You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):
:3020,$ w /tmp/yank
And to write this block in another line/file, go to the desired position and execute next command (insert file written before):
:r /tmp/yank
(Reminder: don't forget to remove file: /tmp/yank)
Another way could be to open the two files in two split buffers and use the following "snippet" after visual selection of the lines of interest.
:vnoremap <F4> :y<CR><C-W>Wr<Esc>p
This is for the worst-case scenario of exiting Vim if you just want out, have no idea what you've done and you don't care what will happen to the files you opened.
Ctrl-cEnterEntervi
EnterCtrl-\Ctrl-n:qa!
Enter
This should get you out most of the time.
Some interesting cases where you need something like this:
i
Ctrl-ovg
(you enter insert mode, then visual mode and then operator pending mode)
Qappend
Enter
i
Ctrl-ogQ
Ctrl-r=
Ctrl-k (thanks to porges for this case)
:set insertmode
(this is a case when Ctrl-\Ctrl-n returns you to normal mode)
Edit: This answer was corrected due to cases above. It used to be:
EscEscEsc:qa!
Enter
However, that doesn't work if you have entered Ex mode. In that case you would need to do:
vi
Enter:qa!
Enter
So a complete command for "I don't want to know what I've done and I don't want to save anything, I just want out now!" would be
vi
EnterEscEscEsc:qa!
Enter
Press A to enter edit mode starting at the end of the line.
% is also good when you want to diff files across two different copies of a project without wearing out the pinkies (from root of project1):
:vert diffs /project2/root/%
From vim's help page:
CTRL-R {0-9a-z"%#:-=.} *c_CTRL-R* *c_<C-R>*
Insert the contents of a numbered or named register. Between
typing CTRL-R and the second character '"' will be displayed
<...snip...>
Special registers:
'"' the unnamed register, containing the text of
the last delete or yank
'%' the current file name
'#' the alternate file name
'*' the clipboard contents (X11: primary selection)
'+' the clipboard contents
'/' the last search pattern
':' the last command-line
'-' the last small (less than a line) delete
'.' the last inserted text
*c_CTRL-R_=*
'=' the expression register: you are prompted to
enter an expression (see |expression|)
(doesn't work at the expression prompt; some
things such as changing the buffer or current
window are not allowed to avoid side effects)
When the result is a |List| the items are used
as lines. They can have line breaks inside
too.
When the result is a Float it's automatically
converted to a String.
See |registers| about registers. {not in Vi}
<...snip...>
The command to run depends on what base image you are using.
For Alpine, vi
is installed as part of the base OS. Installing vim
would be:
apk -U add vim
For Debian and Ubuntu:
apt-get update && apt-get install -y vim
For CentOS, vi
is usually installed with the base OS. For vim
:
yum install -y vim
This should only be done in early development. Once you get a working container, the changes to files should be made to your image or configs stored outside of your container. Update your Dockerfile and other files it uses to build a new image. This certainly shouldn't be done in production since changes inside the container are by design ephemeral and will be lost when the container is replaced.
I use this script: https://github.com/maksimr/vim-jsbeautify
In the above link you have all the info:
:call HtmlBeautify()
Does the job beautifully!
I couldn't copy files using the answers above but I have putty and I found a workaround on Quora.
Note: it copies all the printed characters of that session to the log file, so it will get big eventually. In that case, delete the log file and cat the target file so you get that particular file's content copied on your machine.
For someone who doesn't know vi, some answers from above might mislead him with phrases like "paste ... after/before current line".
It's actually "paste ... after/before cursor".
yy or Y to copy the line
or
dd to delete the line
then
p to paste the copied or deleted text after the cursor
or
P to paste the copied or deleted text before the cursor
For more key bindings, you can visit this site: vi Complete Key Binding List
For vi Editor, use :insert. This will keep all your formatting and not insert auto-indenting.Once done press escape to view the actual formatted file otherwise you'l see some garbage characters. like ^I e.g:
public static void main(String[] args) {
^I
^I System.out.println("Some Garbage printed upon using :insert");
}
If you are on the first line, pressing (upper case) J will join that line and the next line together, removing the newline. You can also combine this with a count, so pressing 3J
will combine all 3 lines together.
On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.
If you prefer a non-visual mode method and acknowledge the line numbers, I would like to suggest you an another straightforward way.
Example
I want to delete text from line 45 to line 101.
My method suggests you to type a below command in command-mode:
45Gd101G
It reads:
Go to line 45 (
45G
) then delete text (d
) from the current line to the line 101 (101G
).
Note that on vim
you might use gg
in stead of G
.
Compare to the @Bonnie Varghese's answer which is:
:45,101d[enter]
The command above from his answer requires 9 times typing including enter, where my answer require 8 - 10 times typing. Thus, a speed of my method is comparable.
Personally, I myself prefer 45Gd101G
over :45,101d
because I like to stick to the syntax of the vi's command, in this case is:
+---------+----------+--------------------+
| syntax | <motion> | <operator><motion> |
+---------+----------+--------------------+
| command | 45G | d101G |
+---------+----------+--------------------+
Press delete key in insert mode to remove blank lines.
Assuming the cursor is on the line you like to move.
Moving up and down:
:m
for move
:m +1
- moves down 1 line
:m -2
- move up 1 lines
(Note you can replace +1 with any numbers depending on how many lines you want to move it up or down, ie +2 would move it down 2 lines, -3 would move it up 2 lines)
To move to specific line
:set number
- display number lines (easier to see where you are moving it to)
:m 3
- move the line after 3rd line (replace 3 to any line you'd like)
Moving multiple lines:
V
(i.e. Shift-V) and move courser up and down to select multiple lines in VIM
once selected hit : and run the commands above, m +1
etc
The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a {
and hitting Enter indents the following line.
As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.
You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.
sav person.haml_spec.rb | call delete(expand('#'))
Use the > command. To indent five lines, 5>>. To mark a block of lines and indent it, Vjj> to indent three lines (Vim only). To indent a curly-braces block, put your cursor on one of the curly braces and use >% or from anywhere inside block use >iB.
If you’re copying blocks of text around and need to align the indent of a block in its new location, use ]p instead of just p. This aligns the pasted block with the surrounding text.
Also, the shiftwidth
setting allows you to control how many spaces to indent.
In the syntax s/foo/bar
, \r
and \n
have different meanings, depending on context.
For foo
:
\r
== "carriage return" (CR
/ ^M
)
\n
== matches "line feed" (LF
) on Linux/Mac, and CRLF
on Windows
For bar
:
\r
== produces LF
on Linux/Mac, CRLF
on Windows
\n
== "null byte" (NUL
/ ^@
)
When editing files in linux (i.e. on a webserver) that were initially created in a windows environment and uploaded (i.e. FTP/SFTP) - all the ^M
's you see in vim, are the CR
's which linux does not translate as it uses only LF
's to depict a line break.
NUL
== 0x00 == 0 == Ctrl + @ == ^@
shown in vim
LF
== 0x0A == 10 == Ctrl + J
CR
== 0x0D == 13 == Ctrl + M == ^M
shown in vim
Here is a list of the ASCII control characters. Insert them in Vim via Ctrl + V,Ctrl + ---key---.
In Bash or the other Unix/Linux shells, just type Ctrl + ---key---.
Try Ctrl + M in Bash. It's the same as hitting Enter, as the shell realizes what is meant, even though Linux systems use line feeds for line delimiting.
To insert literal's in bash, prepending them with Ctrl + V will also work.
Try in Bash:
echo ^[[33;1mcolored.^[[0mnot colored.
This uses ANSI escape sequences. Insert the two ^[
's via Ctrl + V, Esc.
You might also try Ctrl + V,Ctrl + M, Enter, which will give you this:
bash: $'\r': command not found
Remember the \r
from above? :>
This ASCII control characters list is different from a complete ASCII symbol table, in that the control characters, which are inserted into a console/pseudoterminal/Vim via the Ctrl key (haha), can be found there.
Whereas in C and most other languages, you usually use the octal codes to represent these 'characters'.
If you really want to know where all this comes from: The TTY demystified. This is the best link you will come across about this topic, but beware: There be dragons.
TL;DR
Usually foo
= \n
, and bar
= \r
.
I suggest doing:
*
to do a "bounded search" for what's under the cursor, or do a standard /pattern
search.:%s///gn
to get the number of occurrences. Or you can use :%s///n
to get the number of lines with occurrences.** I really with I could find a plug-in that would giving messaging of "match N of N1 on N2 lines" with every search, but alas.
Note:
Don't be confused by the tricky wording of the output. The former command might give you something like 4 matches on 3 lines
where the latter might give you 3 matches on 3 lines
. While technically accurate, the latter is misleading and should say '3 lines match'. So, as you can see, there really is never any need to use the latter ('n' only) form. You get the same info, more clearly, and more by using the 'gn' form.
You can also use
:-0
This sets the cursor at the present line (blank here) at the 0 column.
After mapping the below to a simple key combo, the following are very useful for me:
Jump into a file while over its path
gf
get full path name of existing file
:r!echo %:p
get directory of existing file
:r!echo %:p:h
run code:
:!ruby %:p
ruby abbreviations:
ab if_do if end<esc>bi<cr><esc>xhxO
ab if_else if end<esc>bi<cr><esc>xhxO else<esc>bhxA<cr> <esc>k$O
ab meth def method<cr>end<esc>k<esc>:s/method/
ab klas class KlassName<cr>end<esc>k<esc>:s/KlassName/
ab mod module ModName<cr>end<esc>k<esc>:s/ModName/
run current program:
map ,rby :w!<cr>:!ruby %:p<cr>
check syntax of current program:
map ,c :w!<cr>:!ruby -c %:p<cr>
run all specs for current spec program:
map ,s :w!<cr>:!rspec %:p<cr>
crack it open irb:
map ,i :w!<cr>:!irb<cr>
rspec abreviations:
ab shared_examples shared_examples_for "behavior here" do<cr>end
ab shared_behavior describe "description here" do<cr> before :each do<cr>end<cr>it_should_behave_like "behavior here"<cr><bs>end<cr>
ab describe_do describe "description here" do<cr>end
ab context_do describe "description here" do<cr>end
ab it_do it "description here" do<cr>end
ab before_each before :each do<cr>end<cr>
rails abbreviations:
user authentication:
ab userc <esc>:r $VIMRUNTIME/Templates/Ruby/c-users.rb<cr>
ab userv <esc>:r $VIMRUNTIME/Templates/Ruby/v-users.erb<cr>
ab userm <esc>:r $VIMRUNTIME/Templates/Ruby/m-users.rb<cr>
open visually selected url in firefox:
"function
function open_url_in_firefox:(copy_text)
let g:open_url_in_firefox="silent !open -a \"firefox\" \"".a:copy_text."\""
exe g:open_url_in_firefox
endfunction
"abbreviations
map ,d :call open_url_in_firefox:(expand("%:p"))<cr>
map go y:call open_url_in_firefox:(@0)<cr>
rspec: run spec containing current line:
"function
function run_single_rspec_test:(the_test)
let g:rake_spec="!rspec ".a:the_test.":".line(".")
exe g:rake_spec
endfunction
"abbreviations
map ,s :call run_single_rspec_test:(expand("%:p"))<cr>
rspec-rails: run spec containing current line:
"function
function run_single_rails_rspec_test:(the_test)
let g:rake_spec="!rake spec SPEC=\"".a:the_test.":".line(".")."\""
exe g:rake_spec
endfunction
"abbreviations
map ,r :call run_single_rails_rspec_test:(expand("%:p"))<cr>
rspec-rails: run spec containing current line with debugging:
"function
function run_spec_containing_current_line_with_debugging:(the_test)
let g:rake_spec="!rake spec SPEC=\"".a:the_test.":".line(".")." -d\""
exe g:rake_spec
endfunction
"abbreviations
map ,p :call run_spec_containing_current_line_with_debugging:(expand("%:p")) <cr>
html
"abbreviations
"ab htm <html><cr><tab><head><cr></head><cr><body><cr></body><cr><bs><bs></html>
ab template_html <script type = 'text/template' id = 'templateIdHere'></script>
ab script_i <script src=''></script>
ab script_m <script><cr></script>
ab Tpage <esc>:r ~/.vim/templates/pageContainer.html<cr>
ab Ttable <esc>:r ~/.vim/templates/listTable.html<cr>
"function to render common html template
function html:()
call feedkeys( "i", 't' )
call feedkeys("<html>\<cr> <head>\<cr></head>\<cr><body>\<cr> ", 't')
call feedkeys( "\<esc>", 't' )
call feedkeys( "i", 't' )
call include_js:()
call feedkeys("\<bs>\<bs></body>\<cr> \<esc>hxhxi</html>", 't')
endfunction
javascript
"jasmine.js
"abbreviations
ab describe_js describe('description here', function(){<cr>});
ab context_js context('context here', function(){<cr>});
ab it_js it('expectation here', function(){<cr>});
ab expect_js expect().toEqual();
ab before_js beforeEach(function(){<cr>});
ab after_js afterEach(function(){<cr>});
"function abbreviations
ab fun1 function(){}<esc>i<cr><esc>ko
ab fun2 x=function(){};<esc>hi<cr>
ab fun3 var x=function(){<cr>};
"method for rendering inclusion of common js files
function include_js:()
let includes_0 = " <link type = 'text\/css' rel = 'stylesheet' href = '\/Users\/johnjimenez\/common\/stylesheets\/jasmine-1.1.0\/jasmine.css'\/>"
let includes_1 = " <link type = 'text\/css' rel = 'stylesheet' href = '\/Users\/johnjimenez\/common\/stylesheets\/screen.css'\/>"
let includes_2 = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/jquery-1.7.2\/jquery-1.7.2.js'><\/script>"
let includes_3 = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/underscore\/underscore.js'><\/script>"
let includes_4 = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/backbone-0.9.2\/backbone.js'><\/script>"
let includes_5 = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/jasmine-1.1.0\/jasmine.js'><\/script>"
let includes_6 = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/jasmine-1.1.0\/jasmine-html.js'><\/script>"
let includes_7 = "<script>"
let includes_8 = " describe('default page', function(){ "
let includes_9 = "it('should have an html tag', function(){ "
let includes_10 = " expect( $( 'head' ).html() ).not.toMatch(\/^[\\s\\t\\n]*$\/);"
let includes_11 = "});"
let includes_12 = "});"
let includes_13 = "$(function(){"
let includes_14 = "jasmine.getEnv().addReporter( new jasmine.TrivialReporter() );"
let includes_15 = "jasmine.getEnv().execute();"
let includes_16 = "});"
let includes_17 = "\<bs>\<bs><\/script>"
let j = 0
while j < 18
let entry = 'includes_' . j
call feedkeys( {entry}, 't' )
call feedkeys( "\<cr>", 't' )
let j = j + 1
endwhile
endfunction
"jquery
"abbreviations
ab docr $(document).ready(function(){});
ab jqfun $(<cr>function(){<cr>}<cr>);
In vim if you are confused which all lines will be affected, Use below
:%s/foo/bar/gc
Change each 'foo' to 'bar', but ask for confirmation first. Press 'y' for yes and 'n' for no. Dont forget to save after that
:wq
Do it the vi way.
To delete 5 lines press: 5dd
( 5 delete )
To select ( actually copy them to the clipboard ) you type: 10yy
It is a bit hard to grasp, but very handy to learn when using those remote terminals
Be aware of the learning curves for some editors:
(source: calver at unix.rulez.org)
Try adding
set background=dark
to your .gvimrc
too. This work well for me.
If you are talking about show line number command in vi/vim
you could use
set nu
in commandline mode to turn on and
set nonu
will turn off the line number display or
set nu!
to toggle off display of line numbers
if you're on osx and want to be able to click on your tabs, use MouseTerm and SIMBL (taken from here). Also, check out this related discussion.
After opening a file using vi
1) You can press Shift + g to go the end of the file
and
2) Press g twice to go to the beginning of the file
NOTE : - g is case-sensitive (Thanks to @Ben for pointing it out)
If you want to keep your \t
equal to 8 spaces then consider setting:
set softtabstop=2 tabstop=8 shiftwidth=2
This will give you two spaces per <TAB>
press, but actual \t
in your code will still be viewed as 8 characters.
I got this error when my directory path is incorrect, ensure your directory names and path are correct
You seem to misuse vim, but that's likely due to not being very familiar with it.
The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.
Here's a couple of use-cases:
But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.
If you don't want to add/edit .vimrc, you can start with
vi "+set number" /path/to/file
highlight search
:set hlsearch
in .vimrc
that is
and search for space tabs and carriage returns
/ \|\t\|\r
or search for all whitespace characters
/\s
of search for all non white space characters (the whitespace characters are not shown, so you see the whitespace characters between words, but not the trailing whitespace characters)
/\S
to show all trailing white space characters - at the end of the line
/\s$
If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3")
. If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.
You can easily check this, e.g. by trying:
$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);
echo bin2hex($decrypted_string)."=".bin2hex("TheString");
Just enclose your textbox inside a view and then override inputAccessoryView returning the view. Important: Your view should be created programmatically. Do not use @IBOutlets.
override var inputAccessoryView: UIView? {
get {
return newlyProgramaticallyCreatedView
}}
A non-jQuery solution that more closely mimics IsNullOrWhiteSpace
, but to detect null, empty or all-spaces only:
function isEmptyOrSpaces(str){
return str === null || str.match(/^ *$/) !== null;
}
...then:
var addr = ' ';
if(isEmptyOrSpaces(addr)){
// error
}
* EDIT * Please note that op specifically states:
I need to check to see if a var is null or has any empty spaces or for that matter just blank.
So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.
You can set background color of view to the UIColor with alpha, and not affect view.alpha
:
view.backgroundColor = UIColor(white: 1, alpha: 0.5)
or
view.backgroundColor = UIColor.red.withAlphaComponent(0.5)
List last updated on December 1, 2020:
As of November 30, 2020, AWS now has EC2 Mac instances:
We previously used and had good experiences with:
Here are some other sites that I am aware of:
When we were with MacStadium, we loved them. We had great connectivity/uptime. When I've needed hands-on support to plug in a Time Machine backup, they've been great. They performed a seamless upgrade to better hardware for us over one weekend (when we could afford a bit of downtime), and that went off without a hitch. Highly recommended. (Not affiliated - just happy).
In April of 2020, we stopped using MacStadium, simply because we no longer needed a Mac server. If I need another Mac host, I would be happy to go back to them.
$.ajax({
url: 'http://url.of.my.server/submit',
dataType: "jsonp",
jsonp: 'callback',
jsonpCallback: 'jsonp_callback'
});
jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:
url: 'http://url.of.my.server/submit?callback=?'
the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.
$.ajax({
url: 'http://url.of.my.server/submit?callback=?',
success: function (data, status) {
mySurvey.closePopup();
},
error: function (xOptions, textStatus) {
mySurvey.closePopup();
}
});
The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:
$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});
Here's a solution I found that does not throw scripting errors in IE: http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx
As a oneliner:
import os
# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )
# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )
A more robust solution accounting for files and directories as well would be (2.7):
def rm(f):
if os.path.isdir(f): return os.rmdir(f)
if os.path.isfile(f): return os.unlink(f)
raise TypeError, 'must be either file or directory'
map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
As @FelixKling pointed out, the most likely scenario is that the nodes you are looking for do not exist (yet).
However, modern development practices can often manipulate document elements outside of the document tree either with DocumentFragments or simply detaching/reattaching current elements directly. Such techniques may be used as part of JavaScript templating or to avoid excessive repaint/reflow operations while the elements in question are being heavily altered.
Similarly, the new "Shadow DOM" functionality being rolled out across modern browsers allows elements to be part of the document, but not query-able by document.getElementById and all of its sibling methods (querySelector, etc.). This is done to encapsulate functionality and specifically hide it.
Again, though, it is most likely that the element you are looking for simply is not (yet) in the document, and you should do as Felix suggests. However, you should also be aware that that is increasingly not the only reason that an element might be unfindable (either temporarily or permanently).
Use the ->pluck() method
$roles = DB::table('roles')->pluck('title');
If you would like to retrieve an array containing the values of a single column, you may use the pluck method
Use the ->lists() method
$roles = DB::table('roles')->lists('title');
This method will return an array of role titles. You may also specify a custom key column for the returned array:
A simple and jQuery free solution:
document.querySelector('#elitable').onclick = function(ev) {
// ev.target <== td element
// ev.target.parentElement <== tr
var index = ev.target.parentElement.rowIndex;
}
Bonus: It works even if rows are added/removed dynamically
To see the whole file: git show stash@{0}:<filename>
To see the diff: git diff stash@{0}^1 stash@{0} -- <filename>
The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()
SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.
source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html
You can use the view width to set the height. 100 vw is 100% of the width.
height: 60vw;
would make the height 60% of the width.
That's simple. You can set option to display only week days in toLocaleDateString() to get the names. For example:
(new Date()).toLocaleDateString('en-US',{ weekday: 'long'}) will return only the day of the week. And (new Date()).toLocaleDateString('en-US',{ month: 'long'}) will return only the month of the year.
The best way to skip the first item(s) is:
from itertools import islice
for car in islice(cars, 1, None):
# do something
islice in this case is invoked with a start-point of 1, and an end point of None, signifying the end of the iterator.
To be able to skip items from the end of an iterable, you need to know its length (always possible for a list, but not necessarily for everything you can iterate on). for example, islice(cars, 1, len(cars)-1) will skip the first and last items in the cars list.
A little late to the party, but this is how I did it for an insert:
DECLARE @ManagerID AS Varchar (25) = 'NA'
DECLARE @ManagerEmail AS Varchar (50) = 'NA'
Declare @RecordCount AS int = 0
SET @ManagerID = ?
SET @ManagerEmail = ?
SET @RecordCount = ?
INSERT INTO...
the over partition keyword is as if we are partitioning the data by client_id creation a subset of each client id
select client_id, operation_date,
row_number() count(*) over (partition by client_id order by client_id ) as operationctrbyclient
from client_operations e
order by e.client_id;
this query will return the number of operations done by the client_id
/**
* If $header is an array of headers
* It will format and return the correct $header
* $header = [
* 'Accept' => 'application/json',
* 'Content-Type' => 'application/x-www-form-urlencoded'
* ];
*/
$i_header = $header;
if(is_array($i_header) === true){
$header = [];
foreach ($i_header as $param => $value) {
$header[] = "$param: $value";
}
}
I think checking keypress
events is not completely adequate, as I believe users can copy/paste into input boxes without triggering a keypress.
So onblur
is probably somewhat more reliable (but is less immediate).
To truly make sure characters you don't want are not entered into input boxes (or textareas, etc.), I think you will need to
keypress
(if you want to give immediate feedback) and onblur
, The code samples in the other answers will work fine for doing the client-side checks (just don't rely only on checking keypress
events), but as was pointed out in the accepted answer, a server-side check is really required.
For the GUI itself:
PyQT is pretty much the reference.
Another way to develop a rapid user interface is to write a web app, have it run locally and display the app in the browser.
Plus, if you go for the Tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on Windows environment without Python.
Stopping the service and killing the daemon are indeed the correct ways to shutdown a node. However, it's not recommended to do so directly if you want to take down a node for maintenance. In fact, if you don't have replicas you will lose data.
When you directly shutdown a node, Elasticsearch will wait for 1m (default time) for it to come back online. If it doesn't, then it will start to allocate the shards from that node to other nodes wasting lots of IO.
A typical approach would be to disable shard allocation temporarily by issuing:
PUT _cluster/settings
{
"persistent": {
"cluster.routing.allocation.enable": "none"
}
}
Now, when you take down a node, ES won't try to allocate shard from that node to other nodes and you can perform you maintenance activity and then once the node is up, you can enable shard allocation again:
PUT _cluster/settings
{
"persistent": {
"cluster.routing.allocation.enable": "all"
}
}
Source: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/restart-upgrade.html
If you don't have replicas for all your indexes, then performing this type of activity will have downtime on some of the indexes. A cleaner way in this case would be to migrate all the shards to other nodes before taking the node down:
PUT _cluster/settings
{
"transient" : {
"cluster.routing.allocation.exclude._ip" : "10.0.0.1"
}
}
This will move all shards from 10.0.0.1
to other nodes (will take time depending on the data). Once everything is done, you can kill the node, perform maintenance and get it back online. This is a slower operation and is not required if you have replicas.
(Instead of _ip, _id, _name with wildcards will work just fine.)
More information: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/allocation-filtering.html
Other answers have explained how to kill a process.
You can delete files in PHP using the unlink()
function.
unlink('path/to/file.jpg');
Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
and all I received was 2017-02-20 the time disappeared
My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
now the time doesn't disappear.
Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes
object directly.
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)
# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
Hope that helps.
First you need to use this command
npm config set registry https://registry.your-registry.npme.io/
This we are doing to set our companies Enterprise registry as our default registry.
You can try other given solutions also.
Here are a few ways to do it
INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip)
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
from SOMETABLEWITHTONSOFROWS LIMIT 3;
or
INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip)
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
or
INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip)
values ('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
This is purely driver registration/deregistration issue in mysql`s driver or tomcats webapp-classloader. Copy mysql driver into tomcats lib folder (so its loaded by jvm directly, not by tomcat), and message will be gone. That makes mysql jdbc driver to be unloaded only at JVM shutdown, and noone cares about memory leaks then.
(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))
To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].
You can break a line at an operator, list separator, or period.
You need to add the following line:
using FootballLeagueSystem;
into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login
.
At the moment the compiler can't find the Login
class.
To start the process with parameters, you can use following code:
string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);
To kill/exit the program again, you can use following code:
proc.CloseMainWindow();
proc.Close();
Here's a quick and dirty function to remove a row by index.
removeRowByIndex <- function(x, row_index) {
nr <- nrow(x)
if (nr < row_index) {
print('row_index exceeds number of rows')
} else if (row_index == 1)
{
return(x[2:nr, ])
} else if (row_index == nr) {
return(x[1:(nr - 1), ])
} else {
return (x[c(1:(row_index - 1), (row_index + 1):nr), ])
}
}
It's main flaw is it the row_index argument doesn't follow the R pattern of being a vector of values. There may be other problems as I only spent a couple of minutes writing and testing it, and have only started using R in the last few weeks. Any comments and improvements on this would be very welcome!
Create-React-App has a simple way to deal with this problem: add a proxy field to the package.json file as shown below
"proxy": "http://localhost:8081",
Terminal > su
> password
> vim /etc/vimrc
Click here and edit as in line number (13):
set nu
Davids, I had the exact same problem as you. MVC is not intuitive and it seems when they designed it the kiddos didn't understand the purpose or importance of an intuitive querystring system for MVC.
Querystrings are not set in the routes at all (RouteConfig). They are add-on "extra" parameters to Actions in the Controller. This is very confusing as the Action parameters are designed to process BOTH paths AND Querystrings. If you added parameters and they did not work, add a second one for the querystring as so:
This would be your action in your Controller class that catches the ID (which is actually just a path set in your RouteConfig file as a typical default path in MVC):
public ActionResult Hello(int id)
But to catch querystrings an additional parameter in your Controller needs to be the added (which is NOT set in your RouteConfig file, by the way):
public ActionResult Hello(int id, string start, string end)
This now listens for "/Hello?start=&end=" or "/Hello/?start=&end=" or "/Hello/45?start=&end=" assuming the "id" is set to optional in the RouteConfig.cs file.
If you wanted to create a "custom route" in the RouteConfig file that has no "id" path, you could leave off the "id" or other parameter after the action in that file. In that case your parameters in your Action method in the controller would process just querystrings.
I found this extremely confusing myself so you are not alone! They should have designed a simple way to add querystring routes for both specific named strings, any querystring name, and any number of querystrings in the RouteConfig file configuration design. By not doing that it leaves the whole use of querystrings in MVC web applications as questionable, which is pretty bizarre since querystrings have been a stable part of the World Wide Web since the mid-1990's. :(
You can create enums to deal with errors :)
enum RikhError: Error {
case unknownError
case connectionError
case invalidCredentials
case invalidRequest
case notFound
case invalidResponse
case serverError
case serverUnavailable
case timeOut
case unsuppotedURL
}
and then create a method inside enum to receive the http response code and return the corresponding error in return :)
static func checkErrorCode(_ errorCode: Int) -> RikhError {
switch errorCode {
case 400:
return .invalidRequest
case 401:
return .invalidCredentials
case 404:
return .notFound
//bla bla bla
default:
return .unknownError
}
}
Finally update your failure block to accept single parameter of type RikhError :)
I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)
Hope it helps :)
Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...
id = cursor.lastrowid
...should work too, and it's per-connection based obviously.
Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate
now has second parameter values
, which is being used for new record, but not for search
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
Name = r.Field<string>("Name"),
Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable
It depends on a design. There are no rules for URIs at REST over HTTP (main thing is that they are unique). Often it comes to the matter of taste and intuition...
I take following approach:
EDIT
The whoami utility has been obsoleted by the id(1) utility, and is equivalent to id -un
. The command id -p
is suggested for normal interactive use.
Everywhere inside the query string, the wildcard should be ?
instead of '?'
. That should solve the problem.
EDIT :
To add to that, you need to change date '?'
to to_date(?, 'yyyy-mm-dd')
. Please try that and let me know.
Only for .NET Core Web API project, add following changes:
services.AddMvc()
line in the ConfigureServices()
method of the Startup.cs file:services.AddCors(allowsites=>{allowsites.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
app.UseMvc()
line in the Configure()
method of the Startup.cs file:app.UseCors(options => options.AllowAnyOrigin());
[EnableCors("AllowOrigin")]
Try using while
loop, Array.prototype.push()
var myArray = [], X = 3;
while (myArray.length < X) {
myArray.push("")
}
Alternatively, using Array.prototype.fill()
var myArray = Array(3).fill("");
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
For CodeIgniter 4
, you can use the built-in API Response Trait
Here's sample code for reference:
<?php namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
class Home extends BaseController
{
use ResponseTrait;
public function index()
{
$data = [
'data' => 'value1',
'data2' => 'value2',
];
return $this->respond($data);
}
}
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like
if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {
//some interesting behaviour here
}
which I guess is a bit unwieldy but it gets the job done.
See https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult for additional enum options you can use here.
Here is a simple approach which triggers when the video ends.
<html>
<body>
<video id="myVideo" controls="controls">
<source src="video.mp4" type="video/mp4">
etc ...
</video>
</body>
<script type='text/javascript'>
document.getElementById('myVideo').addEventListener('ended', function(e) {
alert('The End');
})
</script>
</html>
In the 'EventListener' line substitute the word 'ended' with 'pause' or 'play' to capture those events as well.
The other answers were good answers when the question was asked. Time moves on, Date
and SimpleDateFormat
get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time
package:
String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.format(DateTimeFormatter.ofPattern("H:mm"));
The result is the desired, 9:00
.
Throwing runtime exceptions "sparingly" isn't really a good policy -- Effective Java recommends that you use checked exceptions when the caller can reasonably be expected to recover. (Programmer error is a specific example: if a particular case indicates programmer error, then you should throw an unchecked exception; you want the programmer to have a stack trace of where the logic problem occurred, not to try to handle it yourself.)
If there's no hope of recovery, then feel free to use unchecked exceptions; there's no point in catching them, so that's perfectly fine.
It's not 100% clear from your example which case this example is in your code, though.
When running the python file, you would normally do this
python app.py
This will display these messages.
To avoid these messsages. Inside the CLI (Command Line Interface), run these commands.
export FLASK_APP=app.py
export FLASK_RUN_HOST=127.0.0.1
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run
This should work perfectlly. :) :)
You can use numpy:
import numpy as np
Example from Empty Array:
np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]])
Just reset any content manually when modal is hidden:
$(".modal").on("hidden.bs.modal", function(){
$(".modal-body1").html("");
});
There is more events. More about them here
$(document).ready(function() {_x000D_
$(".modal").on("hidden.bs.modal", function() {_x000D_
$(".modal-body1").html("Where did he go?!?!?!");_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
Launch modal_x000D_
</button>_x000D_
_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>_x000D_
</button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<div class='modal-body1'>_x000D_
<h3>Close and open, I will be gone!</h3>_x000D_
</div>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Based on the answer from @Ryan Ahearn
, following is what I did on Ubuntu
16.04 to create a user front
that only has permission for nginx's web dir /var/www/html
.
Steps:
* pre-steps: * basic prepare of server, * create user 'dev' which will be the owner of "/var/www/html", * * install nginx, * * * create user 'front' sudo useradd -d /home/front -s /bin/bash front sudo passwd front # create home folder, if not exists yet, sudo mkdir /home/front # set owner of new home folder, sudo chown -R front:front /home/front # switch to user, su - front # copy .bashrc, if not exists yet, cp /etc/skel/.bashrc ~front/ cp /etc/skel/.profile ~front/ # enable color, vi ~front/.bashrc # uncomment the line start with "force_color_prompt", # exit user exit * * add to group 'dev', sudo usermod -a -G dev front * change owner of web dir, sudo chown -R dev:dev /var/www * change permission of web dir, chmod 775 $(find /var/www/html -type d) chmod 664 $(find /var/www/html -type f) * * re-login as 'front' to make group take effect, * * test * * ok *
I faced the same problem on Windows 10. As soon as I cleared my Path variable from edit environment variables option, the icon started to appear. It was occurring because I had previously installed python 3.6.1 on my computer and added it to my path variable as C:\Python36;C:\Python36\DLL; and so on. There isn't any need to uninstall Anaconda Navigator and start from scratch if you have correctly followed the steps mentioned at the documentation for it.
I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.
The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.
I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.
My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.
class Basket extends Array
constructor: ->
add: (item) ->
@push(item)
remove: (item) ->
index = @indexOf(item)
@.splice(index, 1)
contains: (item) ->
@indexOf(item) isnt -1
indexOf: (item) ->
indexOf = -1
@.forEach (stored_item, index) ->
if (item.id is stored_item.id)
indexOf = index
return indexOf
Then you initialize this in your controller and create a function for that action:
$scope.basket = new Basket()
$scope.addItemToBasket = (item) ->
$scope.basket.add(item)
Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:
li ng-repeat="item in items"
a href="#" ng-click="addItemToBasket(item)"
If you want to trigger the event as you type, use the following:
$('input[name=myInput]').on('keyup', function() { ... });
If you want to trigger the event on leaving the input field, use the following:
$('input[name=myInput]').on('change', function() { ... });
You have to enable CORS to solve this
set it in your response headers like
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
});
response.end('Hello World\n');
}).listen(3000);
use a CORS middleware like
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
and apply via
app.configure(function() {
app.use(allowCrossDomain);
//some other code
});
Here are two reference links
Since this seems to be the number one google hit on base64 encoding and iphone, I felt like sharing my experience with the code snippet above.
It works, but it is extremely slow. A benchmark on a random image (0.4 mb) took 37 seconds on native iphone. The main reason is probably all the OOP magic - single char NSStrings etc, which are only autoreleased after the encoding is done.
Another suggestion posted here (ab)uses the openssl library, which feels like overkill as well.
The code below takes 70 ms - that's a 500 times speedup. This only does base64 encoding (decoding will follow as soon as I encounter it)
+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
int lentext = [data length];
if (lentext < 1) return @"";
char *outbuf = malloc(lentext*4/3+4); // add 4 to be sure
if ( !outbuf ) return nil;
const unsigned char *raw = [data bytes];
int inp = 0;
int outp = 0;
int do_now = lentext - (lentext%3);
for ( outp = 0, inp = 0; inp < do_now; inp += 3 )
{
outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
outbuf[outp++] = base64EncodingTable[raw[inp+2] & 0x3F];
}
if ( do_now < lentext )
{
char tmpbuf[2] = {0,0};
int left = lentext%3;
for ( int i=0; i < left; i++ )
{
tmpbuf[i] = raw[do_now+i];
}
raw = tmpbuf;
outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
if ( left == 2 ) outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
}
NSString *ret = [[[NSString alloc] initWithBytes:outbuf length:outp encoding:NSASCIIStringEncoding] autorelease];
free(outbuf);
return ret;
}
I left out the line-cutting since I didn't need it, but it's trivial to add.
For those who are interested in optimizing: the goal is to minimize what happens in the main loop. Therefore all logic to deal with the last 3 bytes is treated outside the loop.
Also, try to work on data in-place, without additional copying to/from buffers. And reduce any arithmetic to the bare minimum.
Observe that the bits that are put together to look up an entry in the table, would not overlap when they were to be orred together without shifting. A major improvement could therefore be to use 4 separate 256 byte lookup tables and eliminate the shifts, like this:
outbuf[outp++] = base64EncodingTable1[(raw[inp] & 0xFC)];
outbuf[outp++] = base64EncodingTable2[(raw[inp] & 0x03) | (raw[inp+1] & 0xF0)];
outbuf[outp++] = base64EncodingTable3[(raw[inp+1] & 0x0F) | (raw[inp+2] & 0xC0)];
outbuf[outp++] = base64EncodingTable4[raw[inp+2] & 0x3F];
Of course you could take it a whole lot further, but that's beyond the scope here.
@JsonFormat(shape= JsonFormat.Shape.OBJECT)
public enum SomeEnum
available since https://github.com/FasterXML/jackson-databind/issues/24
just tested it works with version 2.1.2
answer to TheZuck:
I tried your example, got Json:
{"events":[{"type":"ADMIN"}]}
My code:
@RequestMapping(value = "/getEvent") @ResponseBody
public EventContainer getEvent() {
EventContainer cont = new EventContainer();
cont.setEvents(Event.values());
return cont;
}
class EventContainer implements Serializable {
private Event[] events;
public Event[] getEvents() {
return events;
}
public void setEvents(Event[] events) {
this.events = events;
}
}
and dependencies are:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
<exclusions>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
<exclusion>
<artifactId>jackson-core</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
</exclusions>
</dependency>
<jackson.version>2.1.2</jackson.version>
for more information on How to create Circle Android Custom Progress Bar view this link
Step 01 You should create an xml file on drawable file for configure the appearance of progress bar . So Im creating my xml file as circular_progress_bar.xml.
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="120"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="140">
<item android:id="@android:id/background">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:useLevel="false"
android:angle="0"
android:type="sweep"
android:thicknessRatio="50.0">
<solid android:color="#000000"/>
</shape>
</item>
<item android:id="@android:id/progress">
<rotate
android:fromDegrees="120"
android:toDegrees="120">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:angle="0"
android:type="sweep"
android:thicknessRatio="50.0">
<solid android:color="#ffffff"/>
</shape>
</rotate>
</item>
</layer-list>
Step 02 Then create progress bar on your xml file Then give the name of xml file on your drawable folder as the parth of android:progressDrawable
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginLeft="0dp"
android:layout_centerHorizontal="true"
android:indeterminate="false"
android:max="100"
android:progressDrawable="@drawable/circular_progress_bar" />
Step 03 Visual the progress bar using thread
package com.example.progress;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private ProgressBar progBar;
private TextView text;
private Handler mHandler = new Handler();
private int mProgressStatus=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progBar= (ProgressBar)findViewById(R.id.progressBar);
text = (TextView)findViewById(R.id.textView1);
dosomething();
}
public void dosomething() {
new Thread(new Runnable() {
public void run() {
final int presentage=0;
while (mProgressStatus < 63) {
mProgressStatus += 1;
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progBar.setProgress(mProgressStatus);
text.setText(""+mProgressStatus+"%");
}
});
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
res.setHeader('Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
Blockquote : you have to add OPTIONS & Authorization to the setHeader()
this change has fixed my problem, just give a try!
For me, the HTML Prettify
solution was extremely simple. I went to the HTML Prettify page.
Sublime Package Manager
prettify
HTML prettify
selection in the menuBoom. Done. Looks great
To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).
Then I register a pre- or post-build event in Visual Studio...
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"
For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).
You forgot the .class
:
if (value.getClass() == Integer.class) {
System.out.println("This is an Integer");
}
else if (value.getClass() == String.class) {
System.out.println("This is a String");
}
else if (value.getClass() == Float.class) {
System.out.println("This is a Float");
}
Note that this kind of code is usually the sign of a poor OO design.
Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:
"foo".getClass() == Object.class
is false, whereas
"foo" instanceof Object
is true.
Whether one or the other must be used depends on your requirements.
Adding line breaks to your Git commit
Try the following to create a multi-line commit message:
git commit -m "Demonstrate multi-line commit message in Powershell" -m "Add a title to your commit after -m enclosed in quotes,
then add the body of your comment after a second -m.
Press ENTER before closing the quotes to add a line break.
Repeat as needed.
Then close the quotes and hit ENTER twice to apply the commit."
Then verify what you've done:
git log -1
You should end up with something like this:
The screenshot is from an example I set up using PowerShell with Poshgit.
You have two options; either handle the exception or test the length:
if len(dlist) > 1:
newlist.append(dlist[1])
continue
or
try:
newlist.append(dlist[1])
except IndexError:
pass
continue
Use the first if there often is no second item, the second if there sometimes is no second item.
Navigate to:
My Computer -> Properties -> Advanced -> Environment Variables -> System Variables
Suppose you had already having python 2.7 added in path variable and you want to change default path to python 3.x
then add path of python3.5.x folder before python2.7 path.
open cmd: type "python --version"
python version will be changed to python 3.5.x
I had the same problem when I install python3.5.3. And finally I find the pip.exe in this folder: ~/python/scripts/pip.exe. Hope that help.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:
JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);
This is what I did:
Timestamp timestamp = Timestamp.valueOf(stringValue);
where stringValue
can be any format of Date/Time.
If you google for sort order windows explorer you will find out that Windows Explorer (since Windows XP) obviously uses the function StrCmpLogicalW in the sort order "by name". I did not find information about the treatment of the underscore character. I was amused by the following note in the documentation:
Behavior of this function, and therefore the results it returns, can change from release to release. ...
You can subtract the time zone difference from now.
final Calendar calendar = Calendar.getInstance();
final int utcOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
final long tempDate = new Date().getTime();
return new Date(tempDate - utcOffset);
Applying the recursive function on numpy arrays will be faster than the current answer.
df = pd.DataFrame(np.repeat(np.arange(2, 6),3).reshape(4,3), columns=['A', 'B', 'D'])
new = [df.D.values[0]]
for i in range(1, len(df.index)):
new.append(new[i-1]*df.A.values[i]+df.B.values[i])
df['C'] = new
Output
A B D C
0 1 1 1 1
1 2 2 2 4
2 3 3 3 15
3 4 4 4 64
4 5 5 5 325
Yeah, you can't constrain the iframe itself with height and width. You should put a div around it. If you control the content in the iframe, you can put some JS within the iframe content that will tell the parent to scroll the div when the touch event is received.
like this:
The JS:
setTimeout(function () {
var startY = 0;
var startX = 0;
var b = document.body;
b.addEventListener('touchstart', function (event) {
parent.window.scrollTo(0, 1);
startY = event.targetTouches[0].pageY;
startX = event.targetTouches[0].pageX;
});
b.addEventListener('touchmove', function (event) {
event.preventDefault();
var posy = event.targetTouches[0].pageY;
var h = parent.document.getElementById("scroller");
var sty = h.scrollTop;
var posx = event.targetTouches[0].pageX;
var stx = h.scrollLeft;
h.scrollTop = sty - (posy - startY);
h.scrollLeft = stx - (posx - startX);
startY = posy;
startX = posx;
});
}, 1000);
The HTML:
<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" id="iframe" src="url" />
</div>
If you don't control the iframe content, you can use an overlay over the iframe in a similar manner, but then you can't interact with the iframe contents other than to scroll it - so you can't, for example, click links in the iframe.
It used to be that you could use two fingers to scroll within an iframe, but that doesn't work anymore.
Update: iOS 6 broke this solution for us. I've been attempting to get a new fix for it, but nothing has worked yet. In addition, it is no longer possible to debug javascript on the device since they introduced Remote Web Inspector, which requires a Mac to use.
Try this
link_to "+ Service", my_services_new_path(:account_id => acct.id)
it will pass the account_id as you want.
For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.
select dbo.fun_functional_score('01091400003')
goobox()
will take the URL of your image file, and change it to be used directly as an image source.cconst goobox = (url)=>{
let dropbox_regex = /(http(s)*:\/\/)*(www\.)*(dropbox.com)/;
let drive_regex =/(http(s)*:\/\/)*(www\.)*(drive.google.com\/file\/d\/)/;
if(url.match(dropbox_regex)){
return url.replace(/(http(s)*:\/\/)*(www\.)*/, "https://dl.");
}
if(url.match(drive_regex)){
return `https://drive.google.com/uc?id=${url.replace(drive_regex, "").match(/[\w]*\//)[0].replace(/\//,"")}`;
}
return console.error('Wrong URL, not a vlid drobox or google drive url');
}
let url = 'https://drive.google.com/file/d/1PiCWHIwyQWrn4YxatPZDkB8EfegRIkIV/view'
goobox(URL); // https://drive.google.com/uc?id=1PiCWHIwyQWrn4YxatPZDkB8EfegRIkIV
Ad hoc is latin for "for this purpose". You might call it an "on the fly" query, or a "just so" query. It's the kind of SQL query you just loosely type out where you need it
var newSqlQuery = "SELECT * FROM table WHERE id = " + myId;
...which is an entirely different query each time that line of code is executed, depending on the value of myId
. The opposite of an ad hoc query is a predefined query such as a Stored Procedure, where you have created a single query for the entire generalized purpose of selecting from that table (say), and pass the ID as a variable.
echo "mydir/doc/ mydir/usoe ./mydir/usm" | awk '{ split($0,array," "); for(i in array){ system("cd "array[i]" && echo $PWD") } }'
var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);
#pragma comment
is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.
#pragma comment(lib, libname)
tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies
See #pragma comment on MSDN
If you want a deep copy without override while retaining the same obj
reference
obj = _.assign(obj, _.merge(obj, [source]))
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
Found similar problem within student's work, script element was put after closing body tag, so, obviously, JavaScript could not find any HTML element.
But, there was one more serious error: there was a reference to an external javascript file with some code, which removed all contents of a certain HTML element before inserting new content. After commenting out this reference, everything worked properly.
So, sometimes the error might be that some previously called Javascript changed content or even DOM, so calling for instance getElementById later doesn't make sense, since that element was removed.
def common_start(sa, sb):
""" returns the longest common substring from the beginning of sa and sb """
def _iter():
for a, b in zip(sa, sb):
if a == b:
yield a
else:
return
return ''.join(_iter())
>>> common_start("apple pie available", "apple pies")
'apple pie'
Or a slightly stranger way:
def stop_iter():
"""An easy way to break out of a generator"""
raise StopIteration
def common_start(sa, sb):
return ''.join(a if a == b else stop_iter() for a, b in zip(sa, sb))
Which might be more readable as
def terminating(cond):
"""An easy way to break out of a generator"""
if cond:
return True
raise StopIteration
def common_start(sa, sb):
return ''.join(a for a, b in zip(sa, sb) if terminating(a == b))
If you are compiling a PROCEDURE, possibly this is referring to a table or view that does not exist as it is created in the same PROCEDURE. In this case the solution is to make the query declared as String eg v_query: = 'insert into table select * from table2
and then execute immediate on v_query
;
This is because the compiler does not yet recognize the object and therefore does not find the reference. Greetings.
Swift 5 Just call this function and pass your view
public func setViewSettingWithBgShade(view: UIView)
{
view.layer.cornerRadius = 8
view.layer.borderWidth = 1
view.layer.borderColor = AppTextFieldBorderColor.cgColor
//MARK:- Shade a view
view.layer.shadowOpacity = 0.5
view.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
view.layer.shadowRadius = 3.0
view.layer.shadowColor = UIColor.black.cgColor
view.layer.masksToBounds = false
}
The Best way and recommended way of comparing date in typescript
is:
var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();
if(today === reqDateVar){
// NOW
} else {
// Some other time
}
You have a lot of type-mismatches in your code such as trying to put an int
value where BigDecimal
is required. The corrected version of your code:
public class Payment
{
BigDecimal itemCost = BigDecimal.ZERO;
BigDecimal totalCost = BigDecimal.ZERO;
public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
{
itemCost = itemPrice.multiply(new BigDecimal(itemQuantity));
totalCost = totalCost.add(itemCost);
return totalCost;
}
}
i just found this site that give a cool themes for the select box http://gregfranko.com/jquery.selectBoxIt.js/
and you can try this themes if your problem with the overall look blue - yellow - grey
I had this problem trying to hit https://ct.mob0.com/Styles/Fun.png, which is an image distributed by CloudFlare on its CDN that supports crazy stuff like SPDY and weird redirect SSL certs.
Instead of specifying Ssl3 as in Simons answer I was able to fix it by going down to Tls12 like this:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
new WebClient().DownloadData("https://ct.mob0.com/Styles/Fun.png");
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
You should find that the following schema allows the what you have proposed.
<xs:element name="foo">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:choice>
<xs:element maxOccurs="unbounded" name="child1" type="xs:unsignedByte" />
<xs:element maxOccurs="unbounded" name="child2" type="xs:string" />
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
This will allow you to create a file such as:
<?xml version="1.0" encoding="utf-8" ?>
<foo>
<child1>2</child1>
<child1>3</child1>
<child2>test</child2>
<child2>another-test</child2>
</foo>
Which seems to match your question.
.panel-default >.panel-heading
{
background: #ffffff;
}
This is what worked for me to change the color to white.
How about this?
for item in mylist:
if item in checklist:
pass
else:
# do something
print item
There's actually nothing wrong with document.write
, per se. The problem is that it's really easy to misuse it. Grossly, even.
In terms of vendors supplying analytics code (like Google Analytics) it's actually the easiest way for them to distribute such snippets
As long as you don't try to use it after the document has loaded, document.write
is not inherently evil, in my humble opinion.
You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.
#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
# now Firefox will run in a virtual display.
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()
You can also use xvfbwrapper, which is a similar module (but has no external dependencies):
from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
# launch stuff inside virtual display here
vdisplay.stop()
or better yet, use it as a context manager:
from xvfbwrapper import Xvfb
with Xvfb() as xvfb:
# launch stuff inside virtual display here.
# It starts/stops in this code block.
If you wanted to evaluate floats, and you wanted to accept NaN
s as input but not other strings like 'abc'
, you could do the following:
def isnumber(x):
import numpy
try:
return type(numpy.float(x)) == float
except ValueError:
return False
You can get the duration from the 'contentDetails' field in the json response.
Pandas 0.24.0+ solution
In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method
import csv
from io import StringIO
from sqlalchemy import create_engine
def psql_insert_copy(table, conn, keys, data_iter):
# gets a DBAPI connection that can provide a cursor
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join('"{}"'.format(k) for k in keys)
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
table_name, columns)
cur.copy_expert(sql=sql, file=s_buf)
engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)
I created a function in VBA for you, so you can do this now in an easy way.
Create a VBA code module (macro) as you can see in this tutorial.
Module
in Insert
.Excel Macro-Enabled
in Save As
.Function listUnique(rng As Range) As Variant
Dim row As Range
Dim elements() As String
Dim elementSize As Integer
Dim newElement As Boolean
Dim i As Integer
Dim distance As Integer
Dim result As String
elementSize = 0
newElement = True
For Each row In rng.Rows
If row.Value <> "" Then
newElement = True
For i = 1 To elementSize Step 1
If elements(i - 1) = row.Value Then
newElement = False
End If
Next i
If newElement Then
elementSize = elementSize + 1
ReDim Preserve elements(elementSize - 1)
elements(elementSize - 1) = row.Value
End If
End If
Next
distance = Range(Application.Caller.Address).row - rng.row
If distance < elementSize Then
result = elements(distance)
listUnique = result
Else
listUnique = ""
End If
End Function
Just enter =listUnique(range)
to a cell. The only parameter is range
that is an ordinary Excel range. For example: A$1:A$28
or H$8:H$30
.
range
must be a column.range
starts.It works in columns that have empty cells in them. Also the function outputs nothing (not errors) if you overwind the cells (calling the function) into places where should be no output, as I did it in the previous example's "2. Grow it" part.
Try the following: Paste "2004-06-01 00:00:00.000" into Excel.
Now try paste "2004-06-01 00:00:00" into Excel.
Excel doesn't seem to be able to handle milliseconds when pasting...
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static MainActivity instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instance = this;
}
public static MainActivity getInstance() {
return instance;
}
public void myMethod() {
// do something...
}
)
AnotherClass.java
public Class AnotherClass() {
// call this method
MainActivity.getInstance().myMethod();
}
You can proxyfy references to your object with, for example, dictionary singleton. You may store not object, but its ID or hash and access it trought the dictionary. Then when you need to remove the object you set value for its key to null.
This is an old thread but I was surprised nobody mentioned grep. The -A option allows specifying a number of lines to print after a search match and the -B option includes lines before a match. The following command would output 10 lines before and 10 lines after occurrences of "my search string" in the file "mylogfile.log":
grep -A 10 -B 10 "my search string" mylogfile.log
If there are multiple matches within a large file the output can rapidly get unwieldy. Two helpful options are -n which tells grep to include line numbers and --color which highlights the matched text in the output.
If there is more than file to be searched grep allows multiple files to be listed separated by spaces. Wildcards can also be used. Putting it all together:
grep -A 10 -B 10 -n --color "my search string" *.log someOtherFile.txt
You forgot to declare double as a return type
public double diameter()
{
double d = radius * 2;
return d;
}
I just came across this more recent example . To simplify and use the most recent examples, giving the css a selector class of 'grad',(I've included backwards compatibility)
.grad {
background-color: #F07575; /* fallback color if gradients are not supported */
background-image: -webkit-linear-gradient(top left, red, rgba(255,0,0,0));/* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
background-image: -moz-linear-gradient(top left, red, rgba(255,0,0,0));/* For Firefox (3.6 to 15) */
background-image: -o-linear-gradient(top left, red, rgba(255,0,0,0));/* For old Opera (11.1 to 12.0) */
background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0)); /* Standard syntax; must be last */
}
from https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:
var data = context.MyEntities.AsNoTracking().Where(...).ToList();
As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.
It works for me:
function stringIncludes(a, b) {
return a.indexOf(b) !== -1;
}
I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.
The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.
First I recommand you can try use print and observe the action:
for i in range(0, 5, 1):
print i
the result:
0
1
2
3
4
You can understand the function principle.
In fact, range
scan range is from 0
to 5-1
.
It equals 0 <= i < 5
When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.
You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.
for i in range(5, 0, -1):
print i
the result:
5
4
3
2
1
Thus it can be seen, it equals 5 >= i > 0
You want to implement your java code in python:
for (int index = last-1; index >= posn; index--)
It should code this:
for i in range(last-1, posn-1, -1)
\s
matches any white-space character\S
matches any non-white-space character[^ ]
matches anything but a space character.Pick whichever is most appropriate.
Here is the working example for Bootstrap 4.3
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
_x000D_
<div class="accordion" id="accordionExample">_x000D_
<div class="card">_x000D_
<div class="card-header" id="headingOne" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">_x000D_
<h2 class="mb-0">_x000D_
<button class="btn btn-link" type="button" >_x000D_
Collapsible Group Item #1_x000D_
</button>_x000D_
</h2>_x000D_
</div>_x000D_
_x000D_
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">_x000D_
<div class="card-body">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<div class="card-header" id="headingTwo" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">_x000D_
<h2 class="mb-0">_x000D_
<button class="btn btn-link collapsed" type="button" >_x000D_
Collapsible Group Item #2_x000D_
</button>_x000D_
</h2>_x000D_
</div>_x000D_
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">_x000D_
<div class="card-body">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<div class="card-header" id="headingThree" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">_x000D_
<h2 class="mb-0">_x000D_
<button class="btn btn-link collapsed" type="button" >_x000D_
Collapsible Group Item #3_x000D_
</button>_x000D_
</h2>_x000D_
</div>_x000D_
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">_x000D_
<div class="card-body">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Another correct way to get selected value would be using this selector:
$("option[value="0"]:selected")
Best for you!
For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.
The answer by Tony Andrews is a decent one. But the real answer is that this has been a convention used by relational database community and is NOT a necessity. Maybe it is a good convention, maybe not.
Comparing anything to NULL results in UNKNOWN (3rd truth value). So as has been suggested with nulls all traditional wisdom concerning equality goes out the window. Well that's how it seems at first glance.
But I don't think this is necessarily so and even SQL databases don't think that NULL destroys all possibility for comparison.
Run in your database the query SELECT * FROM VALUES(NULL) UNION SELECT * FROM VALUES(NULL)
What you see is just one tuple with one attribute that has the value NULL. So the union recognized here the two NULL values as equal.
When comparing a composite key that has 3 components to a tuple with 3 attributes (1, 3, NULL) = (1, 3, NULL) <=> 1 = 1 AND 3 = 3 AND NULL = NULL The result of this is UNKNOWN.
But we could define a new kind of comparison operator eg. ==. X == Y <=> X = Y OR (X IS NULL AND Y IS NULL)
Having this kind of equality operator would make composite keys with null components or non-composite key with null value unproblematic.
I am using phpMyAdmin Server version: 5.1.41.
It offers possibility for view sql history through phpmyadmin.pma_history
table.
You can search your query in this table.
pma_history
table has below structure:
You can use reflection to "automate" the full equality testing. you can implement the equality "tracking" code you wrote for a single field, then use reflection to run that test on all fields in the object.
[
is a command (or a builtin in some shells). It must be separated by whitespace from the preceding statement:
elif [
I combined several approaches here. I like the idea of the preprocessor and the indexed list.
There's no extra dynamic allocation, and because of the inlining the compiler might be able to optimize the lookup.
typedef NS_ENUM(NSUInteger, FormatType) { FormatTypeJSON = 0, FormatTypeXML, FormatTypeAtom, FormatTypeRSS, FormatTypeCount };
NS_INLINE NSString *FormatTypeToString(FormatType t) {
if (t >= FormatTypeCount)
return nil;
#define FormatTypeMapping(value) [value] = @#value
NSString *table[FormatTypeCount] = {FormatTypeMapping(FormatTypeJSON),
FormatTypeMapping(FormatTypeXML),
FormatTypeMapping(FormatTypeAtom),
FormatTypeMapping(FormatTypeRSS)};
#undef FormatTypeMapping
return table[t];
}
I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.
You can also use OFFSET:
OFFSET($A$10,-$B$1+1,0,$B$1)
It moves the range $A$10 up by $B$1-1 (becomes $A$6 ($A$5)) and then resizes the range to $B$1 rows (becomes $A$6:$A$10 ($A$5:$A$10))
You will get all the class in below array
event.target.classList
From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.
The simplest way for me to create and reuse a library project:
file > new > new module
(and answer the UI questions)include ':myLibrary'
check/or add if in the file build.gradle:
dependencies {
...
compile project(':myLibrary')
}
To reuse this library module in another project, copy it's folder in the project instead of step 1 and do the steps 2 and 3.
You can also create a new studio application project You can easily change an existing application module to a library module by changing the plugin assignment in the build.gradle file to com.android.library.
apply plugin: 'com.android.application'
android {...}
to
apply plugin: 'com.android.library'
android {...}
more here
$('#dropdownid').val('selectedvalue');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id='dropdownid'>_x000D_
<option value=''>- Please choose -</option>_x000D_
<option value='1'>1</option>_x000D_
<option value='2'>2</option>_x000D_
<option value='selectedvalue'>There we go!</option>_x000D_
<option value='3'>3</option>_x000D_
<option value='4'>4</option>_x000D_
<option value='5'>5</option>_x000D_
</select>
_x000D_
I've done this before. I had a pdf that I generated with fpdf, and I needed to add on a variable amount of PDFs to it.
So I already had an fpdf object and page set up (http://www.fpdf.org/) And I used fpdi to import the files (http://www.setasign.de/products/pdf-php-solutions/fpdi/) FDPI is added by extending the PDF class:
class PDF extends FPDI
{
}
$pdffile = "Filename.pdf";
$pagecount = $pdf->setSourceFile($pdffile);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx, 10, 10, 200);
}
This basically makes each pdf into an image to put into your other pdf. It worked amazingly well for what I needed it for.
With the lib config option your are able to cherry pick Map into your project. Just add es2015.collection
to your lib section. When you have no lib config add one with the defaults and add es2015.collection
.
So when you have target: es5, change tsconfig.json to:
"target": "es5",
"lib": [ "dom", "es5", "scripthost", "es2015.collection" ],
Simple:
var removedText = self.val().replace(/[^0-9]+/, '');
^ - means NOT
If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update()
:
S.update(T)
The return value is None
, but S
will be updated to be the union of the original S
and T
.
You haven't actually asked a question, but assuming you have one, this could be your answer...
Assuming all characters, except the "Special Characters" are allowed you can write
String regex = "^[^<>'\"/;`%]*$";
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
The answer from Blundell should work, but for some bizarre reason it didn't do with me. I had to pipe first the filenames outputted by the first command into a file and then loop through that file and delete that file one by one.
git ls-files -i --exclude-from=.gitignore > to_remove.txt
while read line; do `git rm -r --cached "$line"`; done < to_remove.txt
rm to_remove.txt
git commit -m 'Removed all files that are in the .gitignore'
git push origin master
Syntax:
CASE value WHEN [compare_value] THEN result
[WHEN [compare_value] THEN result ...]
[ELSE result]
END
Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
mysql> SELECT CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END;
+-------------------------------------------------------------+
| CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false |
+-------------------------------------------------------------+
I am use:
SELECT act.*,
CASE
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND lises.session_date >= now()
LEFT JOIN session AS ses ON ses.activity_id = act.id AND ses.session_date >= now()
WHERE act.id
It's example from great MSDN article about using ExpandoObject for creating dynamic ad-hoc types for incoming structured data (i.e XML, Json).
We can also assign delegate to ExpandoObject's dynamic property:
dynamic person = new ExpandoObject();
person.FirstName = "Dino";
person.LastName = "Esposito";
person.GetFullName = (Func<String>)(() => {
return String.Format("{0}, {1}",
person.LastName, person.FirstName);
});
var name = person.GetFullName();
Console.WriteLine(name);
Thus it allows us to inject some logic into dynamic object at runtime. Therefore, together with lambda expressions, closures, dynamic keyword and DynamicObject class, we can introduce some elements of functional programming into our C# code, which we knows from dynamic languages as like JavaScript or PHP.
Here's my version:
/* Convert a hex char digit to its integer value. */
int hexDigitToInt(char digit) {
digit = tolower(digit);
if ('0' <= digit && digit <= '9') //if it's decimal
return (int)(digit - '0');
else if ('a' <= digit && digit <= 'f') //if it's abcdef
return (int)(digit - ('a' - 10));
else
return -1; //value not in [0-9][a-f] range
}
/* Decode a hex string. */
char *decodeHexString(const char *hexStr) {
char* decoded = malloc(strlen(hexStr)/2+1);
char* hexStrPtr = (char *)hexStr;
char* decodedPtr = decoded;
while (*hexStrPtr != '\0') { /* Step through hexStr, two chars at a time. */
*decodedPtr = 16 * hexDigitToInt(*hexStrPtr) + hexDigitToInt(*(hexStrPtr+1));
hexStrPtr += 2;
decodedPtr++;
}
*decodedPtr = '\0'; /* final null char */
return decoded;
}
I was able to find the moment.js object for the selected date with the following:
$('#datepicker').data('DateTimePicker').date()
More info about moment.js and how to format the date using the moment.js object
C++11 offers std::normal_distribution
, which is the way I would go today.
Here are some solutions in order of ascending complexity:
Add 12 uniform random numbers from 0 to 1 and subtract 6. This will match mean and standard deviation of a normal variable. An obvious drawback is that the range is limited to ±6 – unlike a true normal distribution.
The Box-Muller transform. This is listed above, and is relatively simple to implement. If you need very precise samples, however, be aware that the Box-Muller transform combined with some uniform generators suffers from an anomaly called Neave Effect1.
For best precision, I suggest drawing uniforms and applying the inverse cumulative normal distribution to arrive at normally distributed variates. Here is a very good algorithm for inverse cumulative normal distributions.
1. H. R. Neave, “On using the Box-Muller transformation with multiplicative congruential pseudorandom number generators,” Applied Statistics, 22, 92-97, 1973
A mix fix for the underscore map bug :P
_.mixin({
mapobj : function( obj, iteratee, context ) {
if (obj == null) return [];
iteratee = _.iteratee(iteratee, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
results = {},
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
if ( _.isObject( obj ) ) {
return _.object( results ) ;
}
return results;
}
});
A simple workaround that keeps the right key and return as object It is still used the same way as i guest you could used this function to override the bugy _.map function
or simply as me used it as a mixin
_.mapobj ( options , function( val, key, list )
Be careful with window.history.length
because it includes also entries for window.history.forward()
So you may have maybe window.history.length
with more than 1 entries, but no history back entries.
This means that nothing happens if you fire window.history.back()
It's quite simple, first HTML must be added:
<div id="dialog"></div>
Then, it must be initialized:
<script type="text/javascript">
jQuery( document ).ready( function() {
jQuery( '#dialog' ).dialog( { 'autoOpen': false } );
});
</script>
After this you can show it by code:
jQuery( '#dialog' ).dialog( 'open' );
ionic state is deprecated as on [email protected]
If you happen to be using ionic and the ionic cli you can run:
ionic state reset
As long as all your plugin information was saved in your package.json earlier, this will essentially perform an rm/add for all your plugins. Just note that this will also rm/add your platforms as well, but that shouldn't matter.
This is also nice for when you ignore your plugin folders from your repo, and want to setup the project on another machine.
Obviously this doesn't directly answer the question, but many people are currently using both, and will end up here.
Using the "autofocus" attribute works to give input focus to the button by default. In fact clicking on any control within the form also gives focus to the form, a requirement for the form to react to the RETURN. So, the "autofocus" does that for you in case the user never clicked on any other control within the form.
So, the "autofocus" makes the crucial difference if the user never clicked on any of the form controls before hitting RETURN.
But even then, there are still 2 conditions to be met for this to work without JS:
a) you have to specify a page to go to (if left empty it wont work). In my example it is hello.php
b) the control has to be visible. You could conceivably move it off the page to hide, but you cannot use display:none or visibility:hidden. What I did, was to use inline style to just move it off the page to the left by 200px. I made the height 0px so that it does not take up space. Because otherwise it can still disrupt other controls above and below. Or you could float the element too.
<form action="hello.php" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password"/><br/>
<div class="yourCustomDiv"/>
<input autofocus type="submit" style="position:relative; left:-200px; height:0px;" />
</form>
I know I come late, but only recently I was able to implement such "addHeader" to the Adapter. In my FlexibleAdapter project you can call setHeader
on a Sectionable item, then you call showAllHeaders
. If you need only 1 header then the first item should have the header. If you delete this item, then the header is automatically linked to the next one.
Unfortunately footers are not covered (yet).
The FlexibleAdapter allows you to do much more than create headers/sections. You really should have a look: https://github.com/davideas/FlexibleAdapter.
Just like that nice warning you got, you are trying to do something that is an Anti-Pattern in React. This is a no-no. React is intended to have an unmount happen from a parent to child relationship. Now if you want a child to unmount itself, you can simulate this with a state change in the parent that is triggered by the child. let me show you in code.
class Child extends React.Component {
constructor(){}
dismiss() {
this.props.unmountMe();
}
render(){
// code
}
}
class Parent ...
constructor(){
super(props)
this.state = {renderChild: true};
this.handleChildUnmount = this.handleChildUnmount.bind(this);
}
handleChildUnmount(){
this.setState({renderChild: false});
}
render(){
// code
{this.state.renderChild ? <Child unmountMe={this.handleChildUnmount} /> : null}
}
}
this is a very simple example. but you can see a rough way to pass through to the parent an action
That being said you should probably be going through the store (dispatch action) to allow your store to contain the correct data when it goes to render
I've done error/status messages for two separate applications, both went through the store. It's the preferred method... If you'd like I can post some code as to how to do that.
Few things to note first. this is in typescript so you would need to remove the type declarations :)
I am using the npm packages lodash for operations, and classnames (cx alias) for inline classname assignment.
The beauty of this setup is I use a unique identifier for each notification when the action creates it. (e.g. notify_id). This unique ID is a Symbol()
. This way if you want to remove any notification at any point in time you can because you know which one to remove. This notification system will let you stack as many as you want and they will go away when the animation is completed. I am hooking into the animation event and when it finishes I trigger some code to remove the notification. I also set up a fallback timeout to remove the notification just in case the animation callback doesn't fire.
import { USER_SYSTEM_NOTIFICATION } from '../constants/action-types';
interface IDispatchType {
type: string;
payload?: any;
remove?: Symbol;
}
export const notifySuccess = (message: any, duration?: number) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: true, message, notify_id: Symbol(), duration } } as IDispatchType);
};
};
export const notifyFailure = (message: any, duration?: number) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: false, message, notify_id: Symbol(), duration } } as IDispatchType);
};
};
export const clearNotification = (notifyId: Symbol) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, remove: notifyId } as IDispatchType);
};
};
const defaultState = {
userNotifications: []
};
export default (state: ISystemNotificationReducer = defaultState, action: IDispatchType) => {
switch (action.type) {
case USER_SYSTEM_NOTIFICATION:
const list: ISystemNotification[] = _.clone(state.userNotifications) || [];
if (_.has(action, 'remove')) {
const key = parseInt(_.findKey(list, (n: ISystemNotification) => n.notify_id === action.remove));
if (key) {
// mutate list and remove the specified item
list.splice(key, 1);
}
} else {
list.push(action.payload);
}
return _.assign({}, state, { userNotifications: list });
}
return state;
};
in the base render for your application you would render the notifications
render() {
const { systemNotifications } = this.props;
return (
<div>
<AppHeader />
<div className="user-notify-wrap">
{ _.get(systemNotifications, 'userNotifications') && Boolean(_.get(systemNotifications, 'userNotifications.length'))
? _.reverse(_.map(_.get(systemNotifications, 'userNotifications', []), (n, i) => <UserNotification key={i} data={n} clearNotification={this.props.actions.clearNotification} />))
: null
}
</div>
<div className="content">
{this.props.children}
</div>
</div>
);
}
user notification class
/*
Simple notification class.
Usage:
<SomeComponent notifySuccess={this.props.notifySuccess} notifyFailure={this.props.notifyFailure} />
these two functions are actions and should be props when the component is connect()ed
call it with either a string or components. optional param of how long to display it (defaults to 5 seconds)
this.props.notifySuccess('it Works!!!', 2);
this.props.notifySuccess(<SomeComponentHere />, 15);
this.props.notifyFailure(<div>You dun goofed</div>);
*/
interface IUserNotifyProps {
data: any;
clearNotification(notifyID: symbol): any;
}
export default class UserNotify extends React.Component<IUserNotifyProps, {}> {
public notifyRef = null;
private timeout = null;
componentDidMount() {
const duration: number = _.get(this.props, 'data.duration', '');
this.notifyRef.style.animationDuration = duration ? `${duration}s` : '5s';
// fallback incase the animation event doesn't fire
const timeoutDuration = (duration * 1000) + 500;
this.timeout = setTimeout(() => {
this.notifyRef.classList.add('hidden');
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}, timeoutDuration);
TransitionEvents.addEndEventListener(
this.notifyRef,
this.onAmimationComplete
);
}
componentWillUnmount() {
clearTimeout(this.timeout);
TransitionEvents.removeEndEventListener(
this.notifyRef,
this.onAmimationComplete
);
}
onAmimationComplete = (e) => {
if (_.get(e, 'animationName') === 'fadeInAndOut') {
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}
}
handleCloseClick = (e) => {
e.preventDefault();
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}
assignNotifyRef = target => this.notifyRef = target;
render() {
const {data, clearNotification} = this.props;
return (
<div ref={this.assignNotifyRef} className={cx('user-notification fade-in-out', {success: data.isSuccess, failure: !data.isSuccess})}>
{!_.isString(data.message) ? data.message : <h3>{data.message}</h3>}
<div className="close-message" onClick={this.handleCloseClick}>+</div>
</div>
);
}
}
Only checked
and checked="checked"
are valid. Your other options depend on error recovery in browsers.
checked="yes"
and checked="true"
are particularly bad as they imply that checked="no"
and checked="false"
will set the default state to be unchecked … which they will not.
I have found a solution by myself. I use the PDANet tool to find the driver automatically.
If you recently update your Android Studio to 3.3.1 that have a problem with com.google.gms:google-services (Below 4.2.0) dependencies So please update com.google.gms:google-services to 4.2.0.
dependencies {
classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.2.0'
}
There is no standard naming of keys in JSON. According to the Objects section of the spec:
The JSON syntax does not impose any restrictions on the strings used as names,...
Which means camelCase or snake_case should work fine.
Imposing a JSON naming convention is very confusing. However, this can easily be figured out if you break it down into components.
Programming language for generating JSON
JSON itself has no standard naming of keys
Programming language for parsing JSON
snake_case will still make sense for those with Java entries because the existing JSON libraries for Java are using only methods to access the keys instead of using the standard dot.syntax. This means that it wouldn't hurt that much for Java to access the snake_cased keys in comparison to the other programming language which can do the dot.syntax.
Example for Java's org.json
package
JsonObject.getString("snake_cased_key")
Example for Java's com.google.gson
package
JsonElement.getAsString("snake_cased_key")
Choosing the right JSON naming convention for your JSON implementation depends on your technology stack. There are cases where one can use snake_case, camelCase, or any other naming convention.
Another thing to consider is the weight to be put on the JSON-generator vs the JSON-parser and/or the front-end JavaScript. In general, more weight should be put on the JSON-generator side rather than the JSON-parser side. This is because business logic usually resides on the JSON-generator side.
Also, if the JSON-parser side is unknown then you can declare what ever can work for you.
You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumnName BIT
The other option would be to create a new column of type BIT
, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
Jinja 2.6 does not have the map function. So an alternate way of doing this would be:
set_fact: foo="{% for i in bar_result.results %}{{ i.ansible_facts.foo_item }}{%endfor%}"
From Java Notes 6.0 website:
/**
* An object of type RomanNumeral is an integer between 1 and 3999. It can
* be constructed either from an integer or from a string that represents
* a Roman numeral in this range. The function toString() will return a
* standardized Roman numeral representation of the number. The function
* toInt() will return the number as a value of type int.
*/
public class RomanNumeral {
private final int num; // The number represented by this Roman numeral.
/* The following arrays are used by the toString() function to construct
the standard Roman numeral representation of the number. For each i,
the number numbers[i] is represented by the corresponding string, letters[i].
*/
private static int[] numbers = { 1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1 };
private static String[] letters = { "M", "CM", "D", "CD", "C", "XC",
"L", "XL", "X", "IX", "V", "IV", "I" };
/**
* Constructor. Creates the Roman number with the int value specified
* by the parameter. Throws a NumberFormatException if arabic is
* not in the range 1 to 3999 inclusive.
*/
public RomanNumeral(int arabic) {
if (arabic < 1)
throw new NumberFormatException("Value of RomanNumeral must be positive.");
if (arabic > 3999)
throw new NumberFormatException("Value of RomanNumeral must be 3999 or less.");
num = arabic;
}
/*
* Constructor. Creates the Roman number with the given representation.
* For example, RomanNumeral("xvii") is 17. If the parameter is not a
* legal Roman numeral, a NumberFormatException is thrown. Both upper and
* lower case letters are allowed.
*/
public RomanNumeral(String roman) {
if (roman.length() == 0)
throw new NumberFormatException("An empty string does not define a Roman numeral.");
roman = roman.toUpperCase(); // Convert to upper case letters.
int i = 0; // A position in the string, roman;
int arabic = 0; // Arabic numeral equivalent of the part of the string that has
// been converted so far.
while (i < roman.length()) {
char letter = roman.charAt(i); // Letter at current position in string.
int number = letterToNumber(letter); // Numerical equivalent of letter.
i++; // Move on to next position in the string
if (i == roman.length()) {
// There is no letter in the string following the one we have just processed.
// So just add the number corresponding to the single letter to arabic.
arabic += number;
}
else {
// Look at the next letter in the string. If it has a larger Roman numeral
// equivalent than number, then the two letters are counted together as
// a Roman numeral with value (nextNumber - number).
int nextNumber = letterToNumber(roman.charAt(i));
if (nextNumber > number) {
// Combine the two letters to get one value, and move on to next position in string.
arabic += (nextNumber - number);
i++;
}
else {
// Don't combine the letters. Just add the value of the one letter onto the number.
arabic += number;
}
}
} // end while
if (arabic > 3999)
throw new NumberFormatException("Roman numeral must have value 3999 or less.");
num = arabic;
} // end constructor
/**
* Find the integer value of letter considered as a Roman numeral. Throws
* NumberFormatException if letter is not a legal Roman numeral. The letter
* must be upper case.
*/
private int letterToNumber(char letter) {
switch (letter) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: throw new NumberFormatException(
"Illegal character \"" + letter + "\" in Roman numeral");
}
}
/**
* Return the standard representation of this Roman numeral.
*/
public String toString() {
String roman = ""; // The roman numeral.
int N = num; // N represents the part of num that still has
// to be converted to Roman numeral representation.
for (int i = 0; i < numbers.length; i++) {
while (N >= numbers[i]) {
roman += letters[i];
N -= numbers[i];
}
}
return roman;
}
/**
* Return the value of this Roman numeral as an int.
*/
public int toInt() {
return num;
}
}
Use myList.get(3)
to get access to the current object and modify it, assuming instances of Customer
have a way to be modified.
You can send Email by Jquery just follow these steps
include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :
$( document ).ready(function() {
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});
With Java 8 Streams:
Stream.of(object).collect(Collectors.toList())
or if you need a set:
Stream.of(object).collect(Collectors.toSet())
Try
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
_x000D_
<select id="mySelect">
<option value="A">Text A</option>
<option value="B">Text B</option>
<option value="C">Text C</option>
</select>
_x000D_
Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:
a = (1, 2, 3)
b = a + (4, 5, 6) # (1, 2, 3, 4, 5, 6)
c = b[1:] # (2, 3, 4, 5, 6)
And, of course, build them from existing values:
name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)
It is worth to check if you have refactored package name of your main class annotated with @SpringBootApplication
. In that case the testcase should be in an appropriate package otherwise it will be looking for it in the older package . this was the case for me.
its pretty easy if u just want to redirect to a url without any status codes or anything like that u can simple say
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/')
def redirect_to_link():
# return redirect method, NOTE: replace google.com with the link u want
return redirect('https://google.com')
Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:
$ date
If the date and/or time is incorrect, try to update using:
$ sudo ntpdate -u time.nist.gov
Something like this:
ARGV.each do|a|
puts "Argument: #{a}"
end
then
$ ./test.rb "test1 test2"
or
v1 = ARGV[0]
v2 = ARGV[1]
puts v1 #prints test1
puts v2 #prints test2
There are a couple of ways to solve this. The least hackiest and almost what you want:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
)
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);
This gets you the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
<SOAP-ENV:Body>
<ns1:Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</ns1:Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo>
tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT,
to the options array like this:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
'style' => SOAP_DOCUMENT,
)
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);
This results in the following request XML:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.
Look at bda.cache http://pypi.python.org/pypi/bda.cache - uses ZCA and is tested with zope and bfg.
Here is some LESS for you, in case you customize the navbar:
.navbar .divider-vertical {
height: floor(@navbar-height - @navbar-margin-bottom);
margin: floor(@navbar-margin-bottom / 2) 9px;
border-left: 1px solid #f2f2f2;
border-right: 1px solid #ffffff;
}
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + " years";
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + " months";
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + " days";
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + " hours";
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + " minutes";
}
return Math.floor(seconds) + " seconds";
}
var aDay = 24*60*60*1000;
console.log(timeSince(new Date(Date.now()-aDay)));
console.log(timeSince(new Date(Date.now()-aDay*2)));
_x000D_
Ah yes. Welcome to Asynchronous execution.
Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.
Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.
The solutions posted here don't work in non-ascii characters (i.e. if you plan to exchange base64 between Node.js and a browser). In order to make it work you have to mark the input text as 'binary'.
Buffer.from('Hélló wórld!!', 'binary').toString('base64')
This gives you SOlsbPMgd/NybGQhIQ==
. If you make atob('SOlsbPMgd/NybGQhIQ==')
in a browser it will decode it in the right way. It will do it right also in Node.js via:
Buffer.from('SOlsbPMgd/NybGQhIQ==', 'base64').toString('binary')
If you don't do the "binary part", you will decode wrongly the special chars.
Forcing the TCP/IP connection (by providing 127.0.0.1
instead of localhost
or .
) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.
So, here is the checklist so far:
Check this link for steps on how to install express.js for your application locally.
But, if for some reason you are installing express globally, make sure the directory you are in is the directory where Node is installed. On my Windows 10, package.json is located at
C:\Program Files\nodejs\node_modules\npm
Open command prompt as administrator and change your directory to the location where your package.json is located.
Then issue the install command.
The spring configuration precedence is as follows.
So your configuration will be overridden at the command-line if you wish to do that. But the recommendation is to avoid overriding, though you can use multiple profiles.
This is based on @Reid's solution. Except:
Array
prototype.undefined
items, it just moves the item to the right-most position.Function:
function move(array, oldIndex, newIndex) {
if (newIndex >= array.length) {
newIndex = array.length - 1;
}
array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
return array;
}
Unit tests:
describe('ArrayHelper', function () {
it('Move right', function () {
let array = [1, 2, 3];
arrayHelper.move(array, 0, 1);
assert.equal(array[0], 2);
assert.equal(array[1], 1);
assert.equal(array[2], 3);
})
it('Move left', function () {
let array = [1, 2, 3];
arrayHelper.move(array, 1, 0);
assert.equal(array[0], 2);
assert.equal(array[1], 1);
assert.equal(array[2], 3);
});
it('Move out of bounds to the left', function () {
let array = [1, 2, 3];
arrayHelper.move(array, 1, -2);
assert.equal(array[0], 2);
assert.equal(array[1], 1);
assert.equal(array[2], 3);
});
it('Move out of bounds to the right', function () {
let array = [1, 2, 3];
arrayHelper.move(array, 1, 4);
assert.equal(array[0], 1);
assert.equal(array[1], 3);
assert.equal(array[2], 2);
});
});
I did most of the suggested stuff here, still didnt work. Tried this and it worked: Open your XAMPP Control Panel, locate the Config button for the Apache module. Click on the Config button and Select PHP (php.ini). Open with any text editor and remove the semi-column before php_openssl. Save and Restart Apache. That should do!
This is a bit hackish combo of static and get works for me
class ConstantThingy{
static get NO_REENTER__INIT() {
if(ConstantThingy._NO_REENTER__INIT== null){
ConstantThingy._NO_REENTER__INIT = new ConstantThingy(false,true);
}
return ConstantThingy._NO_REENTER__INIT;
}
}
elsewhere used
var conf = ConstantThingy.NO_REENTER__INIT;
if(conf.init)...
var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");
Use the global(g
) flag
In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.
In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.
Trying to get property of non-object
For Example:
if (!empty($this->xml_data->thing1->thing2))
{
foreach ($this->xml_data->thing1->thing2 as $thing)
{
}
}
Use this one
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// Get the layout inflater
LayoutInflater inflater = (activity).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the
// dialog layout
builder.setTitle(title);
builder.setCancelable(false);
builder.setIcon(R.drawable.galleryalart);
builder.setView(inflater.inflate(R.layout.dialogue, null))
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
}
});
builder.create();
builder.show();
If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?
If you do use placeholders, ^
and $
match the beginning and the end of a string, respectively.
Or with the power of Java 8 Optional, you also can do such trick:
Optional.ofNullable(boolValue).orElse(false)
:)
This is often caused by the (accidental) removal of the JRE folder that is set in the Eclipse configuration. You can try following these instructions from the Eclipse wiki on how to configure the eclipse.ini file to include the the JRE location, or alternatively, launch eclipse from the command prompt using VM arguments. I have tried them both myself and in my opinion, the command prompt option works much better.
Once you are able to launch Eclipse, make sure you verify the installed JRE location under Java --> Installed JREs in the Preferences window.
I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.
if (a > 0)
answer = compute(a, b, c, d, e);
else
answer = compute(-a, b, c, d, e);
With a ternary operator, this could be accomplished with the following.
answer = compute(a > 0 ? a : -a, b, c, d, e);
Try this code:
$(document).ready(function(){
$('#YourControlID').click(function(){
if() { //your condition
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
}
});
});
You can use method getDate():
$('#calendar').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
alert(day + '-' + month + '-' + year);
}
});
302 is temporary redirect, which is generated by the server whereas 307 is internal redirect response generated by the browser. Internal redirect means that redirect is done automatically by browser internally, basically the browser alters the entered url from http to https in get request by itself before making the request so request for unsecured connection is never made to the internet. Whether browser will alter the url to https or not depends upon the hsts preload list that comes preinstalled with the browser. You can also add any site which support https to the list by entering the domain in the hsts preload list of your own browser which is at chrome://net-internals/#hsts.One more thing website domains can be added by their owners to preload list by filling up the form at https://hstspreload.org/ so that it comes preinstalled in browsers for every user even though I mention you can do particularly for yourself also.
Let me explain with an example:
I made a get request to http://www.pentesteracademy.com which supports only https and I don't have that domain in my hsts preload list on my browser as site owner has not registered for it to come with preinstalled hsts preload list.
GET request for unsecure version of the site is redirected to secure version(see http header named location for that in response in above image).
Now I add the site to my own browser preload list by adding its domain in Add hsts domain form at chrome://net-internals/#hsts, which modifies my personal preload list on my chrome browser.Be sure to select include subdomains for STS option there.
Let's see the request and response for the same website now after adding it to hsts preload list.
you can see the internal redirect 307 there in response headers, actually this response is generated by your browser not by server.
Also HSTS preload list can help prevent users reach the unsecure version of site as 302 redirect are prone to mitm attacks.
Hope I somewhat helped you understand more about redirects.
Take a look at cat /proc/stat
grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.
NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.
Current CPU usage can be potentially calculated with:
awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)
If you have a lateinit
property in one class and need to check if it is initialized from another class
if(foo::file.isInitialized) // this wouldn't work
The workaround I have found is to create a function to check if the property is initialized and then you can call that function from any other class.
Example:
class Foo() {
private lateinit var myFile: File
fun isFileInitialised() = ::file.isInitialized
}
// in another class
class Bar() {
val foo = Foo()
if(foo.isFileInitialised()) // this should work
}
A class that takes a required dependency as a constructor argument can only be instantiated if that argument is provided (you should have a guard clause to make sure the argument is not null.) A constructor therefore enforces the dependency requirement whether or not you're using Spring, making it container-agnostic.
If you use setter injection, the setter may or may not be called, so the instance may never be provided with its dependency. The only way to force the setter to be called is using @Required
or @Autowired
, which is specific to Spring and is therefore not container-agnostic.
So to keep your code independent of Spring, use constructor arguments for injection.
Update: Spring 4.3 will perform implicit injection in single-constructor scenarios, making your code more independent of Spring by potentially not requiring an @Autowired
annotation at all.
Here's how you should do it:
change_column :users, :admin, :boolean, :default => false
But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.
How about creating a timer with the next date?
In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create. DateTime is always represents a specific date and time but not a recurring date.
If you think the space before and after "=" is mandatory, try it as separate item in the list.
Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Swift 4
In Info.plist
add this property
View controller-based status bar appearance to NO
and after that in AppDelegate
inside the didFinishLaunchingWithOptions
add these lines of code
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent
You should create the response using Request.CreateResponse:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");
You can pass objects not just strings to CreateResponse and it will serialize them based on the request's Accept header. This saves you from manually choosing a formatter.