If an InterruptedException
is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt()
method. The wait method detects that and throws an InterruptedException
so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.
If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException
clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// code for stopping current task so thread stops
}
Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.
What might be better is to add this:
} catch (InterruptedException e) {
throw new RuntimeException("Unexpected interrupt", e);
}
...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.
Selected response is correct, but someone like me, may have issues with async validation with sending request to the server-side - button will be not disabled during given request processing, so button will blink, which looks pretty strange for the users.
To void this, you just need to handle $pending state of the form:
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid || myForm.$pending">Save</button>
</form>
If you need the exact functionality of the back button in your custom button, why not just call yourActivity.onBackPressed() that way if you override the functionality of the backbutton your custom button will behave the same.
To address the question
How to use Apple's new San Francisco font on a webpage
font-family: -apple-system, system-ui, BlinkMacSystemFont;
or (even shorter):
font-family: -apple-system, BlinkMacSystemFont;
should suffice.
If you want to default to system font on multiple platforms, though, I'd suggest:
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, Ubuntu;
-apple-system
— San Francisco in Safari (on Mac OS X and iOS); Neue Helvetica and Lucida Grande on older versions of Mac OS X.system-ui
— default UI font on a given platform.BlinkMacSystemFont
— equivalent of -apple-system
, for Chrome on Mac OS X."Segoe UI"
— Windows (Vista+) and Windows Phone.Roboto
— Android (Ice Cream Sandwich (4.0)+) and Chrome OS.Ubuntu
— all versions of Ubuntu.The idea is borrowed from the following issue on github.
You can look up fonts for other OS or older versions of them in this article on css-tricks.
I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.
However, I noticed that .Wait() is working properly inside the void method.
and since async void and void have the same signature, you might need to do the following.
void LoadBlahBlah()
{
blah().Wait(); //this blocks
}
Confusingly enough async/await does not block on the next code.
async void LoadBlahBlah()
{
await blah(); //this does not block
}
When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks
this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.
So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.
hopefully my rambling makes sense to anybody also looking for answers.
Edit: I made some example code and decompiled it to see what is actually going on.
static async void Test()
{
await Task.Delay(5000);
}
static async Task TestAsync()
{
await Task.Delay(5000);
}
Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)
private static void Test()
{
<Test>d__1 stateMachine = new <Test>d__1();
stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
<TestAsync>d__2 stateMachine = new <TestAsync>d__2();
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.
meaning without the returning Task, there would be no way to check if it is complete.
as expected, it only starts the Task running async, and then it continues in the code. and the async Task, first it starts the Task, and then it returns it.
so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.
"Vanilla JS” is an expression that got popular after the publishing of a satire website in 2012 (http://vanilla-js.com/). There’s a section covering its story/meaning in this post.
So why the joke? It kind of came as a modern response to the old school knee-jerk reflex of relying on jQuery and additional JS libraries. With the ECMAScript spec and modern browsers capabilities, the need to bypass plain JS with external libraries to maintain consistency across browsers just isn’t there anymore. Here’s a site that shows you how true this is with concrete examples: http://youmightnotneedjquery.com/
private void ShowRowNumber(DataGridView dataGridView)
{
dataGridView.RowHeadersWidth = 50;
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
dataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
}
As stated in this blog post it seems possible to use mod_security to implement a rate limit per second.
The configuration is something like this:
SecRuleEngine On
<LocationMatch "^/somepath">
SecAction initcol:ip=%{REMOTE_ADDR},pass,nolog
SecAction "phase:5,deprecatevar:ip.somepathcounter=1/1,pass,nolog"
SecRule IP:SOMEPATHCOUNTER "@gt 60" "phase:2,pause:300,deny,status:509,setenv:RATELIMITED,skip:1,nolog"
SecAction "phase:2,pass,setvar:ip.somepathcounter=+1,nolog"
Header always set Retry-After "10" env=RATELIMITED
</LocationMatch>
ErrorDocument 509 "Rate Limit Exceeded"
Using Java 8, you can simply use ncopies
of Collections
class:
Object[] arrays = Collections.nCopies(size, object).stream().toArray();
In your case it will be:
Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.
Here is a detailed answer of a similar case of yours.
If you really mean any and ASCII (not e.g. all Unicode characters):
xxx[\x00-\x7F]+xxx
JavaScript example:
var re = /xxx[\x00-\x7F]+xxx/;
re.test('xxxabcxxx')
// true
re.test('xxx???xxx')
// false
It's wrong because (in the absence of a read error) it enters the loop one more time than the author expects. If there is a read error, the loop never terminates.
Consider the following code:
/* WARNING: demonstration of bad coding technique!! */
#include <stdio.h>
#include <stdlib.h>
FILE *Fopen(const char *path, const char *mode);
int main(int argc, char **argv)
{
FILE *in;
unsigned count;
in = argc > 1 ? Fopen(argv[1], "r") : stdin;
count = 0;
/* WARNING: this is a bug */
while( !feof(in) ) { /* This is WRONG! */
fgetc(in);
count++;
}
printf("Number of characters read: %u\n", count);
return EXIT_SUCCESS;
}
FILE * Fopen(const char *path, const char *mode)
{
FILE *f = fopen(path, mode);
if( f == NULL ) {
perror(path);
exit(EXIT_FAILURE);
}
return f;
}
This program will consistently print one greater than the number of characters in the input stream (assuming no read errors). Consider the case where the input stream is empty:
$ ./a.out < /dev/null
Number of characters read: 1
In this case, feof()
is called before any data has been read, so it returns false. The loop is entered, fgetc()
is called (and returns EOF
), and count is incremented. Then feof()
is called and returns true, causing the loop to abort.
This happens in all such cases. feof()
does not return true until after a read on the stream encounters the end of file. The purpose of feof()
is NOT to check if the next read will reach the end of file. The purpose of feof()
is to determine the status of a previous read function
and distinguish between an error condition and the end of the data stream. If fread()
returns 0, you must use feof
/ferror
to decide whether an error occurred or if all of the data was consumed. Similarly if fgetc
returns EOF
. feof()
is only useful after fread has returned zero or fgetc
has returned EOF
. Before that happens, feof()
will always return 0.
It is always necessary to check the return value of a read (either an fread()
, or an fscanf()
, or an fgetc()
) before calling feof()
.
Even worse, consider the case where a read error occurs. In that case, fgetc()
returns EOF
, feof()
returns false, and the loop never terminates. In all cases where while(!feof(p))
is used, there must be at least a check inside the loop for ferror()
, or at the very least the while condition should be replaced with while(!feof(p) && !ferror(p))
or there is a very real possibility of an infinite loop, probably spewing all sorts of garbage as invalid data is being processed.
So, in summary, although I cannot state with certainty that there is never a situation in which it may be semantically correct to write "while(!feof(f))
" (although there must be another check inside the loop with a break to avoid a infinite loop on a read error), it is the case that it is almost certainly always wrong. And even if a case ever arose where it would be correct, it is so idiomatically wrong that it would not be the right way to write the code. Anyone seeing that code should immediately hesitate and say, "that's a bug". And possibly slap the author (unless the author is your boss in which case discretion is advised.)
simple use remove() function. and pass object as param u want to remove. ur arraylist.remove(obj)
Are you opening the file with mode of 'a' instead of 'w'?
See Reading and Writing Files in the python docs
7.2. Reading and Writing Files
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).
>>> f = open('workfile', 'w') >>> print f <open file 'workfile', mode 'w' at 80a0960>
The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
I have tended in the past to work on my functions in two stages. The first stage would be to treat them as fairly normal SQL queries and make sure that I am getting the right results out of it. After I am confident that it is performing as desired, then I would convert it into a UDF.
Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control
Aria does not change anything visually. (Aria is scared of designers too).
aria-hidden:
aria-hidden attribute is used to hide content for visually impaired users who navigate through application using screen readers (JAWS, NVDA,...).
aria-hidden attribute is used with values true, false.
How To Use:
<i class = "fa fa-books" aria-hidden = "true"></i>
using aria-hidden = "true" on the <i>
hides content to screen reader users with no visual change in the application.
aria-label
aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users
How To Use:
<input type = "edit" aria-label = "search" placeholder = "search">
There is no visual change in application. But screen readers can understand the purpose of control
aria-labelledby
Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually
Approach 1:
<span id = "sd"> Search </span>
<input type = "text" aria-labelledby = "sd">
aria-labelledby can also be used to combine two labels for screen reader users
Approach 2:
<span id = "de"> Billing Address </span>
<span id = "sd"> First Name </span>
<input type = "text" aria-labelledby = "de sd">
Another brute force solution could be,
String input = "thequickbrownfoxjumps";
int n = input.length()/4;
String[] num = new String[n];
for(int i = 0, x=0, y=4; i<n; i++){
num[i] = input.substring(x,y);
x += 4;
y += 4;
System.out.println(num[i]);
}
Where the code just steps through the string with substrings
To use copying with xargs
to directories using wildcards on Mac OS, the only solution that worked for me with spaces in the directory name is:
find ./fs*/* -type d -print0 | xargs -0 -n 1 cp test
Where test
is the file to copy
And ./fs*/*
the directories to copy to
The problem is that xargs sees spaces as a new argument, the solutions to change the delimiter character using -d
or -E
is unfortunately not properly working on Mac OS.
You can also do it like this:
BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);
Prints:
A+B+C= 60000000000
After compiling a few answers, I've come up with the following code. What surprised me was that the timer does not get frozen on a PC (Chrome, FF) or Android Chrome - the trigger worked in the background, and the visibility check was the only reliable info.
var timestamp = new Date().getTime();
var timerDelay = 5000;
var processingBuffer = 2000;
var redirect = function(url) {
//window.location = url;
log('ts: ' + timestamp + '; redirecting to: ' + url);
}
var isPageHidden = function() {
var browserSpecificProps = {hidden:1, mozHidden:1, msHidden:1, webkitHidden:1};
for (var p in browserSpecificProps) {
if(typeof document[p] !== "undefined"){
return document[p];
}
}
return false; // actually inconclusive, assuming not
}
var elapsedMoreTimeThanTimerSet = function(){
var elapsed = new Date().getTime() - timestamp;
log('elapsed: ' + elapsed);
return timerDelay + processingBuffer < elapsed;
}
var redirectToFallbackIfBrowserStillActive = function() {
var elapsedMore = elapsedMoreTimeThanTimerSet();
log('hidden:' + isPageHidden() +'; time: '+ elapsedMore);
if (isPageHidden() || elapsedMore) {
log('not redirecting');
}else{
redirect('appStoreUrl');
}
}
var log = function(msg){
document.getElementById('log').innerHTML += msg + "<br>";
}
setTimeout(redirectToFallbackIfBrowserStillActive, timerDelay);
redirect('nativeApp://');
This works:
var form = $(this).closest('form');
form = form.serializeArray();
form = form.concat([
{name: "customer_id", value: window.username},
{name: "post_action", value: "Update Information"}
]);
$.post('/change-user-details', form, function(d) {
if (d.error) {
alert("There was a problem updating your user details")
}
});
Place your script
inside the body tag
<body>
// Rest of html
<script>
function hideButton() {
$(".loading").hide();
}
function showButton() {
$(".loading").show();
}
</script>
< /body>
If you check this JSFIDDLE and click on javascript, you will see the load Type body
is selected
you can store the Path into string variable like
string s = choofdlog.FileName;
Using just jQuery
, vanilla Javascript
, and the table2CSV
library:
export-to-html-table-as-csv-file-using-jquery
Put this code into a script to be loaded in the head
section:
$(document).ready(function () {
$('table').each(function () {
var $table = $(this);
var $button = $("<button type='button'>");
$button.text("Export to spreadsheet");
$button.insertAfter($table);
$button.click(function () {
var csv = $table.table2CSV({
delivery: 'value'
});
window.location.href = 'data:text/csv;charset=UTF-8,'
+ encodeURIComponent(csv);
});
});
})
Notes:
Requires jQuery and table2CSV: Add script references to both libraries before the script above.
The table
selector is used as an example, and can be adjusted to suit your needs.
It only works in browsers with full Data URI
support: Firefox, Chrome and Opera, not in IE, which only supports Data URIs
for embedding binary image data into a page.
For full browser compatibility you would have to use a slightly different approach that requires a server side script to echo
the CSV.
It cannot be done. It is impossible.
I don't think that solution would work anyways because you will see some error message in your error log file.
The solution was a lot easier than what I thought.
simply, open the following path to your php5-fpm
sudo nano /etc/php5/fpm/pool.d/www.conf
or if you're the admin 'root'
nano /etc/php5/fpm/pool.d/www.conf
Then find this line and uncomment it:
listen.allowed_clients = 127.0.0.1
This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks
like this: fastcgi_pass 127.0.0.1:9000;
after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm
Php5-fpm
sudo service php5-fpm restart
or
sudo service php5-fpm reload
Nginx
sudo service nginx restart
or
sudo service nginx reload
From the comments:
Also comment
;listen = /var/run/php5-fpm.sock
and add
listen = 9000
Kafka stores all the information in zookeeper. You can see all the topic related information under brokers->topics. If you wish to get all the topics programmatically you can do that using Zookeeper API.
It is explained in detail in below links Tutorialspoint, Zookeeper Programmer guide
I used pisswillis's answer for a long time.
csview()
{
local file="$1"
sed "s/,/\t/g" "$file" | less -S
}
But then combined some code I found at http://chrisjean.com/2011/06/17/view-csv-data-from-the-command-line which works better for me:
csview()
{
local file="$1"
cat "$file" | sed -e 's/,,/, ,/g' | column -s, -t | less -#5 -N -S
}
The reason it works better for me is that it handles wide columns better.
this will also work
data.groupby(data['date'].dt.year)
By using NULL
without any quotes.
UPDATE `tablename` SET `fieldName` = NULL;
A scenario which I sometimes run into:
Assume you have a trunk, from which you created a release branch. After some changes on trunk (in particular creating "some-dir" directory), you create a feature/fix branch which you want later merge into release branch as well (because changes were small enough and the feature/fix is important for release).
trunk -- ... -- create "some-dir" -- ...
\ \-feature/fix branch
\- release branch
If you then try to merge the feature/fix branch directly into the release branch you will get a tree conflict (even though the directory did not even exist in feature/fix branch):
svn status
! C some-dir
> local missing or deleted or moved away, incoming file edit upon merge
So you need to explicitly merge the commits which were done on trunk before creating feature/fix branch which created the "some-dir" directory before merging the feature/fix branch.
I often forget that as that is not necessary in git.
json.dump(data, open('data.txt', 'wb'))
Applies to Ubuntu and Linux Mint
In the archive:
sudo nano .bashrc
Add to the end:
export ANDROID_HOME=${HOME}/Android/Sdk
export PATH=${PATH}:${ANDROID_HOME}/platform-tools:${ANDROID_HOME}/tools
Restart the terminal and doing: echo $ HOME or $ PATH, you can know these variables.
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
#pragma mark - NSSecureCoding
The main purpose of "pragma" is for developer reference.
You can easily find a method/Function in a vast thousands of coding lines.
Xcode 11+:
Marker Line in Top
// MARK: - Properties
Marker Line in Top and Bottom
// MARK: - Properties -
Marker Line only in bottom
// MARK: Properties -
You can run npx webpack
. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package.
Source of info: https://webpack.js.org/guides/getting-started/
The confusion is understandable, since the two words sound similar, and since the concepts are often closely related and used together. Also, as mentioned, the commonly used abbreviation Auth doesn't help.
Others have already described well what authentication and authorization mean. Here's a simple rule to help keep the two clearly apart:
- Authentication validates your Identity (or authenticity, if you prefer that)
- Authorization validates your authority, i.e. your right to access and possibly change something.
Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage())
;
I use this function :
<?php
function is_ping_address($ip) {
exec('ping -c1 -w1 '.$ip, $outcome, $status);
preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
return ( $arr[1] == 100 ) ? false : true;
}
To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.
Tested on PostgreSQL 9.5 :
-- only digits
select * from books where title ~ '^[0-9]*$';
or,
select * from books where title SIMILAR TO '[0-9]*';
-- start with digit
select * from books where title ~ '^[0-9]+';
There should be no single quotes here . Single quotes are for string literals: 'A'
'some value'
.
Either use double quotes to preserve the upper case spelling of "A":
CREATE TABLE "A" ...
Or don't use quotes at all:
CREATE TABLE A ...
which is identical to
CREATE TABLE a ...
because all unquoted identifiers are folded to lower case automatically in PostgreSQL.
You could avoid problems with the index name completely by using simpler syntax:
CREATE TABLE csd_relationship (
csd_relationship_id serial PRIMARY KEY,
type_id integer NOT NULL,
object_id integer NOT NULL
);
Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.
You can also add a CALayer to the button - you can do lots of things with these including a color overlay, this example uses a plain color layer you can also easily graduate the colour. Be aware though added layers obscure those underneath
+(void)makeButtonColored:(UIButton*)button color1:(UIColor*) color
{
CALayer *layer = button.layer;
layer.cornerRadius = 8.0f;
layer.masksToBounds = YES;
layer.borderWidth = 4.0f;
layer.opacity = .3;//
layer.borderColor = [UIColor colorWithWhite:0.4f alpha:0.2f].CGColor;
CAGradientLayer *colorLayer = [CAGradientLayer layer];
colorLayer.cornerRadius = 8.0f;
colorLayer.frame = button.layer.bounds;
//set gradient colors
colorLayer.colors = [NSArray arrayWithObjects:
(id) color.CGColor,
(id) color.CGColor,
nil];
//set gradient locations
colorLayer.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:1.0f],
nil];
[button.layer addSublayer:colorLayer];
}
Try this way, allow you even filter by other key
data:
var my_data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}];
usage:
//We do that to ensure to get a correct JSON
var my_json = JSON.stringify(my_data)
//We can use {'name': 'Lenovo Thinkpad 41A429ff8'} as criteria too
var filtered_json = find_in_object(JSON.parse(my_json), {website: 'yahoo'});
filter function
function find_in_object(my_object, my_criteria){
return my_object.filter(function(obj) {
return Object.keys(my_criteria).every(function(c) {
return obj[c] == my_criteria[c];
});
});
}
DataTable dt=new DataTable();
Datacolumn Name = new DataColumn("Name");
Name.DataType= typeoff(string);
Name.AllowDBNull=false; //set as null or not the default is true i.e null
Name.MaxLength=20; //sets the length the default is -1 which is max(no limit)
dt.Columns.Add(Name);
Datacolumn Age = new DataColumn("Age", typeoff(int));`
dt.Columns.Add(Age);
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad Adem"; // or dr[0]="Mohammad Adem";
dr["Age"]=33; // or dr[1]=33;
dt.add.rows(dr);
dr=dt.NewRow();
dr["Name"]="Zahara"; // or dr[0]="Zahara";
dr["Age"]=22; // or dr[1]=22;
dt.rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();
Full working 36 when SCL is not available (based on Joys input)
yum install wget –y
wget https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-11.noarch.rpm
rpm –ivh epel-*.rpm
yum install python36
sudo yum install python34-setuptools
sudo mkdir /usr/local/lib/python3.6
sudo mkdir /usr/local/lib/python3.6/site-packages
sudo easy_install-3.6 pip
Finally activate the environment...
pyvenv-3.6 py3
source py3/bin/activate
Then python3
Try using second parameter for json_decode function:
$json = json_decode(file_get_contents($file), true);
You're mixing if statement with a ternary expression, that's why you're having a syntax error. It might be easier for you to understand what's going on if you extract mapping function outside of your render method:
renderItem = (id) => {
// just standard if statement
if (this.props.schema.collectionName.length < 0) {
return (
<Expandable>
<ObjectDisplay
key={id}
parentDocumentId={id}
schema={schema[this.props.schema.collectionName]}
value={this.props.collection.documents[id]}
/>
</Expandable>
);
}
return (
<h1>hejsan</h1>
);
}
Then just call it when mapping:
render() {
return (
<div>
<div className="box">
{
this.props.collection.ids
.filter(
id =>
// note: this is only passed when in top level of document
this.props.collection.documents[id][
this.props.schema.foreignKey
] === this.props.parentDocumentId
)
.map(this.renderItem)
}
</div>
</div>
)
}
Of course, you could have used the ternary expression as well, it's a matter of preference. What you use, however, affects the readability, so make sure to check different ways and tips to properly do conditional rendering in react and react native.
How You can add 5 columns grid in bootstrap
.col-lg-1-5,.col-md-1-5,.col-sm-1-5,.col-xs-1-5{min-height:1px;padding-left:15px;padding-right:15px;position:relative; width:100%;box-sizing:border-box;}_x000D_
.item{width:100%;height:100px; background-color:#cfcfcf;}_x000D_
.col-xs-1-5{width: 20%;float:left;} }_x000D_
_x000D_
@media (min-width: 767px){ .col-sm-1-5{width: 20%;float:left;} }_x000D_
@media (min-width: 992px){ .col-md-1-5{width: 20%;float:left;} }_x000D_
@media (min-width: 1200px){ .col-lg-1-5{width: 20%;float:left;} }
_x000D_
<div class="row">_x000D_
<div class="col-sm-1-5">_x000D_
<div class="item">Item 1</div>_x000D_
</div>_x000D_
<div class="col-sm-1-5">_x000D_
<div class="item">Item 2</div>_x000D_
</div>_x000D_
<div class="col-sm-1-5">_x000D_
<div class="item">Item 3</div>_x000D_
</div>_x000D_
<div class="col-sm-1-5">_x000D_
<div class="item">Item 4</div>_x000D_
</div>_x000D_
<div class="col-sm-1-5">_x000D_
<div class="item">Item 5</div>_x000D_
</div>_x000D_
</div>
_x000D_
yes, but you need to open the global search panel. to do so, press the binoculars icon on the top right corner of the IDE.
you can even filter searches by function identifiers, method scopes an etc...
It depends on what you want to do.
Case # 1: Save the model to use it yourself for inference: You save the model, you restore it, and then you change the model to evaluation mode. This is done because you usually have BatchNorm
and Dropout
layers that by default are in train mode on construction:
torch.save(model.state_dict(), filepath)
#Later to restore:
model.load_state_dict(torch.load(filepath))
model.eval()
Case # 2: Save model to resume training later: If you need to keep training the model that you are about to save, you need to save more than just the model. You also need to save the state of the optimizer, epochs, score, etc. You would do it like this:
state = {
'epoch': epoch,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
...
}
torch.save(state, filepath)
To resume training you would do things like: state = torch.load(filepath)
, and then, to restore the state of each individual object, something like this:
model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])
Since you are resuming training, DO NOT call model.eval()
once you restore the states when loading.
Case # 3: Model to be used by someone else with no access to your code:
In Tensorflow you can create a .pb
file that defines both the architecture and the weights of the model. This is very handy, specially when using Tensorflow serve
. The equivalent way to do this in Pytorch would be:
torch.save(model, filepath)
# Then later:
model = torch.load(filepath)
This way is still not bullet proof and since pytorch is still undergoing a lot of changes, I wouldn't recommend it.
You can do it using a unicode character also
System.out.print('\u0022' + "Hello" + '\u0022');
wmic product get name
Just gets the cmd stuck... still flashing _ after a couple minutes
in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
, if you can find the folder with the software name you are trying to install (not the one named with ProductCode), the UninstallString points to the application's own uninstaller C:\Program Files\Zune\ZuneSetup.exe /x
Here is complete answer for Angular 6+ based on @ryanrain answer:
From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.
Let's suppose you add your json files into "your-json-dir" directory:
add "your-json-dir" into angular.json file (:
"assets": [
"src/assets",
"src/your-json-dir"
]
create or edit typings.d.ts file (at your project root) and add the following content:
declare module "*.json" {
const value: any;
export default value;
}
This will allow import of ".json" modules without typescript error.
in your controller/service/anything else file, simply import the file by using this relative path:
import * as myJson from 'your-json-dir/your-json-file.json';
You can use a TableModel
.
Define a class like this:
public class MyModel extends AbstractTableModel{
//not necessary
}
actually isCellEditable()
is false
by default so you may omit it. (see: http://docs.oracle.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html)
Then use the setModel()
method of your JTable
.
JTable myTable = new JTable();
myTable.setModel(new MyModel());
For Windows and Python 3.x, my two cents contribution about renaming the file on download :
pip install wget
import wget
wget.download('Url', 'C:\\PathToMyDownloadFolder\\NewFileName.extension')
Truely working command line example :
python -c "import wget; wget.download(""https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.17.2.tar.xz"", ""C:\\Users\\TestName.TestExtension"")"
Note : 'C:\\PathToMyDownloadFolder\\NewFileName.extension' is not mandatory. By default, the file is not renamed, and the download folder is your local path.
{{ data.0 }}
should work.
Let's say you wrote data.obj
django tries data.obj
and data.obj()
. If they don't work it tries data["obj"]
. In your case data[0]
can be written as {{ data.0 }}
. But I recommend you to pull data[0]
in the view and send it as separate variable.
In React, when you want to pass an interpreted expression, you have to open a pair of curly braces. Try:
render () {
return (
<button className={`pill ${ this.props.styleName }`}>
{this.props.children}
</button>
);
}
Using the classnames npm package
import classnames from 'classnames';
render() {
return (
<button className={classnames('pill', this.props.styleName)}>
{this.props.children}
</button>
);
}
All the other answers are sufficient but for a large project like ours and where navigations are being made both in code and storyboard, it is quite a daunting task.
For those who are actively using Storyboard. This is my advice: use Regex.
The following format is not good for full screen pages:
<segue destination="Bof-iQ-svK" kind="presentation" identifier="importSystem" modalPresentationStyle="fullScreen" id="bfy-FP-mlc"/>
The following format is good for full screen pages:
<segue destination="7DQ-Kj-yFD" kind="presentation" identifier="defaultLandingToSystemInfo" modalPresentationStyle="fullScreen" id="Mjn-t2-yxe"/>
The following regex compatible with VS CODE will convert all Old Style pages to new style pages. You may need to escape special chars if you're using other regex engines/text editors.
Search Regex
<segue destination="(.*)"\s* kind="show" identifier="(.*)" id="(.*)"/>
Replace Regex
<segue destination="$1" kind="presentation" identifier="$2" modalPresentationStyle="fullScreen" id="$3"/>
If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query).
var exceptionList = new List<string> { "exception1", "exception2" };
var query = myEntities.MyEntity
.Select(e => e.Name)
.Where(e => !exceptionList.Contains(e.Name));
If you're excluding based on another database query using Except
might be a better choice. (Here is a link to the supported Set extensions in LINQ to Entities)
var exceptionList = myEntities.MyOtherEntity
.Select(e => e.Name);
var query = myEntities.MyEntity
.Select(e => e.Name)
.Except(exceptionList);
This assumes a complex entity in which you are excluding certain ones depending some property of another table and want the names of the entities that are not excluded. If you wanted the entire entity, then you'd need to construct the exceptions as instances of the entity class such that they would satisfy the default equality operator (see docs).
I have worked with many digital storage systems and they all store digital objects on the file system. They tend to use a branch approach, so there will be an archive tree on the file system, often starting with year of entry e.g. 2009, subdirectory will be month e.g. 8 for August, next directory will be day e.g. 11 and sometimes they will use hour as well, the file will then be named with the records persistent ID. Using BLOBS has its advantages and I have heard of it being used often in the IT parts of the chemical industry for storing thousands or millions of photographs and diagrams. It can provide more granular security, a single method of backup, potentially better data integrity and improved inter media searching, Oracle has many features for this within the package they used to call Intermedia (I think it is called something else now). The file system can also have granular security provided through a system such as XACML or another XML type security object. See D Space of Fedora Object Store for examples.
Real solution for it case:
android:layout_weight="1"
for TextView, and your button move to right!
You can use format like here,
public static double getDoubleValue(String value,int digit){
if(value==null){
value="0";
}
double i=0;
try {
DecimalFormat digitformat = new DecimalFormat("#.##");
digitformat.setMaximumFractionDigits(digit);
return Double.valueOf(digitformat.format(Double.parseDouble(value)));
} catch (NumberFormatException numberFormatExp) {
return i;
}
}
I've added a time check to my forms. The forms will not be submitted if filled in less than 3 seconds and this was working great for me especially for the long forms. Here's the form check function that I call on the submit button
function formCheck(){
var timeStart;
var timediff;
$("input").bind('click keyup', function () {
timeStart = new Date().getTime();
});
timediff= Math.round((new Date().getTime() - timeStart)/1000);
if(timediff < 3) {
//throw a warning or don't submit the form
}
else submit(); // some submit function
}
When a process uses fork(), it creates a duplicate copy of itself and this duplicates becomes the child of the process. The fork() is implemented using clone() system call in linux which returns twice from kernel.
Let’s understand this with an example:
pid = fork();
// Both child and parent will now start execution from here.
if(pid < 0) {
//child was not created successfully
return 1;
}
else if(pid == 0) {
// This is the child process
// Child process code goes here
}
else {
// Parent process code goes here
}
printf("This is code common to parent and child");
In the example, we have assumed that exec() is not used inside the child process.
But a parent and child differs in some of the PCB(process control block) attributes. These are:
But what about the child memory? Is a new address space created for a child?
The answers in no. After the fork(), both parent and child share the memory address space of parent. In linux, these address space are divided into multiple pages. Only when the child writes to one of the parent memory pages, a duplicate of that page is created for the child. This is also known as copy on write(Copy parent pages only when the child writes to it).
Let’s understand copy on write with an example.
int x = 2;
pid = fork();
if(pid == 0) {
x = 10;
// child is changing the value of x or writing to a page
// One of the parent stack page will contain this local variable. That page will be duplicated for child and it will store the value 10 in x in duplicated page.
}
else {
x = 4;
}
But why is copy on write necessary?
A typical process creation takes place through fork()-exec() combination. Let’s first understand what exec() does.
Exec() group of functions replaces the child’s address space with a new program. Once exec() is called within a child, a separate address space will be created for the child which is totally different from the parent’s one.
If there was no copy on write mechanism associated with fork(), duplicate pages would have created for the child and all the data would have been copied to child’s pages. Allocating new memory and copying data is a very expensive process(takes processor’s time and other system resources). We also know that in most cases, the child is going to call exec() and that would replace the child’s memory with a new program. So the first copy which we did would have been a waste if copy on write was not there.
pid = fork();
if(pid == 0) {
execlp("/bin/ls","ls",NULL);
printf("will this line be printed"); // Think about it
// A new memory space will be created for the child and that memory will contain the "/bin/ls" program(text section), it's stack, data section and heap section
else {
wait(NULL);
// parent is waiting for the child. Once child terminates, parent will get its exit status and can then continue
}
return 1; // Both child and parent will exit with status code 1.
Why does parent waits for a child process?
Why is exec() system call necessary?
It’s not necessary to use exec() with fork(). If the code that the child will execute is within the program associated with parent, exec() is not needed.
But think of cases when the child has to run multiple programs. Let’s take the example of shell program. It supports multiple commands like find, mv, cp, date etc. Will be it right to include program code associated with these commands in one program or have child load these programs into the memory when required?
It all depends on your use case. You have a web server which given an input x that returns the 2^x to the clients. For each request, the web server creates a new child and asks it to compute. Will you write a separate program to calculate this and use exec()? Or you will just write computation code inside the parent program?
Usually, a process creation involves a combination of fork(), exec(), wait() and exit() calls.
Try using jQuery.parseJSON when you get the data back.
type: "POST",
dataType: "json",
url: url,
data: { get_member: id },
success: function(data) {
response = jQuery.parseJSON(data);
$("input[ name = type ]:eq(" + response.type + " )")
.attr("checked", "checked");
$("input[ name = name ]").val( response.name);
$("input[ name = fname ]").val( response.fname);
$("input[ name = lname ]").val( response.lname);
$("input[ name = email ]").val( response.email);
$("input[ name = phone ]").val( response.phone);
$("input[ name = website ]").val( response.website);
$("#admin_member_img")
.attr("src", "images/member_images/" + response.image);
},
error: function(error) {
alert(error);
}
$filterQuery = $this->queryFactory->create(QueryInterface::TYPE_BOOL, ['must' => $queries,'should'=>$queriesGeo]);
In must
you need to add the query condition array which you want to work with AND
and in should
you need to add the query condition which you want to work with OR
.
You can check this: https://github.com/Smile-SA/elasticsuite/issues/972
In my case, I change a lot an specific JS file and I need it to be in its last version in all browsers where is being used.
I do not have a specific version number for this file, so I simply hash the current date and time (hour and minute) and pass it as the version number:
<script src="/js/panel/app.js?v={{ substr(md5(date("Y-m-d_Hi")),10,18) }}"></script>
I need it to be loaded every minute, but you can decide when it should be reloaded.
in laravel used decimal column type for migration
$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);
for more information see available column type
You can also use echo
to remove blank spaces, either at the beginning or at the end of the string, but also repeating spaces inside the string.
$ myVar=" kokor iiij ook "
$ echo "$myVar"
kokor iiij ook
$ myVar=`echo $myVar`
$
$ # myVar is not set to "kokor iiij ook"
$ echo "$myVar"
kokor iiij ook
check it
const mq = window.matchMedia( "(min-width: 500px)" );
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json)
. my_json_object
in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.
The way I ended up solving it: the write_to_file.json
will have everything up to the bytes object that is causing the issue.
In my particular case this was a line obtained through
for line in text:
json_object['line'] = line.strip()
I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:
for line in text:
json_object['line'] = line.strip().decode()
It must work. I used to debug a .exe file and a dll at the same time ! What I suggest is 1) Include the path of the dll in your B project, 2) Then compile in debug your A project 3) Control that the path points on the A dll and de pdb file.... 4)After that you start in debug the B project and if all is ok, you will be able to debug in both projects !
Logical nullish assignment (??=)
The main idea is still using Array#reduce()
to aggregate with output as object
to get the highest performance (both time and space complexity) in terms of searching
& construct bunches of intermediate arrays
like other answers.
const arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];
const result = arr.reduce((acc, curr) => {
acc[curr] ??= {[curr]: 0};
acc[curr][curr]++;
return acc;
}, {});
console.log(Object.values(result));
_x000D_
It is enough to use in your xml file.
android:singleLine="false".
Hope it will work.
All the best!
If you haven't found out yet, you can use the amazing screen plugin.
Conque is also exceptional but I find screen much more practical (it wont "litter" your buffer for example and you can just send the commands that you really want after editing them in your buffer)
xml:space="preserve"
has to work for all compliant XML parsers.
However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br />
(X)HTML tag, maybe this is the problem which you are facing.
You can also add
and/or
to insert CR/LF characters.
In case you're looking for a more modern way to check to see if a service is running (this will not work for just any old process), then systemctl might be what you're looking for.
Here's the basic command:
systemctl show --property=ActiveState your_service_here
Which will yield very simple output (one of the following two lines will appear depending on whether the service is running or not running):
ActiveState=active
ActiveState=inactive
And if you'd like to know all of the properties you can get:
systemctl show --all your_service_here
If you prefer that alphabetized:
systemctl show --all your_service_here | sort
And the full code to act on it:
service=$1
result=`systemctl show --property=ActiveState $service`
if [[ "$result" == 'ActiveState=active' ]]; then
echo "$service is running" # Do something here
else
echo "$service is not running" # Do something else here
fi
Recommended as an answer:
Here's a solution using es2015 generators:
function* subsetSum(numbers, target, partial = [], partialSum = 0) {
if(partialSum === target) yield partial
if(partialSum >= target) return
for(let i = 0; i < numbers.length; i++){
const remaining = numbers.slice(i + 1)
, n = numbers[i]
yield* subsetSum(remaining, target, [...partial, n], partialSum + n)
}
}
Using generators can actually be very useful because it allows you to pause script execution immediately upon finding a valid subset. This is in contrast to solutions without generators (ie lacking state) which have to iterate through every single subset of numbers
Both functions are wrong. First of all function initNode
has a confusing name. It should be named as for example initList
and should not do the task of addNode. That is, it should not add a value to the list.
In fact, there is not any sense in function initNode, because the initialization of the list can be done when the head is defined:
Node *head = nullptr;
or
Node *head = NULL;
So you can exclude function initNode
from your design of the list.
Also in your code there is no need to specify the elaborated type name for the structure Node
that is to specify keyword struct before name Node
.
Function addNode
shall change the original value of head. In your function realization you change only the copy of head passed as argument to the function.
The function could look as:
void addNode(Node **head, int n)
{
Node *NewNode = new Node {n, *head};
*head = NewNode;
}
Or if your compiler does not support the new syntax of initialization then you could write
void addNode(Node **head, int n)
{
Node *NewNode = new Node;
NewNode->x = n;
NewNode->next = *head;
*head = NewNode;
}
Or instead of using a pointer to pointer you could use a reference to pointer to Node. For example,
void addNode(Node * &head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
}
Or you could return an updated head from the function:
Node * addNode(Node *head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
return head;
}
And in main
write:
head = addNode(head, 5);
import java.util.ArrayList;
import java.util.List;
class ArrLst{
public static void main(String args[]){
List l=new ArrayList();
l.add(10);
l.add(11);
l.add(12);
l.add(13);
l.add(14);
l.forEach((a)->System.out.println(a));
}
}
For Microsoft Access
UPDATE TableA A
INNER JOIN TableB B
ON A.ID = B.ID
SET A.Name = B.Name
You're looking for a non-greedy (or lazy) match. To get a non-greedy match in regular expressions you need to use the modifier ?
after the quantifier. For example you can change .*
to .*?
.
By default grep
doesn't support non-greedy modifiers, but you can use grep -P
to use the Perl syntax.
You cannot simply assign value to a character in the string. Use this method to replace value of a particular character:
name = "India"
result=name .replace("d",'*')
Output: In*ia
Also, if you want to replace say * for all the occurrences of the first character except the first character, eg. string = babble output = ba**le
Code:
name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
This will do:
/^(apple|banana)$/
to exclude from captured strings (e.g. $1
,$2
):
(?:apple|banana)
This suits the requirement:
select username, account_status, EXPIRY_DATE from dba_users where
username='<username>';
Output:
USERNAME ACCOUNT_STATUS EXPIRY_DA
--------------------------------------------------------------------------------
SYSTEM EXPIRED 13-NOV-17
I just tested the code at the bottom and it prints 16384
twice (I'm on Excel 2010) and the first row gets selected. Your problem seems to be somewhere else.
Have you tried to get rid of the selects:
Sheets("BOM").Rows(copyFromRow).Copy
With Sheets("Proposal")
.Paste Destination:=.Rows(copyToRow)
copyToRow = copyToRow + 1
Application.CutCopyMode = False
.Rows(copyToRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End With
Test code to get convinced that the problem does not seem to be what you think it is.
Sub test()
Dim r
Dim i As Long
i = 1
r = Rows(i & ":" & i)
Debug.Print UBound(r, 2)
r = Rows(i)
Debug.Print UBound(r, 2)
Rows(i).Select
End Sub
<style type="text/css">
.stretchedToMargin {
position:absolute;
width:100%;
height:100%;
}
</style>
There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.
When you do something like git add file
you add it to the index. And when you commit it, you add it to the tree as well.
It will probably help you to know the three more common flags in git reset
:
git reset [--
<mode>
] [<commit>
]This form resets the current branch head to
<commit>
and possibly updates the index (resetting it to the tree of<commit>
) and the working tree depending on<mode>
, which must be one of the following:
--softDoes not touch the index file nor the working tree at all (but resets the head to
<commit>
, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.--mixed
Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.
--hard
Resets the index and working tree. Any changes to tracked files in the working tree since
<commit>
are discarded.
Now, when you do something like git reset HEAD
, what you are actually doing is git reset HEAD --mixed
and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add
). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add
was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD
is the exact opposite of git add
.
git rm
, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached
, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add
was used to add a new (previously untracked) file, then git rm --cached
is the exact opposite of git add
(and is pretty much identical to git reset HEAD
).
Git 2.25 introduced a new command for these cases, git restore
, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.
I think the simplest will be
let minutes = Date(timeIntervalSinceNow:(minutes * 60.0))
Your code works for me. When does addSalespersonOption
get called? There may be a problem with that call.
Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:
<select id="salesperson">
<option value="">(select)</option>
</select>
instead of this:
<select id="salesperson" />
<option value"">(select)</option>
</select>
Edit: When does your options list get dynamically populated? Are you sure you are passing 'on'
for the defSales
value in your call to addSalespersonOption
? Try changing that code to this:
if (selected == "on") {
alert('setting default selected option to ' + text);
html = '<option value="'+value+'" selected="selected">'+text+'</option>';
}
and see if the alert happens and what is says if it does happen.
Edit: Working example of my testing (the error:undefined is from jsbin, not my code).
Run the given command
git add . && git commit -m "Changes Committed"
However, even if it seems a single command, It's two separate command runs one by one. Here we just used &&
to combine them. It's not much different than running
git add .
and git commit -m "Changes Committed"
separately. You can run multiple commands together but sequence matters here. How if you want to push the changes to remote server along with staging and commit you can do it as given,
git add . && git commit -m "Changes Committed" && git push origin master
Instead, if you change the sequence and put the push
to first, It will be executed first and does not give desired push after staging and commit just because it already ran first.
&&
runs the second command on the line when the first command comes back successfully, or with an error level of 0. The opposite of &&
is ||
, which runs the second command when the first command is unsuccessful, or with an error level of 1.
Alternatively, you can create alise as git config --global alias.addcommit '!git add -a && git commit -m'
and use it as git addcommit -m "Added and commited new files"
WARNING! THIS WILL DELETE THE ENTIRE GIT HISTORY FOR YOUR SUBMODULE. ONLY DO THIS IF YOU CREATED THE SUBMODULE BY ACCIDENT. CERTAINLY NOT WHAT YOU WANT TO DO IN MOST CASES.
I think you have to go inside week1 folder and delete the .git folder:
sudo rm -Rf .git
then go back to top level folder and do:
git add .
then do a commit and push the code.
Use fs.writeFileSync inside the try/catch block as below.
`var fs = require('fs');
try {
const file = fs.writeFileSync(ASIN + '.json', JSON.stringify(results))
console.log("JSON saved");
return results;
} catch (error) {
console.log(err);
}`
You should take a look at Batarang for AngularJS debugging
As for your issue:
Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show
<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
</div>
</div>
</div>
</div>
<!-- End of Confirmation Dialog -->
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://www.cryptocompare.com/media/19684/doge.png', 'icons/taskks12.png', function(){
console.log('done');
});
Just to demonstrate the flexibility of javascript: you can use a oneliner for this
function padLeft(nr, n, str){
return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5)); //=> '00023'
console.log((23).padLeft(5)); //=> '00023'
console.log((23).padLeft(5,' ')); //=> ' 23'
console.log(padLeft(23,5,'>>')); //=> '>>>>>>23'
If you want to use this for negative numbers also:
Number.prototype.padLeft = function (n,str) {
return (this < 0 ? '-' : '') +
Array(n-String(Math.abs(this)).length+1)
.join(str||'0') +
(Math.abs(this));
}
console.log((-23).padLeft(5)); //=> '-00023'
Alternative if you don't want to use Array
:
number.prototype.padLeft = function (len,chr) {
var self = Math.abs(this)+'';
return (this<0 && '-' || '')+
(String(Math.pow( 10, (len || 2)-self.length))
.slice(1).replace(/0/g,chr||'0') + self);
}
If you are writing code for Node, using Node modules as described by Ivan is without a doubt the way to go.
However, if you need to load JavaScript that has already been written and isn't aware of node, the vm
module is the way to go (and definitely preferable to eval
).
For example, here is my execfile
module, which evaluates the script at path
in either context
or the global context:
var vm = require("vm");
var fs = require("fs");
module.exports = function(path, context) {
var data = fs.readFileSync(path);
vm.runInNewContext(data, context, path);
}
Also note: modules loaded with require(…)
don't have access to the global context.
"Hard Coding" means something that you want to embeded with your program or any project that can not be changed directly. For example if you are using a database server, then you must hardcode to connect your database with your project and that can not be changed by user. Because you have hard coded.
I don't have access to a SQL Server at home, so I'm guess at the syntax here, but it's more or less:
DECLARE @names VARCHAR(500)
SELECT @names = @names + ' ' + Name
FROM Names
SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)
You can use resize like this:
For n = 1 To 5
Columns(n).Resize(, 5).Select
'~~> rest of your code
Next
In any Range Manipulation that you do, always keep at the back of your mind Resize and Offset property.
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).d['a']
, d['b']
changes at same time because they both point to same object.You can try this methods
window.open(location, '_self').close();
IE 6 and 7: 2
IE 8: 6
IE 9: 6
IE 10: 8
IE 11: 8
Firefox 2: 2
Firefox 3: 6
Firefox 4 to 46: 6
Opera 9.63: 4
Opera 10: 8
Opera 11 and 12: 6
Chrome 1 and 2: 6
Chrome 3: 4
Chrome 4 to 23: 6
Safari 3 and 4: 4
source: http://p2p.wrox.com/book-professional-website-performance-optimizing-front-end-back-end-705/
Multiplexed support(one single TCP connection for all requests)
This seems a lot cleaner than the answer above...
<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
</script>
<table id="theTable">
<tr>
<td>id</td>
<td>name</td>
</tr>
<tr id="templateRow" style="display:none">
<td>{id}</td>
<td><input /></td>
</tr>
</table>
<button onclick="addRow();">Go</button>
I am not sure if this has been solved but the best way is to use the WpfAnimatedGid library. It is very easy, simple and straight forward to use. It only requires 2lines of XAML code and about 5 lines of C# Code in the code behind.
You will see all the necessary details of how this can be used there. This is what I also used instead of re-inventing the wheel
hi friend in this case you can use the
AppendDataBound="true"
and after this use the list item. for e.g.:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
but the problem in this is after second time select data are append with old data.
@mogstad has been kind enough to wrap @stephencelis solution in a Cocoapod:
pod 'libCommonCrypto'
The other pods available did not work for me.
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();
Undefined behavior working in your favor. Whatever memory you're clobbering apparently isn't holding anything important. Note that C and C++ do not do bounds checking on arrays, so stuff like that isn't going to be caught at compile or run time.
I had same issue when first start Android Studio in Window 10, with java jdk 1.8.0_66. The solution that worked is:
Step 1: Close Android Studio
Step 2: Delete Folder C:\Users\Anna\.gradle (Anna is my username)
Step 3: Open Android Studio as Administrator
Step 4: If you are currently in an opened project, close current project by select File > Close Project.
Step 5: Now you seeing this Quick Start GUI:
Wait for gradle to build again (it would download all the dependency in your build.gradle for every module in your project)
If it has not worked till now, you could restart your computer. Do step 1 again.
This happens sometime when I changed Android Studio version or recently upgrade Window. Hope that helps !
If you do not want to change the settings or play with command line. There is option to compress the file and upload in phpMyAdmin. It should bring down the size considerably.
One easy non-loop approach would be to use genvarname
to create a cell array of strings:
>> N = 5;
>> f = genvarname(repmat({'f'}, 1, N), 'f')
f =
'f1' 'f2' 'f3' 'f4' 'f5'
The function genvarname
has been deprecated, so matlab.lang.makeUniqueStrings
can be used instead in the following way to get the same output:
>> N = 5;
>> f = strrep(matlab.lang.makeUniqueStrings(repmat({'f'}, 1, N), 'f'), '_', '')
f =
1×5 cell array
'f1' 'f2' 'f3' 'f4' 'f5'
In a Ruby on Rails project by default the root of the HTML source for the server is the public directory. So your link would be:
<img src="images/rss.jpg" alt="rss feed" />
But it is best practice in a Rails project to use the built in helper:
<%= image_tag("rss.jpg", :alt => "rss feed") %>
That will create the correct image link plus if you ever add assert servers, etc it will work with those.
I have the similar problem, but with IntelliJ IDEA + Maven + TestNG + spring-test. (spring-test is essential of course :) ) It was fixed when I've change config of maven-surefire-plugin to disable run tests in parallel. Like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<skipTests>${maven.test.skip}</skipTests>
<trimStackTrace>false</trimStackTrace>
<!--<parallel>methods</parallel>-->
<!-- to skip integration tests -->
<excludes>
<exclude>**/IT*Test.java</exclude>
<exclude>**/integration/*Test.java</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<skipTests>${maven.integration-test.skip}</skipTests>
<!-- Make sure to include this part, since otherwise it is excluding Integration tests -->
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/IT*Test.java</include>
<include>**/integration/*Test.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
One thing I hadn't seen really emphasized here is that modern functional languages such as Haskell really more on first class functions for flow control than explicit recursion. You don't need to define factorial recursively in Haskell, as was done above. I think something like
fac n = foldr (*) 1 [1..n]
is a perfectly idiomatic construction, and much closer in spirit to using a loop than to using explicit recursion.
Please use dataset
var article = document.querySelector('#electriccars'),
data = article.dataset;
// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"
so in your case for setting data:
getElementById('item1').dataset.icon = "base2.gif";
It could be that you don't have privileges to some of the files. From an administrator account, try "sudo rsync -av " Alternately, enable the root account and sign in as root. That should allow you to completely hose your system and brute force your rsync! ;-) I'm not sure if the above mentioned --extended-attributes will help, but I threw it in too, just for good measure.
GET:
with JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://hostname/resource
with XML:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
POST:
For posting data:
curl --data "param1=value1¶m2=value2" http://hostname/resource
For file upload:
curl --form "[email protected]" http://hostname/resource
RESTful HTTP Post:
curl -X POST -d @filename http://hostname/resource
For logging into a site (auth):
curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/
Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.
Code-
if (len(s)<=3):
return s
elif s[-3:]=="ing":
return s+"ly"
else: return s + "ing"
I wanted to elaborate the answer by lifeless a bit because when I started reading about how to use super() in a multiple inheritance hierarchy in Python, I did't get it immediately.
What you need to understand is that super(MyClass, self).__init__()
provides the next __init__
method according to the used Method Resolution Ordering (MRO) algorithm in the context of the complete inheritance hierarchy.
This last part is crucial to understand. Let's consider the example again:
#!/usr/bin/env python2
class First(object):
def __init__(self):
print "First(): entering"
super(First, self).__init__()
print "First(): exiting"
class Second(object):
def __init__(self):
print "Second(): entering"
super(Second, self).__init__()
print "Second(): exiting"
class Third(First, Second):
def __init__(self):
print "Third(): entering"
super(Third, self).__init__()
print "Third(): exiting"
According to this article about Method Resolution Order by Guido van Rossum, the order to resolve __init__
is calculated (before Python 2.3) using a "depth-first left-to-right traversal" :
Third --> First --> object --> Second --> object
After removing all duplicates, except for the last one, we get :
Third --> First --> Second --> object
So, lets follow what happens when we instantiate an instance of the Third
class, e.g. x = Third()
.
Third.__init__
executes.
Third(): entering
super(Third, self).__init__()
executes and MRO returns First.__init__
which is called.First.__init__
executes.
First(): entering
super(First, self).__init__()
executes and MRO returns Second.__init__
which is called.Second.__init__
executes.
Second(): entering
super(Second, self).__init__()
executes and MRO returns object.__init__
which is called.object.__init__
executes (no print statements in the code there)Second.__init__
which then prints Second(): exiting
First.__init__
which then prints First(): exiting
Third.__init__
which then prints Third(): exiting
This details out why instantiating Third() results in to :
Third(): entering
First(): entering
Second(): entering
Second(): exiting
First(): exiting
Third(): exiting
The MRO algorithm has been improved from Python 2.3 onwards to work well in complex cases, but I guess that using the "depth-first left-to-right traversal" + "removing duplicates expect for the last" still works in most cases (please comment if this is not the case). Be sure to read the blog post by Guido!
The values of LENGTH_SHORT
and LENGTH_LONG
are 0 and 1. This means they are treated as flags rather than actual durations so I don't think it will be possible to set the duration to anything other than these values.
If you want to display a message to the user for longer, consider a Status Bar Notification. Status Bar Notifications can be programmatically canceled when they are no longer relevant.
Write Following Code to set padding, it may help you.
TextView ApplyPaddingTextView = (TextView)findViewById(R.id.textView1);
final LayoutParams layoutparams = (RelativeLayout.LayoutParams) ApplyPaddingTextView.getLayoutParams();
layoutparams.setPadding(50,50,50,50);
ApplyPaddingTextView.setLayoutParams(layoutparams);
Use LinearLayout.LayoutParams
or RelativeLayout.LayoutParams
according to parent layout of the child view
I believe this will work:
TextArea.Text = "Line 1" & vbCrLf & "Line 2"
System.Environment.NewLine could be used in place of vbCrLf if you wanted to be a little less VB6 about it.
That helped me with my code.
When I tried feltering only a type of files and show them on screen by adding a condition that tests on each line.
Like this
elif command == 'ls':
print("directory of ", ftp.pwd())
data = []
ftp.dir(data.append)
for line in data:
x = line.split(".")
formats=["gz", "zip", "rar", "tar", "bz2", "xz"]
if x[-1] in formats:
print ("-", line)
If you want to compare two Maps then, below code may help you
(new TreeMap<String, Object>(map1).toString().hashCode()) == new TreeMap<String, Object>(map2).toString().hashCode()
The best way for me was to put it in a hidden div in php blade
<div hidden id="token">{{$token}}</div>
then call it in javascript as a constant to avoid undefined var errors
const token = document.querySelector('div[id=token]').textContent
// console.log(token)
// eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MjNlOTcyMi02N2NmLTQ4M2UtYTk4Mi01YmE5YTI0Y2M2MzMiLCJqdGkiOiI2Y2I1ZGRhNzRhZjNhYTkwNzA3ZjMzMDFiYjBiZDUzNTZjNjYxMGUyZWJlNmYzOTI5NzBmMjNjNDdiNjhjY2FiYjI0ZWVmMzYwZmNiZDBmNyIsImlhdCI6IjE2MDgwODMyNTYuNTE2NjE4IiwibmJmIjoiMTYwODA4MzI1Ni41MTY2MjUiLCJleHAiOiIxNjIzODA4MDU2LjMxMTg5NSIsInN1YiI6IjUiLCJzY29wZXMiOlsiYWRtaW4iXX0.GbKZ8CIjt3otzFyE5aZEkNBCtn75ApIfS6QbnD6z0nxDjycknQaQYz2EGems9Z3Qjabe5PA9zL1mVnycCieeQfpLvWL9xDu9hKkIMs006Sznrp8gWy6JK8qX4Xx3GkzWEx8Z7ZZmhsKUgEyRkqnKJ-1BqC2tTiTBqBAO6pK_Pz7H74gV95dsMiys9afPKP5ztW93kwaC-pj4h-vv-GftXXc6XDnUhTppT4qxn1r2Hf7k-NXE_IHq4ZPb20LRXboH0RnbJgq2JA1E3WFX5_a6FeWJvLlLnGGNOT0ocdNZq7nTGWwfocHlv6pH0NFaKa3hLoRh79d5KO_nysPVCDt7jYOMnpiq8ybIbe3oYjlWyk_rdQ9067bnsfxyexQwLC3IJpAH27Az8FQuOQMZg2HJhK8WtWUph5bsYUU0O2uPG8HY9922yTGYwzeMEdAqBss85jdpMNuECtlIFM1Pc4S-0nrCtBE_tNXn8ATDrm6FecdSK8KnnrCOSsZhR04MvTyznqCMAnKtN_vMDpmIAmPd181UanjO_kxR7QIlsEmT_UhM1MBmyfdIEvHkgLgUdUouonjQNvOKwCrrgDkP0hkZQff-iuHPwpL-CUjw7GPa70lp-TIDhfei8T90RkAXte1XKv7ku3sgENHTwPrL9QSrNtdc5MfB9AbUV-tFMJn9T7k
I was looking for this too. I've got a project that runs HWC, and I'd like to keep the web site out of the app tree, but I don't want to keep it in the debug (or release) directory. FWIW, the accepted solution (and this one as well) only identifies the directory the executable is running in.
To find that directory, I've been using
string startupPath = System.IO.Path.GetFullPath(".\\").
The procedures outlined here do not work for Android 7 (Nougat) [and possibly Android 6, but I'm unable to verify]. You can't pull the .apk files directly under Nougat (unless in root mode, but that requires a rooted phone). But, you can copy the .apk to an alternate path (say /sdcard/Download) on the phone using adb shell, then you can do an adb pull from the alternate path.
If you insist on everything initializing as empty, you need an extra set of brackets on the inside ([[]] instead of [], since this is "a list containing 1 empty list to be duplicated" as opposed to "a list containing nothing to duplicate"):
distance=[[[[]]*n]*n]*n
Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:
x <- 1:10
y <- x + c(-0.5,0.5)
plot(x,y, xlim=c(0,11), ylim=c(-1,12))
fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )
fit7 <- lm( y ~ x + cos(x*pi) )
xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')
Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).
check the official example. X,Y and Z are indeed 2d arrays, numpy.meshgrid() is a simple way to get 2d x,y mesh out of 1d x and y values.
http://matplotlib.sourceforge.net/mpl_examples/mplot3d/surface3d_demo.py
here's pythonic way to convert your 3-tuples to 3 1d arrays.
data = [(1,2,3), (10,20,30), (11, 22, 33), (110, 220, 330)]
X,Y,Z = zip(*data)
In [7]: X
Out[7]: (1, 10, 11, 110)
In [8]: Y
Out[8]: (2, 20, 22, 220)
In [9]: Z
Out[9]: (3, 30, 33, 330)
Here's mtaplotlib delaunay triangulation (interpolation), it converts 1d x,y,z into something compliant (?):
http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.griddata
URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
I'm late to the game here but in-case others want an easy solution, I created a set of functions which can be called like:
ggplot + scale_x_continuous(labels = human_gbp)
which give you human readable numbers for x or y axes (or any number in general really).
You can find the functions here: Github Repo Just copy the functions in to your script so you can call them.
Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.
ADDED: My latest favourite is JetBrains' dotPeek.
Seems like the only way to get decimal in a pretty (for me) form requires some ridiculous code.
The only solution I got so far:
CASE WHEN xy>0 and xy<1 then '0' || to_char(xy) else to_char(xy)
xy
is a decimal.
xy query result
0.8 0.8 --not sth like .80
10 10 --not sth like 10.00
Simply add this
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
well, as an easier alternative and shorter, you could do this too!!
var fd = new FormData();
var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); //page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID
fd.append("file", file_data);
$.ajax({
url: 'add.php?'+ other_data, //<== just add it to the end of url ***
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
If you are getting the output Optional(5)
when trying to print the value of 5
in an optional Int or String, you should unwrap the value first:
if let value = text {
print(value)
}
Now you've got the value without the "Optional" string that Swift adds when the value is not unwrapped before.
I would recommend not to use HTTP authentication with custom scheme names. If you feel that you have something of generic use, you can define a new scheme, though. See http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p7-auth-latest.html#rfc.section.2.3 for details.
Solved mine with
File -> Settings -> Build, Execution, Deployment -> Build Tools ->
Gradle -> Offline work
Gradle builds went from 8 minutes to 3 seconds.
I think you need to update your libraries so that your VBA code works, your using ms outlook
The min sdk version is the minimum version of the Android operating system required to run your application.
The target sdk version is the version of Android that your app was created to run on.
The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.
Usually the compile sdk version and the target sdk version are the same.
You can overwrite your default activity animation. Here is the solution that I use:
Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorPrimary</item>
<item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>
</style>
<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
<item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
<item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
<item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
<item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>
Create anim folder under res folder and then create this four animation files:
slide_in_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
This is my sample project in github.
That's all... Happy coding :)
In Eclipse 3.7, I found a terminal view plugin that I installed through Eclipse Marketplace. Details are as follow:
Local Terminal (Incubation) http://market.eclipsesource.com/yoxos/node/org.eclipse.tm.terminal.local.feature.group
A terminal emulation for local shells and external tools. Requires CDT Core 7.0 or later. Works on Linux, Solaris and Mac. Includes Source.
Side note, this terminal does not execute .bash_profile
or .bashrc
so you can do
source ~/.bash_profile
and (if this isn't sourced by `.bash_profile)
source ~/.bashrc
Update:
This is actually was base for Terminal plug-in for Eclipse fork. Quote from http://alexruiz.developerblogs.com/?p=2428
Uwe Stieber July 23, 2013 at 12:57 am
Alex, why not aiming for rejoining your work with the original TM Terminal? I’ve checked and haven’t found any bugzilla asking for missing features or pointing out bugs. There had been changes to the original Terminal control, so I’m not sure if all of your original reasons to clone it are still true.
typescript prevent accessing object without assigning type that has the desired property or
already assigned to any
so you can use optional chaining window?.MyNamespace = 'value'
.
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
Just in case. Make sure you load the IE specific js files after you load your css files.
<TextView
android:id="@+id/phoneNumber"
android:autoLink="phone"
android:linksClickable="true"
android:text="+91 22 2222 2222"
/>
This is how you can open EditText label assigned number on dialer directly.
As MySql accepts the date in y-m-d format in date type column, you need to STR_TO_DATE
function to convert the date into yyyy-mm-dd format for insertion in following way:
INSERT INTO table_name(today)
VALUES(STR_TO_DATE('07-25-2012','%m-%d-%y'));
Similary, if you want to select the date in different format other than Mysql format, you should try DATE_FORMAT
function
SELECT DATE_FORMAT(today, '%m-%d-%y') from table_name;
Please note that the proposed code is only valid with Python 2
Here is an example:
from Tkinter import * # from x import * is bad practice
from ttk import *
# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
class VerticalScrolledFrame(Frame):
"""A pure Tkinter scrollable frame that actually works!
* Use the 'interior' attribute to place widgets inside the scrollable frame
* Construct and pack/place/grid normally
* This frame only allows vertical scrolling
"""
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
if __name__ == "__main__":
class SampleApp(Tk):
def __init__(self, *args, **kwargs):
root = Tk.__init__(self, *args, **kwargs)
self.frame = VerticalScrolledFrame(root)
self.frame.pack()
self.label = Label(text="Shrink the window to activate the scrollbar.")
self.label.pack()
buttons = []
for i in range(10):
buttons.append(Button(self.frame.interior, text="Button " + str(i)))
buttons[-1].pack()
app = SampleApp()
app.mainloop()
It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.
edit:
to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.
to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).
to 3)
Well, it positions the window on the canvas.
One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.
There's a class called SoapHexBinary that does exactly what you want.
using System.Runtime.Remoting.Metadata.W3cXsd2001;
public static byte[] GetStringToBytes(string value)
{
SoapHexBinary shb = SoapHexBinary.Parse(value);
return shb.Value;
}
public static string GetBytesToString(byte[] value)
{
SoapHexBinary shb = new SoapHexBinary(value);
return shb.ToString();
}
I had the same Problem and the Answer is just Right in front of you, remember when you ran the script while installing mysql like
sudo mysql_secure_installation
there somewhere you chose which password type would you like to chose
There are three levels of password validation policy:
LOW Length >= 8 MEDIUM Length >= 8, numeric, mixed case, and special characters STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:
you have to give a password to same policy
here are some sample examples for your passwords:
for type 0: abcdabcd
for type 1: abcd1234
for type 2: ancd@1234
My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this
Error in my case
SQL>create view v1 as select * from books where id=10;
insufficient privileges.
Solution
1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba
E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
2) Enter password: here you have to type that password that you give at the time of installation of oracle software.
3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.
for creating new user
SQL> create user abc identified by xyz;
here abc is user and xyz is password.
giving all the privileges to abc user
SQL> grant all privileges to abc;
grant succeeded.
if you are seen this message then all the privileges are giving to the abc user.
4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.
In My case
in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
SQL> grant all privileges to SCOTT;
grant succeeded.
Now I can create views.
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
calling bean action from a will be a good idea,keep attribute autoRun="true" example below
<p:remoteCommand autoRun="true" name="myRemoteCommand" action="#{bean.action}" partialSubmit="true" update=":form" />
For Apple TV Simulator (tvOS, AppleTV) you should add --display=external
parameter. I use this to save to desktop:
xcrun simctl io booted recordVideo --display=external --codec=h264 --force ~/Desktop/SimulatorVideo.mov
--force
to rewrite if file exist
--codec
to higher framerate
Long Press on Power button, then you will have the option for the screenshot.
for Full-screen responsive background image
set css height ( height:100vh )
example :
.main-header {
background-image: url(../img/bb-background2.png);
background-repeat: no-repeat;
background-position: center;
background-size: cover;
width: 100%;
height:100vh; /* responsive height */
}
Use setTimeout function with either of the following
// simulates similar behavior as an HTTP redirect
window.location.replace("http://www.google.com");
// simulates similar behavior as clicking on a link
window.location.href = "http://www.google.com";
setTimeout(function(){
window.location.replace("http://www.google.com");
}, 1000)
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});
You can have both formats as an argument to the function date():
date("d-m-Y H:i:s")
Check the manual for more info : http://php.net/manual/en/function.date.php
As pointed out by @ThomasVdBerge to display minutes you need the 'i' character
You can move your files to other folder and then pull whole folder.
adb shell mkdir /sdcard/tmp adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end) adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back adb shell rmdir /sdcard/tmp # remove temporary directory
For Word Wrapping in Php Storm 1. Select File from the menu 2. From File select setting 3. From setting select Editor 4. Select General from Editor 5. In general checked Use soft wraps in editor from Soft wraps section
All the model fields which have definite types, those should be validated when returned to Controller. If any of the model fields are not matching with their defined type, then ModelState.IsValid will return false. Because, These errors will be added in ModelState.
Use this to implement mask:
https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js
<input id="phn-number" class="ant-input" type="text" placeholder="(XXX) XXX-XXXX" data-inputmask-mask="(999) 999-9999">
jQuery( '#phn-number[data-inputmask-mask]' ).inputmask();
The configuration property name has been changed in the latest version of maven-javadoc-plugin which is 3.0.0.
Hence the <additionalparam> will not work. So we have to modify it as below.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<doclint>none</doclint>
</configuration>
</plugin>
Using Arel:
topics=Topic.arel_table
Topic.where(topics[:forum_id].not_in(@forum_ids))
or, if preferred:
topics=Topic.arel_table
Topic.where(topics[:forum_id].in(@forum_ids).not)
and since rails 4 on:
topics=Topic.arel_table
Topic.where.not(topics[:forum_id].in(@forum_ids))
Please notice that eventually you do not want the forum_ids to be the ids list, but rather a subquery, if so then you should do something like this before getting the topics:
@forum_ids = Forum.where(/*whatever conditions are desirable*/).select(:id)
in this way you get everything in a single query: something like:
select * from topic
where forum_id in (select id
from forum
where /*whatever conditions are desirable*/)
Also notice that eventually you do not want to do this, but rather a join - what might be more efficient.
For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci.certificateStatus = "TRUE";
break;
default:
dataToSend.naci.certificateStatus = "";
}
}
And because dataToSend.naci
cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci!.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci!.certificateStatus = "TRUE";
break;
default:
dataToSend.naci!.certificateStatus = "";
}
}
$.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: associated_buildsorprojects_form,
success:function(data){
// do console.log(data);
console.log(data);
// you'll find that what exactly inside data
// I do not prefer alter(data); now because, it does not
// completes requirement all the time
// After that you can easily put if condition that you do not want like
// if(data != '')
// if(data == null)
// or whatever you want
},
error: function(errorThrown){
alert(errorThrown);
alert("There is an error with AJAX!");
}
});
It's called a "finalizer", and you should usually only create one for a class whose state (i.e.: fields) include unmanaged resources (i.e.: pointers to handles retrieved via p/invoke calls). However, in .NET 2.0 and later, there's actually a better way to deal with clean-up of unmanaged resources: SafeHandle. Given this, you should pretty much never need to write a finalizer again.
For a histogram with integer x-values I ended up using
plt.hist(data, np.arange(min(data)-0.5, max(data)+0.5))
plt.xticks(range(min(data), max(data)))
The offset of 0.5 centers the bins on the x-axis values. The plt.xticks
call adds a tick for every integer.
This issue occured a few days ago with my Bitbucket repositories. I was able to fix it by setting the remote url to http rather than https.
I also tried setting https proxies in the command line and git config but this didn't work.
$ git pull
fatal: unable to access 'https://[email protected]/sacgf/x.git/': Received HTTP code 407 from proxy after CONNECT
Note that we are using https:
$ git remote -v
origin https://[email protected]/sacgf/x.git (fetch)
origin https://[email protected]/sacgf/x.git (push)
Replace https url with http url:
$ git remote set-url origin http://[email protected]/sacgf/x.git
$ git pull
Username for 'https://bitbucket.org': username
Password for 'https://[email protected]':
remote: Counting objects: 43, done.
remote: Compressing objects: 100% (42/42), done.
remote: Total 43 (delta 31), reused 0 (delta 0)
Unpacking objects: 100% (43/43), done.
From http://bitbucket.org/sacgf/x
a41eb87..ead1a92 master -> origin/master
First, rewinding head to replay your work on top of it...
Fast-forwarded master to ead1a920caf60dd11e4d1a021157d3b9854a9374.
d
When pthread_exit() is called, the calling threads stack is no longer addressable as "active" memory for any other thread. The .data, .text and .bss parts of "static" memory allocations are still available to all other threads. Thus, if you need to pass some memory value into pthread_exit() for some other pthread_join() caller to see, it needs to be "available" for the thread calling pthread_join() to use. It should be allocated with malloc()/new, allocated on the pthread_join threads stack, 1) a stack value which the pthread_join caller passed to pthread_create or otherwise made available to the thread calling pthread_exit(), or 2) a static .bss allocated value.
It's vital to understand how memory is managed between a threads stack, and values store in .data/.bss memory sections which are used to store process wide values.
The readr package will fix this issue.
install.packages('readr')
library(readr)
readr::read_csv('yourfile.csv')
var inputs = $('#foo');
inputs.each(function(){
this.style.textTransform = 'uppercase';
})
.keyup(function(){
this.value = this.value.toUpperCase();
});
#!/bin/bash
cd /opt/
sudo mkdir java
sudo tar -zxvf ~/Downloads/jdk-8u192-linux-x64.tar.gz
sudo ln -s jdk1.8.0_192 current
for file in /opt/java/current/bin/*
do
if [ -x $file ]
then
filename=`basename $file`
sudo update-alternatives --install /usr/bin/$filename $filename $file 20000
sudo update-alternatives --set $filename $file
#echo $file $filename
fi
done
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
For me that solved it: https://coderwall.com/p/-ckobg
PROVISIONING_PROFILE = ...
"PROVISIONING_PROFILE[sdk=iphoneos*]" = ...
CODE_SIGN_IDENTITY = ...
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ...
A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL
(doc). The URL object has a Query()
method (doc) that returns a Values
type, which is simply a map[string][]string
of the QueryString parameters.
If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm()
and then use req.Form
field to get the map of key-value pairs, but you can also call FormValue(key)
to get the value of a specific key. This calls ParseForm()
if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).
Just wanted to add something: I found tim cooper's answer very useful, I used it to make a method which accepts an array of positions and does the insert on all of them so here that is:
EDIT: Looks like my old function assumed $insertstr
was only 1 character and that the array was sorted. This works for arbitrary character length.
function stringInsert($str, $pos, $insertstr) {
if (!is_array($pos)) {
$pos = array($pos);
} else {
asort($pos);
}
$insertionLength = strlen($insertstr);
$offset = 0;
foreach ($pos as $p) {
$str = substr($str, 0, $p + $offset) . $insertstr . substr($str, $p + $offset);
$offset += $insertionLength;
}
return $str;
}
I like to use a rolling file appender to write the logging info to a file. My log4j properties file typically looks something like this. I prefer this way since I like to make package specific logging in case I need varying degrees of logging for different packages. Only one package is mentioned in the example.
log4j.appender.RCS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RCS.File.DateFormat='.'yyyy-ww
#define output location
log4j.appender.RCS.File=C:temp/logs/MyService.log
#define the file layout
log4j.appender.RCS.layout=org.apache.log4j.PatternLayout
log4j.appender.RCS.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm a} %5 %c{1}: Line#%L - %m%n
log4j.rootLogger=warn
#Define package specific logging
log4j.logger.MyService=debug, RCS
You will get such error message when you request HTTPS resource via wrong port, such as 80. So please make sure you specified right port, 443, in the Request options.
To find the duplicate values only :
var duplicates = list.GroupBy(x => x.Key).Any(g => g.Count() > 1);
E.g.
var list = new[] {1,2,3,1,4,2};
GroupBy
will group the numbers by their keys and will maintain the count (number of times it repeated) with it. After that, we are just checking the values who have repeated more than once.
To find the unique values only :
var unique = list.GroupBy(x => x.Key).All(g => g.Count() == 1);
E.g.
var list = new[] {1,2,3,1,4,2};
GroupBy
will group the numbers by their keys and will maintain the count (number of times it repeated) with it. After that, we are just checking the values who have repeated only once means are unique.
Any color
parse into int
simplest two way here:
1) Get System Color
int redColorValue = Color.RED;
2) Any Color Hex Code as a String Argument
int greenColorValue = Color.parseColor("#00ff00")
MUST REMEMBER in above code Color
class must be android.graphics...
!
After reading through erickson's suggestions, and gleaning what I could from a couple other postings and this example here, I've attempted to update Doug's code with the recommended changes. Feel free to edit to make it better.
Some notes: This uses a 128 bit encryption key - java apparently won't do 256 bit encryption out-of-the-box. Implementing 256 requires installing some extra files into the java install directory.
Also, I'm not a crypto person. Take heed.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
public class Crypto
{
String mPassword = null;
public final static int SALT_LEN = 8;
byte [] mInitVec = null;
byte [] mSalt = null;
Cipher mEcipher = null;
Cipher mDecipher = null;
private final int KEYLEN_BITS = 128; // see notes below where this is used.
private final int ITERATIONS = 65536;
private final int MAX_FILE_BUF = 1024;
/**
* create an object with just the passphrase from the user. Don't do anything else yet
* @param password
*/
public Crypto (String password)
{
mPassword = password;
}
/**
* return the generated salt for this object
* @return
*/
public byte [] getSalt ()
{
return (mSalt);
}
/**
* return the initialization vector created from setupEncryption
* @return
*/
public byte [] getInitVec ()
{
return (mInitVec);
}
/**
* debug/print messages
* @param msg
*/
private void Db (String msg)
{
System.out.println ("** Crypt ** " + msg);
}
/**
* this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
* and generates the salt bytes using secureRandom(). The encryption secret key is created
* along with the initialization vectory. The member variable mEcipher is created to be used
* by the class later on when either creating a CipherOutputStream, or encrypting a buffer
* to be written to disk.
*
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidParameterSpecException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
*/
public void setupEncrypt () throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidParameterSpecException,
IllegalBlockSizeException,
BadPaddingException,
UnsupportedEncodingException,
InvalidKeyException
{
SecretKeyFactory factory = null;
SecretKey tmp = null;
// crate secureRandom salt and store as member var for later use
mSalt = new byte [SALT_LEN];
SecureRandom rnd = new SecureRandom ();
rnd.nextBytes (mSalt);
Db ("generated salt :" + Hex.encodeHexString (mSalt));
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
/* Derive the key, given password and salt.
*
* in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
* The end user must also install them (not compiled in) so beware.
* see here: http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
*/
KeySpec spec = new PBEKeySpec (mPassword.toCharArray (), mSalt, ITERATIONS, KEYLEN_BITS);
tmp = factory.generateSecret (spec);
SecretKey secret = new SecretKeySpec (tmp.getEncoded(), "AES");
/* Create the Encryption cipher object and store as a member variable
*/
mEcipher = Cipher.getInstance ("AES/CBC/PKCS5Padding");
mEcipher.init (Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = mEcipher.getParameters ();
// get the initialization vectory and store as member var
mInitVec = params.getParameterSpec (IvParameterSpec.class).getIV();
Db ("mInitVec is :" + Hex.encodeHexString (mInitVec));
}
/**
* If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
* We have the password from initializing the class. pass the iv and salt here which is
* obtained when encrypting the file initially.
*
* @param initvec
* @param salt
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws DecoderException
*/
public void setupDecrypt (String initvec, String salt) throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
DecoderException
{
SecretKeyFactory factory = null;
SecretKey tmp = null;
SecretKey secret = null;
// since we pass it as a string of input, convert to a actual byte buffer here
mSalt = Hex.decodeHex (salt.toCharArray ());
Db ("got salt " + Hex.encodeHexString (mSalt));
// get initialization vector from passed string
mInitVec = Hex.decodeHex (initvec.toCharArray ());
Db ("got initvector :" + Hex.encodeHexString (mInitVec));
/* Derive the key, given password and salt. */
// in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
// The end user must also install them (not compiled in) so beware.
// see here:
// http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(mPassword.toCharArray (), mSalt, ITERATIONS, KEYLEN_BITS);
tmp = factory.generateSecret(spec);
secret = new SecretKeySpec(tmp.getEncoded(), "AES");
/* Decrypt the message, given derived key and initialization vector. */
mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));
}
/**
* This is where we write out the actual encrypted data to disk using the Cipher created in setupEncrypt().
* Pass two file objects representing the actual input (cleartext) and output file to be encrypted.
*
* there may be a way to write a cleartext header to the encrypted file containing the salt, but I ran
* into uncertain problems with that.
*
* @param input - the cleartext file to be encrypted
* @param output - the encrypted data file
* @throws IOException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public void WriteEncryptedFile (File input, File output) throws
IOException,
IllegalBlockSizeException,
BadPaddingException
{
FileInputStream fin;
FileOutputStream fout;
long totalread = 0;
int nread = 0;
byte [] inbuf = new byte [MAX_FILE_BUF];
fout = new FileOutputStream (output);
fin = new FileInputStream (input);
while ((nread = fin.read (inbuf)) > 0 )
{
Db ("read " + nread + " bytes");
totalread += nread;
// create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
// and results in full blocks of MAX_FILE_BUF being written.
byte [] trimbuf = new byte [nread];
for (int i = 0; i < nread; i++)
trimbuf[i] = inbuf[i];
// encrypt the buffer using the cipher obtained previosly
byte [] tmp = mEcipher.update (trimbuf);
// I don't think this should happen, but just in case..
if (tmp != null)
fout.write (tmp);
}
// finalize the encryption since we've done it in blocks of MAX_FILE_BUF
byte [] finalbuf = mEcipher.doFinal ();
if (finalbuf != null)
fout.write (finalbuf);
fout.flush();
fin.close();
fout.close();
Db ("wrote " + totalread + " encrypted bytes");
}
/**
* Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
* to disk as (output) File.
*
* I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
* and still have a correctly decrypted file in the end. Seems to work so left it in.
*
* @param input - File object representing encrypted data on disk
* @param output - File object of cleartext data to write out after decrypting
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws IOException
*/
public void ReadEncryptedFile (File input, File output) throws
IllegalBlockSizeException,
BadPaddingException,
IOException
{
FileInputStream fin;
FileOutputStream fout;
CipherInputStream cin;
long totalread = 0;
int nread = 0;
byte [] inbuf = new byte [MAX_FILE_BUF];
fout = new FileOutputStream (output);
fin = new FileInputStream (input);
// creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
cin = new CipherInputStream (fin, mDecipher);
while ((nread = cin.read (inbuf)) > 0 )
{
Db ("read " + nread + " bytes");
totalread += nread;
// create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
byte [] trimbuf = new byte [nread];
for (int i = 0; i < nread; i++)
trimbuf[i] = inbuf[i];
// write out the size-adjusted buffer
fout.write (trimbuf);
}
fout.flush();
cin.close();
fin.close ();
fout.close();
Db ("wrote " + totalread + " encrypted bytes");
}
/**
* adding main() for usage demonstration. With member vars, some of the locals would not be needed
*/
public static void main(String [] args)
{
// create the input.txt file in the current directory before continuing
File input = new File ("input.txt");
File eoutput = new File ("encrypted.aes");
File doutput = new File ("decrypted.txt");
String iv = null;
String salt = null;
Crypto en = new Crypto ("mypassword");
/*
* setup encryption cipher using password. print out iv and salt
*/
try
{
en.setupEncrypt ();
iv = Hex.encodeHexString (en.getInitVec ()).toUpperCase ();
salt = Hex.encodeHexString (en.getSalt ()).toUpperCase ();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidParameterSpecException e)
{
e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
/*
* write out encrypted file
*/
try
{
en.WriteEncryptedFile (input, eoutput);
System.out.printf ("File encrypted to " + eoutput.getName () + "\niv:" + iv + "\nsalt:" + salt + "\n\n");
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
/*
* decrypt file
*/
Crypto dc = new Crypto ("mypassword");
try
{
dc.setupDecrypt (iv, salt);
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidAlgorithmParameterException e)
{
e.printStackTrace();
}
catch (DecoderException e)
{
e.printStackTrace();
}
/*
* write out decrypted file
*/
try
{
dc.ReadEncryptedFile (eoutput, doutput);
System.out.println ("decryption finished to " + doutput.getName ());
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
If you are concerned with the verbosity of your code I would write this rather than trying to abuse expressions.
if (Source == value) return;
Source = value;
RaisePropertyChanged("Source");
If watch doesn't want to install via
brew install watch
There is another similar/copy version that installed and worked perfectly for me
brew install visionmedia-watch
in my case I added such cyclic resource:
<drawable name="above_shadow">@drawable/above_shadow</drawable>
then changed to
<drawable name="some_name">@drawable/other_name</drawable>
and it worked
I know this post is from 4 years ago, but because of my C# background I was looking for a way to call the base class without having to specify the class name but rather obtain it by a property on the subclass. So my only change to Christoph's answer would be
From this:
MyClass.prototype.doStuff.call(this /*, args...*/);
To this:
this.constructor.prototype.doStuff.call(this /*, args...*/);
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
I've searched through their docs and it seems there is not xpath option. Also, as you can see here on a similar question on SO, the OP is asking for a translation from xpath to BeautifulSoup, so my conclusion would be - no, there is no xpath parsing available.
Consider this as your select list:
<select onchange="var optionVal = $(this).find(':selected').val(); doSomething(optionVal)">
<option value="mostSeen">Most Seen</option>
<option value="newst">Newest</option>
<option value="mostSell">Most Sell</option>
<option value="mostCheap">Most Cheap</option>
<option value="mostExpensive">Most Expensive</option>
</select>
then you check selected option like this:
function doSomething(param) {
if ($(param.selected)) {
alert(param + ' is selected!');
}
}
I think I found a solution to hide certain JavaScript codes in the view source of the browser. But you have to use jQuery to do this.
For example:
In your index.php
<head>
<script language = 'javascript' src = 'jquery.js'></script>
<script language = 'javascript' src = 'js.js'></script>
</head>
<body>
<a href = "javascript:void(null)" onclick = "loaddiv()">Click me.</a>
<div id = "content">
</div>
</body>
You load a file in the html/php body called by a jquery function in the js.js file.
js.js
function loaddiv()
{$('#content').load('content.php');}
Here's the trick.
In your content.php file put another head tag then call another js file from there.
content.php
<head>
<script language = 'javascript' src = 'js2.js'></script>
</head>
<a href = "javascript:void(null)" onclick = "loaddiv2()">Click me too.</a>
<div id = "content2">
</div>
in the js2.js file create any function you want.
example:
js2.js
function loaddiv2()
{$('#content2').load('content2.php');}
content2.php
<?php
echo "Test 2";
?>
Please follow link then copy paste it in the filename of jquery.js
http://dl.dropbox.com/u/36557803/jquery.js
I hope this helps.
The error SQLSTATE[HY000] [1040] Too many connections
is an SQL error, and has to do with the sql server. There could be other applications connecting to the server. The server has a maximum available connections number.
If you have phpmyadmin, you can use the 'variables' tab to check what the setting is.
You can also query the status table like so:
show status like '%onn%';
Or some variance on that. check the manual for what variables there are
(be aware, 'connections' is not the current connections, check that link :) )
^
is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow
.
Go to bin directory of Zookeeper and type
./zkServer.sh status
For More info go through below link:
http://www.ibm.com/developerworks/library/bd-zookeeper/
Hope this could help you.
You need to use an Expanded Widget. But, if your button is on a column, the Expanded Widget fills the rest of the column. So, you need to enclose the Expanded Widget within a row.
Row(children: <Widget>[
Expanded(
flex: 1,
child: RaisedButton(
child: Text("Your Text"),
onPressed: _submitForm,
),
),),])