This code creates a nice vertical scrollbar for me in Firefox and Chrome:
#answerform {
position: absolute;
border: 5px solid gray;
padding: 5px;
background: white;
width: 300px;
height: 400px;
overflow-y: scroll;
}
_x000D_
<div id='answerform'>
badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
<br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
Here is a JS fiddle demo proving the above works.
Try this jsfiddle. This is using jQuery and made from Hashem Qolami's answer. At first, make a regular table then make it scrollable.
const makeScrollableTable = function (tableSelector, tbodyHeight) {
let $table = $(tableSelector);
let $bodyCells = $table.find('tbody tr:first').children();
let $headCells = $table.find('thead tr:first').children();
let headColWidth = 0;
let bodyColWidth = 0;
headColWidth = $headCells.map(function () {
return $(this).outerWidth();
}).get();
bodyColWidth = $bodyCells.map(function () {
return $(this).outerWidth();
}).get();
$table.find('thead tr').children().each(function (i, v) {
$(v).css("width", headColWidth[i]+"px");
$(v).css("min-width", headColWidth[i]+"px");
$(v).css("max-width", headColWidth[i]+"px");
});
$table.find('tbody tr').children().each(function (i, v) {
$(v).css("width", bodyColWidth[i]+"px");
$(v).css("min-width", bodyColWidth[i]+"px");
$(v).css("max-width", bodyColWidth[i]+"px");
});
$table.find('thead').css("display", "block");
$table.find('tbody').css("display", "block");
$table.find('tbody').css("height", tbodyHeight+"px");
$table.find('tbody').css("overflow-y", "auto");
$table.find('tbody').css("overflow-x", "hidden");
};
Then you can use this function as follows:
makeScrollableTable('#test-table', 250);
Try using the following code snippet. This should solve your issue.
body, html {
overflow-x: hidden;
overflow-y: auto;
}
Solved jQuery: Add element after another element
<script>
$( "p" ).append( "<strong>Hello</strong>" );
</script>
OR
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery ( ".sidebar_cart" ) .append( "<a href='http://#'>Continue Shopping</a>" );
});
</script>
One could use the queryParam method, passing it parameter name and an array of values:
public WebTarget queryParam(String name, Object... values);
Example (jersey-client 2.23.2):
WebTarget target = ClientBuilder.newClient().target(URI.create("http://localhost"));
target.path("path")
.queryParam("param_name", Arrays.asList("paramVal1", "paramVal2").toArray())
.request().get();
This will issue request to following URL:
http://localhost/path?param_name=paramVal1¶m_name=paramVal2
In Swift 3.0 (this is a little bit faster and safer than the accepted answer) :
extension String {
func firstCharacterUpperCase() -> String {
if let firstCharacter = characters.first {
return replacingCharacters(in: startIndex..<index(after: startIndex), with: String(firstCharacter).uppercased())
}
return ""
}
}
nameOfString.capitalized won't work, it will capitalize every words in the sentence
You can break up long lines with the caret ^
as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)
Example:
copy file1.txt file2.txt
would be written as:
copy file1.txt^
file2.txt
Use regular expression
var totalWords = "foo love bar very much.";_x000D_
_x000D_
var firstWord = totalWords.replace(/ .*/,'');_x000D_
_x000D_
$('body').append(firstWord);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.
Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.
One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.
You can do something like
for(var k in result) {
console.log(k, result[k]);
}
which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use
typeof result[k] === "object"
to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.
The icon file is added to your project as a content file.
Give class img-fluid
to your div
carousel-item
.Finally it will be:
<div class="carousel-item active img-fluid">
<img class="d-block w-100" src="path to image" alt="First slide">
</div>
You want this - enter N and then take N number of elements.I am considering your input case is just like this
5
2 3 6 6 5
have this in this way in python 3.x (for python 2.x use raw_input()
instead if input()
)
n = int(input())
arr = input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
n = int(raw_input())
arr = raw_input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
When you write the following line of code in TypeScript:
var SUCSS = {};
The type of SUCSS
is inferred from the assignment (i.e. it is an empty object type).
You then go on to add a property to this type a few lines later:
SUCSS.fadeDiv = //...
And the compiler warns you that there is no property named fadeDiv
on the SUCSS
object (this kind of warning often helps you to catch a typo).
You can either... fix it by specifying the type of SUCSS
(although this will prevent you from assigning {}
, which doesn't satisfy the type you want):
var SUCSS : {fadeDiv: () => void;};
Or by assigning the full value in the first place and let TypeScript infer the types:
var SUCSS = {
fadeDiv: function () {
// Simplified version
alert('Called my func');
}
};
Note: I updated this answer based on comments and other answers, so comments prior to May 22nd 2020 may no longer apply. Also I noticed today that some IDE's like VS Code and PyCharm do not recognize a HEREDOC marker that contains spaces, whereas bash has no problem with it, so I'm updating this answer again.
Bash does not provide a builtin syntax for multi-line comment but there are hacks using existing bash syntax that "happen to work now".
Personally I think the simplest (ie least noisy, least weird, easiest to type, most explicit) is to use a quoted HEREDOC, but make it obvious what you are doing, and use the same HEREDOC marker everywhere:
<<'###BLOCK-COMMENT'
line 1
line 2
line 3
line 4
###BLOCK-COMMENT
Single-quoting the HEREDOC marker avoids some shell parsing side-effects, such as weird subsitutions that would cause crash or output, and even parsing of the marker itself. So the single-quotes give you more freedom on the open-close comment marker.
For example the following uses a triple hash which kind of suggests multi-line comment in bash. This would crash the script if the single quotes were absent. Even if you remove ###
, the FOO{}
would crash the script (or cause bad substitution to be printed if no set -e
) if it weren't for the single quotes:
set -e
<<'###BLOCK-COMMENT'
something something ${FOO{}} something
more comment
###BLOCK-COMMENT
ls
You could of course just use
set -e
<<'###'
something something ${FOO{}} something
more comment
###
ls
but the intent of this is definitely less clear to a reader unfamiliar with this trickery.
Note my original answer used '### BLOCK COMMENT'
, which is fine if you use vanilla vi/vim but today I noticed that PyCharm and VS Code don't recognize the closing marker if it has spaces.
Nowadays any good editor allows you to press ctrl-/ or similar, to un/comment the selection. Everyone definitely understands this:
# something something ${FOO{}} something
# more comment
# yet another line of comment
although admittedly, this is not nearly as convenient as the block comment above if you want to re-fill your paragraphs.
There are surely other techniques, but there doesn't seem to be a "conventional" way to do it. It would be nice if ###>
and ###<
could be added to bash to indicate start and end of comment block, seems like it could be pretty straightforward.
Please select the entire sheet and HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=A1<>XFD1
Format..., select choice of formatting, OK, OK.
This is for newer version of Hadoop (I am running 2.4.0)
In the file: hdfs-site.xml Look out for directory paths corresponding to dfs.namenode.name.dir dfs.namenode.data.dir
Hope this helps.
A combination of a few things eventually got things working on my end. Running a flask server on macosx.
In my windows VM I edited the hosts file:
C:\windows\system32\drivers\etc\hosts
10.0.2.2 outer
Shutdown VM and on my Mac in VirtualBox:
VirtualBox > preferences > Network > Host-only Networks > +
to add a network vboxnet1
My_VM > settings > Network > Adapter 1
. Enable Network Adapter
and set Attached to:
to Bridged Adapter
. Advanced > Promiscuous Mode:
to Allow VMs
. OK
My_VM > settings > Network > Adapter 1
. Attached to:
back to NAT
. Then I went to Adapter 2
Attached to:
to Host-only Adapter
and select the previous added network vboxnet1
. I started my server on my mac, running on 127.0.0.1:5000
and this was now accessible on my vm at http://10.0.2.2:5000
Man what a nightmare to test on IE on mac. How is there not a simpler way?
I had a similar issue recently while working on recursion and nested lists. I declared:
print(r_sum([1,2,3[1,2,3],]))
instead of
print(r_sum([1,2,3,[1,2,3],]))
Note the comma after the number 3
There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check out AnimatedScroll.js.
From the docs
Safety check 1
A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
Why do we need a safety check like this?
To answer this lets go though the initialization process in swift.
Two-Phase Initialization
Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
The use of a two-phase initialization process makes initialization safe, while still giving complete flexibility to each class in a class hierarchy. Two-phase initialization prevents property values from being accessed before they are initialized, and prevents property values from being set to a different value by another initializer unexpectedly.
So, to make sure the two step initialization process is done as defined above, there are four safety checks, one of them is,
Safety check 1
A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
Now, the two phase initialization never talks about order, but this safety check, introduces super.init
to be ordered, after the initialization of all the properties.
Safety check 1 might seem irrelevant as, Two-phase initialization prevents property values from being accessed before they are initialized can be satisfied, without this safety check 1.
Like in this sample
class Shape {
var name: String
var sides : Int
init(sides:Int, named: String) {
self.sides = sides
self.name = named
}
}
class Triangle: Shape {
var hypotenuse: Int
init(hypotenuse:Int) {
super.init(sides: 3, named: "Triangle")
self.hypotenuse = hypotenuse
}
}
Triangle.init
has initialized, every property before being used. So Safety check 1 seems irrelevant,
But then there could be another scenario, a little bit complex,
class Shape {
var name: String
var sides : Int
init(sides:Int, named: String) {
self.sides = sides
self.name = named
printShapeDescription()
}
func printShapeDescription() {
print("Shape Name :\(self.name)")
print("Sides :\(self.sides)")
}
}
class Triangle: Shape {
var hypotenuse: Int
init(hypotenuse:Int) {
self.hypotenuse = hypotenuse
super.init(sides: 3, named: "Triangle")
}
override func printShapeDescription() {
super.printShapeDescription()
print("Hypotenuse :\(self.hypotenuse)")
}
}
let triangle = Triangle(hypotenuse: 12)
Output :
Shape Name :Triangle
Sides :3
Hypotenuse :12
Here if we had called the super.init
before setting the hypotenuse
, the super.init
call would then have called the printShapeDescription()
and since that has been overridden it would first fallback to Triangle class implementation of printShapeDescription()
. The printShapeDescription()
of Triangle class access the hypotenuse
a non optional property that still has not been initialised. And this is not allowed as Two-phase initialization prevents property values from being accessed before they are initialized
So make sure the Two phase initialization is done as defined, there needs to be a specific order of calling super.init
, and that is, after initializing all the properties introduced by self
class, thus we need a Safety check 1
I don't think your problem is with the BouncyCastle keystore; I think the problem is with a broken javax.net.ssl package in Android. The BouncyCastle keystore is a supreme annoyance because Android changed a default Java behavior without documenting it anywhere -- and removed the default provider -- but it does work.
Note that for SSL authentication you may require 2 keystores. The "TrustManager" keystore, which contains the CA certs, and the "KeyManager" keystore, which contains your client-site public/private keys. (The documentation is somewhat vague on what needs to be in the KeyManager keystore.) In theory, you shouldn't need the TrustManager keystore if all of your certficates are signed by "well-known" Certifcate Authorities, e.g., Verisign, Thawte, and so on. Let me know how that works for you. Your server will also require the CA for whatever was used to sign your client.
I could not create an SSL connection using javax.net.ssl at all. I disabled the client SSL authentication on the server side, and I still could not create the connection. Since my end goal was an HTTPS GET, I punted and tried using the Apache HTTP Client that's bundled with Android. That sort-of worked. I could make the HTTPS conection, but I still could not use SSL auth. If I enabled the client SSL authentication on my server, the connection would fail. I haven't checked the Apache HTTP Client code, but I suspect they are using their own SSL implementation, and don't use javax.net.ssl.
Use UNION
:
SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks
Or UNION ALL
if you want duplicates:
SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION ALL
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks
Have a look at json_encode
(http://php.net/manual/en/function.json-encode.php). It is available as of PHP 5.2. Use the parameter dataType: 'json'
to have it parsed for you. You'll have the Object as the first argument in success then. For further information have a look at the jQuery-documentation: http://api.jquery.com/jQuery.ajax/
I normally use action="", which is XHTML valid and retains the GET data in the URL.
Yes. Hit Ctrl-R then ". If you have literal control characters in what you have yanked, use Ctrl-R, Ctrl-O, ".
Here is an explanation of what you can do with registers. What you can do with registers is extraordinary, and once you know how to use them you cannot live without them.
Registers are basically storage locations for strings. Vim has many registers that work in different ways:
0
(yank register: when you use y
in normal mode, without specifying a register, yanked text goes there and also to the default register),1
to 9
(shifting delete registers, when you use commands such as c
or d
, what has been deleted goes to register 1, what was in register 1 goes to register 2, etc.),"
(default register, also known as unnamed register. This is where the " comes in Ctrl-R, "),a
to z
for your own use (capitalized A
to Z
are for appending to corresponding registers)._
(acts like /dev/null
(Unix) or NUL
(Windows), you can write to it but it's discarded and when you read from it, it is always empty),-
(small delete register),/
(search pattern register, updated when you look for text with /
, ?
, *
or #
for instance; you can also write to it to dynamically change the search pattern),:
(stores last VimL typed command via Q
or :
, readonly),+
and *
(system clipboard registers, you can write to them to set the clipboard and read the clipboard contents from them)See :help registers
for the full reference.
You can, at any moment, use :registers
to display the contents of all registers. Synonyms and shorthands for this command are :display
, :reg
and :di
.
In Insert or Command-line mode, Ctrl-R plus a register name, inserts the contents of this register. If you want to insert them literally (no auto-indenting, no conversion of control characters like 0x08
to backspace, etc), you can use Ctrl-R, Ctrl-O, register name.
See :help i_CTRL-R
and following paragraphs for more reference.
But you can also do the following (and I probably forgot many uses for registers).
In normal mode, hit ":p. The last command you used in vim is pasted into your buffer.
Let's decompose: "
is a Normal mode command that lets you select what register is to be used during the next yank, delete or paste operation. So ": selects the colon register (storing last command). Then p is a command you already know, it pastes the contents of the register.
cf. :help "
, :help quote_:
You're editing a VimL file (for instance your .vimrc
) and would like to execute a couple of consecutive lines right now: yj:@"Enter.
Here, yj yanks current and next line (this is because j is a linewise motion but this is out of scope of this answer) into the default register (also known as the unnamed register). Then the :@
Ex command plays Ex commands stored in the register given as argument, and "
is how you refer to the unnamed register. Also see the top of this answer, which is related.
Do not confuse "
used here (which is a register name) with the "
from the previous example, which was a Normal-mode command.
cf. :help :@
and :help quote_quote
Insert the last search pattern into your file in Insert mode, or into the command line, with Ctrl-R, /.
cf. :help quote_/
, help i_CTRL-R
Corollary: Keep your search pattern but add an alternative: /
Ctrl-R, / \|alternative
.
You've selected two words in the middle of a line in visual mode, yanked them with y
, they are in the unnamed register. Now you want to open a new line just below where you are, with those two words: :pu
. This is shorthand for :put "
. The :put
command, like many Ex commands, works only linewise.
cf. :help :put
You could also have done: :call setreg('"', @", 'V')
then p
. The setreg
function sets the register of which the name is given as first argument (as a string), initializes it with the contents of the second argument (and you can use registers as variables with the name @x
where x
is the register name in VimL), and turns it into the mode specified in the third argument, V
for linewise, nothing for characterwise and literal ^V
for blockwise.
cf. :help setreg()
. The reverse functions are getreg()
and getregtype()
.
If you have recorded a macro with qa
...q
, then :echo @a
will tell you what you have typed, and @a
will replay the macro (probably you knew that one, very useful in order to avoid repetitive tasks)
cf. :help q
, help @
Corollary from the previous example: If you have 8go
in the clipboard, then @+
will play the clipboard contents as a macro, and thus go to the 8th byte of your file. Actually this will work with almost every register. If your last inserted string was dd
in Insert mode, then @.
will (because the .
register contains the last inserted string) delete a line. (Vim documentation is wrong in this regard, since it states that the registers #
, %
, :
and .
will only work with p
, P
, :put
and Ctrl-R).
cf. :help @
Don't confuse :@
(command that plays Vim commands from a register) and @
(normal-mode command that plays normal-mode commands from a register).
Notable exception is @:
. The command register does not contain the initial colon neither does it contain the final carriage return. However in Normal mode, @:
will do what you expect, interpreting the register as an Ex command, not trying to play it in Normal mode. So if your last command was :e
, the register contains e
but @:
will reload the file, not go to end of word.
cf. :help @:
Show what you will be doing in Normal mode before running it: @='dd'
Enter. As soon as you hit the =
key, Vim switches to expression evaluation: as you enter an expression and hit Enter, Vim computes it, and the result acts as a register content. Of course the register =
is read-only, and one-shot. Each time you start using it, you will have to enter a new expression.
cf. :help quote_=
Corollary: If you are editing a command, and you realize that you should need to insert into your command line some line from your current buffer: don't press Esc! Use Ctrl-R =getline(58)
Enter. After that you will be back to command line editing, but it has inserted the contents of the 58th line.
Define a search pattern manually: :let @/ = 'foo'
cf. :help :let
Note that doing that, you needn't to escape /
in the pattern. However you need to double all single quotes of course.
Copy all lines beginning with foo
, and afterwards all lines containing bar
to clipboard, chain these commands: qaq
(resets the a register storing an empty macro inside it), :g/^foo/y A
, :g/bar/y A
, :let @+ = @a
.
Using a capital register name makes the register work in append mode
Better, if Q
has not been remapped by mswin.vim
, start Ex mode with Q
, chain those “colon commands” which are actually better called “Ex commands”, and go back to Normal mode by typing visual
.
cf. :help :g
, :help :y
, :help Q
Double-space your file: :g/^/put _
. This puts the contents of the black hole register (empty when reading, but writable, behaving like /dev/null
) linewise, after each line (because every line has a beginning!).
Add a line containing foo
before each line: :g/^/-put ='foo'
. This is a clever use of the expression register. Here, -
is a synonym for .-1
(cf. :help :range
). Since :put
puts the text after the line, you have to explicitly tell it to act on the previous one.
Copy the entire buffer to the system clipboard: :%y+
.
cf. :help :range
(for the %
part) and :help :y
.
If you have misrecorded a macro, you can type :let @a='
Ctrl-R =replace(@a,"'","''",'g')
Enter '
and edit it. This will modify the contents of the macro stored in register a
, and it's shown here how you can use the expression register to do that.
If you did dddd
, you might do uu
in order to undo. With p
you could get the last deleted line. But actually you can also recover up to 9 deletes with the registers @1
through @9
.
Even better, if you do "1P
, then .
in Normal mode will play "2P
, and so on.
cf. :help .
and :help quote_number
If you want to insert the current date in Insert mode: Ctrl-R=strftime('%y%m%d')
Enter.
cf. :help strftime()
Once again, what can be confusing:
:@
is a command-line command that interprets the contents of a register as vimscript and sources it@
in normal mode command that interprets the contents of a register as normal-mode keystrokes (except when you use :
register, that contains last played command without the initial colon: in this case it replays the command as if you also re-typed the colon and the final return key).
"
in normal mode command that helps you select a register for yank, paste, delete, correct, etc.
"
is also a valid register name (the default, or unnamed, register) and therefore can be passed as an arguments for commands that expect register namesTry something like this:
var empList = ds.Tables[0].AsEnumerable()
.Select(dataRow => new Employee
{
Name = dataRow.Field<string>("Name")
}).ToList();
From a quick glance on MDN I think you may need to include the .js
at the end of your file name so the import would read
import './course.js'
instead of import './course'
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
You can't force the String arrays to have a specific size. You can do this:
private List<String[]> addresses = new ArrayList<String[]>();
but an array of any size can be added to this list.
However, as others have mentioned, the correct thing to do here is to create a separate class representing addresses. Then you would have something like:
private List<Address> addresses = new ArrayList<Address>();
add method container css in your script like this :
$("#your_select_id").select2({
containerCss : {"display":"block"}
});
it will set your select's width same as width your div.
If these commands don't work for you:
sudo killall mysqld
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start
Try this:
For XAMPP 7.1.1-0, I changed the port number from 3306 to 3307.
You are now good to go.
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
TextView textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.smallLabel);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.largeLabel);
textView.setTypeface(Typeface.DEFAULT_BOLD);
This should help to get distinct values of a column:
df.select('column1').distinct().collect()
Note that .collect()
doesn't have any built-in limit on how many values can return so this might be slow -- use .show()
instead or add .limit(20)
before .collect()
to manage this.
Public Function CheckWholeNumber(Number As Double) As Boolean
If Number - Fix(Number) = 0 Then
CheckWholeNumber = True
End If
End Function
Public Sub TimeDelay(Days As Double, Hours As Double, Minutes As Double, Seconds As Double)
If CheckWholeNumber(Days) = False Then
Hours = Hours + (Days - Fix(Days)) * 24
Days = Fix(Days)
End If
If CheckWholeNumber(Hours) = False Then
Minutes = Minutes + (Hours - Fix(Hours)) * 60
Hours = Fix(Hours)
End If
If CheckWholeNumber(Minutes) = False Then
Seconds = Seconds + (Minutes - Fix(Minutes)) * 60
Minutes = Fix(Minutes)
End If
If Seconds >= 60 Then
Seconds = Seconds - 60
Minutes = Minutes + 1
End If
If Minutes >= 60 Then
Minutes = Minutes - 60
Hours = Hours + 1
End If
If Hours >= 24 Then
Hours = Hours - 24
Days = Days + 1
End If
Application.Wait _
( _
Now + _
TimeSerial(Hours + Days * 24, Minutes, 0) + _
Seconds * TimeSerial(0, 0, 1) _
)
End Sub
example:
call TimeDelay(1.9,23.9,59.9,59.9999999)
hopy you enjoy.
edit:
here's one without any additional functions, for people who like it being faster
Public Sub WaitTime(Days As Double, Hours As Double, Minutes As Double, Seconds As Double)
If Days - Fix(Days) > 0 Then
Hours = Hours + (Days - Fix(Days)) * 24
Days = Fix(Days)
End If
If Hours - Fix(Hours) > 0 Then
Minutes = Minutes + (Hours - Fix(Hours)) * 60
Hours = Fix(Hours)
End If
If Minutes - Fix(Minutes) > 0 Then
Seconds = Seconds + (Minutes - Fix(Minutes)) * 60
Minutes = Fix(Minutes)
End If
If Seconds >= 60 Then
Seconds = Seconds - 60
Minutes = Minutes + 1
End If
If Minutes >= 60 Then
Minutes = Minutes - 60
Hours = Hours + 1
End If
If Hours >= 24 Then
Hours = Hours - 24
Days = Days + 1
End If
Application.Wait _
( _
Now + _
TimeSerial(Hours + Days * 24, Minutes, 0) + _
Seconds * TimeSerial(0, 0, 1) _
)
End Sub
follow he steps. in pgadmin
host-DataBase-Schemas- public (click right) CREATE script- open file -(choose xxx.sql) , then click over the option execute query write result to file -export data file ok- then click in save.its all. it work to me.
note: error in version command script enter image description herede sql over pgadmin can be search, example: http://www.forosdelweb.com/f21/campo-tipo-datetime-postgresql-245389/
With gradle, I replaced this line at build.gradle.kts file inside dependencies block
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
with this
compile("org.springframework.boot:spring-boot-starter-web")
and works fine.
Starting with Jackson 2.6, a property can be marked as read- or write-only. It's simpler than hacking the annotations on both accessors and keeps all the information in one place:
public class User {
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
}
I'm not sure what your problem is, but the following seems to work OK:
#include <stdio.h>
int main()
{
const char s0[] = "ABCD";
const char s1[] = { s0[3], s0[2], s0[1], s0[0], 0 };
puts(s0);
puts(s1);
return 0;
}
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
cl /Od /D "WIN32" /D "_CONSOLE" /Gm /EHsc /RTC1 /MLd /W3 /c /ZI /TC
.\Tmp.c
Tmp.c
Linking...
Build Time 0:02
C:\Tmp>tmp.exe
ABCD
DCBA
C:\Tmp>
Edit 9 June 2009
If you need global access, you might need something ugly like this:
#include <stdio.h>
const char *GetString(int bMunged)
{
static char s0[5] = "ABCD";
static char s1[5];
if (bMunged) {
if (!s1[0]) {
s1[0] = s0[3];
s1[1] = s0[2];
s1[2] = s0[1];
s1[3] = s0[0];
s1[4] = 0;
}
return s1;
} else {
return s0;
}
}
#define S0 GetString(0)
#define S1 GetString(1)
int main()
{
puts(S0);
puts(S1);
return 0;
}
Although all other answers are technically correct, I would recommend you adding the custom path to the beginning of your PATH, not at the end. That way it would be the first place to look for instead of the last:
Add to bottom of ~/.bash_profile
:
export PATH="/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/":$PATH
That way if you have more than one java
or javac
it will use the one you provided first.
for SQL > odd:
select * from id in(select id from employee where id%2=1)
for SQL > Even:
select * from id in(select id from employee where id%2=0).....f5
Just add Eloquent::unguard();
in the top of the run method when you do a seed, no need to create an $fillable
array in all the models you have to seed.
Normally this is already specified in the DatabaseSeeder
class. However because you're calling the UsersTableSeeder
directly:
php artisan db:seed --class="UsersTableSeeder"
Eloquent::unguard();
isn't being called and gives the error.
I believe document.documentElement.outerHTML
should return that for you.
According to MDN, outerHTML
is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML
is in the DOM Parsing and Serialization specification.
The MSDN page on the outerHTML
property notes that it is supported in IE 5+. Colin's answer links to the W3C quirksmode page, which offers a good comparison of cross-browser compatibility (for other DOM features too).
@RequestParam
annotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:
request:
GET: http://someserver.org/path?name=John&surname=Smith
endpoint code:
public User getUser(@RequestParam(value = "name") String name,
@RequestParam(value = "surname") String surname){
...
}
So basically, while @RequestBody
maps entire user request (even for POST) to a String variable, @RequestParam
does so with one (or more - but it is more complicated) request param to your method argument.
I've used this. Add a script reference to jquery on the Report.aspx page. Use the following to link up JQuery to the microsoft events. Used a little bit of Eric's suggestion for setting the overflow.
$(document).ready(function () {
if (navigator.userAgent.toLowerCase().indexOf("webkit") >= 0) {
Sys.Application.add_init(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm.get_isInAsyncPostBack()) {
prm.add_endRequest(function () {
var divs = $('table[id*=_fixedTable] > tbody > tr:last > td:last > div')
divs.each(function (idx, element) {
$(element).css('overflow', 'visible');
});
});
}
});
}
});
You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it. After that, you start your cmd with admin privileges, then try:
netsh wlan start hostednetwork
I found this expression simplest
String[] extractednums = msg.split("\\\\D++");
Your HTML:
<div class="img-with-text">
<img src="yourimage.jpg" alt="sometext" />
<p>Some text</p>
</div>
If you know the width of your image, your CSS:
.img-with-text {
text-align: justify;
width: [width of img];
}
.img-with-text img {
display: block;
margin: 0 auto;
}
Otherwise your text below the image will free-flow. To prevent this, just set a width to your container.
swift 3
if let url = URL(string: "fb://profile/<id>") {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:],completionHandler: { (success) in
print("Open fb://profile/<id>: \(success)")
})
} else {
let success = UIApplication.shared.openURL(url)
print("Open fb://profile/<id>: \(success)")
}
}
In the closure you pass to sort
, compare the properties you want to sort by. Like this:
movieArr.sorted { $0.name < $1.name }
or the following in the cases that you want to bypass cases:
movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }
Sidenote: Typically only types start with an uppercase letter; I'd recommend using name
and date
, not Name
and Date
.
Example, in a playground:
class Movie {
let name: String
var date: Int?
init(_ name: String) {
self.name = name
}
}
var movieA = Movie("A")
var movieB = Movie("B")
var movieC = Movie("C")
let movies = [movieB, movieC, movieA]
let sortedMovies = movies.sorted { $0.name < $1.name }
sortedMovies
sortedMovies
will be in the order [movieA, movieB, movieC]
Swift5 Update
channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
let channelName1 = channel1.name
let channelName2 = channel2.name
return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Or, if you insist on making work for yourself...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
The Google reCAPTCHA version 2 ASP.Net allows validating the Captcha response on the client side using its Callback functions. In this example, the Google new reCAPTCHA will be validated using ASP.Net RequiredField Validator.
<script type="text/javascript">
var onloadCallback = function () {
grecaptcha.render('dvCaptcha', {
'sitekey': '<%=ReCaptcha_Key %>',
'callback': function (response) {
$.ajax({
type: "POST",
url: "Demo.aspx/VerifyCaptcha",
data: "{response: '" + response + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var captchaResponse = jQuery.parseJSON(r.d);
if (captchaResponse.success) {
$("[id*=txtCaptcha]").val(captchaResponse.success);
$("[id*=rfvCaptcha]").hide();
} else {
$("[id*=txtCaptcha]").val("");
$("[id*=rfvCaptcha]").show();
var error = captchaResponse["error-codes"][0];
$("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
}
}
});
}
});
};
</script>
<asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
<asp:RequiredFieldValidator ID="rfvCaptcha" ErrorMessage="The CAPTCHA field is required." ControlToValidate="txtCaptcha"
runat="server" ForeColor="Red" Display="Dynamic" />
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
Always try to use the bufio.NewScanner for collecting input from the console. As others mentioned, there are multiple ways to do the job but Scanner is originally intended to do the job. Dave Cheney explains why you should use Scanner instead of bufio.Reader's ReadLine.
https://twitter.com/davecheney/status/604837853344989184?lang=en
Here is the code snippet answer for your question
package main
import (
"bufio"
"fmt"
"os"
)
/*
Three ways of taking input
1. fmt.Scanln(&input)
2. reader.ReadString()
3. scanner.Scan()
Here we recommend using bufio.NewScanner
*/
func main() {
// To create dynamic array
arr := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter Text: ")
// Scans a line from Stdin(Console)
scanner.Scan()
// Holds the string that scanned
text := scanner.Text()
if len(text) != 0 {
fmt.Println(text)
arr = append(arr, text)
} else {
break
}
}
// Use collected inputs
fmt.Println(arr)
}
If you don't want to programmatically collect the inputs, just add these lines
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
text := scanner.Text()
fmt.Println(text)
The output of above program will be:
Enter Text: Bob
Bob
Enter Text: Alice
Alice
Enter Text:
[Bob Alice]
Above program collects the user input and saves them to an array. We can also break that flow with a special character. Scanner provides API for advanced usage like splitting using a custom function etc, scanning different types of I/O streams(Stdin, String) etc.
I solved this problem by going to folder .vagrant.d/boxes/
under your home and changed name of the folder from laravel-VAGRANTSLASH-homestead
to base
.
And it worked for me.
Please check if virtualization is enabled in your BIOS.
Try Like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
function index(){
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
}
}
?>
You can do this instead too:
tasklist | find /I "test.exe" > nul && taskkill /f /im test.exe > nul
Remove the required: true
rule.
Demo: Fiddle
jQuery('.validatedForm').validate({
rules : {
password : {
minlength : 5
},
password_confirm : {
minlength : 5,
equalTo : "#password"
}
}
Some more:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25
Check out the static java.util.Arrays.equals()
family of methods. There's one that does exactly what you want.
If an element is not part of the visual tree, then RelativeSource will never work.
In this case, you need to try a different technique, pioneered by Thomas Levesque.
He has the solution on his blog under [WPF] How to bind to data when the DataContext is not inherited. And it works absolutely brilliantly!
In the unlikely event that his blog is down, Appendix A contains a mirror copy of his article.
Please do not comment here, please comment directly on his blog post.
The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don’t need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…
Let’s illustrate with a simple example: we want to display a list of products in a DataGrid. In the grid, we want to be able to show or hide the Price column, based on the value of a ShowPrice property exposed by the ViewModel. The obvious approach is to bind the Visibility of the column to the ShowPrice property:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
Visibility="{Binding ShowPrice,
Converter={StaticResource visibilityConverter}}"/>
Unfortunately, changing the value of ShowPrice has no effect, and the column is always visible… why? If we look at the Output window in Visual Studio, we notice the following line:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is ‘DataGridTextColumn’ (HashCode=32685253); target property is ‘Visibility’ (type ‘Visibility’)
The message is rather cryptic, but the meaning is actually quite simple: WPF doesn’t know which FrameworkElement to use to get the DataContext, because the column doesn’t belong to the visual or logical tree of the DataGrid.
We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the DataGrid itself:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
Visibility="{Binding DataContext.ShowPrice,
Converter={StaticResource visibilityConverter},
RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>
Or we can add a CheckBox bound to ShowPrice, and try to bind the column visibility to the IsChecked property by specifying the element name:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
Visibility="{Binding IsChecked,
Converter={StaticResource visibilityConverter},
ElementName=chkShowPrice}"/>
But none of these workarounds seems to work, we always get the same result…
At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I’m not going to give up so soon, at least not while there are other options to consider
The solution to our problem is actually quite simple, and takes advantage of the Freezable class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable objects can inherit the DataContext even when they’re not in the visual or logical tree. I don’t know the exact mechanism that enables this behavior, but we’re going to take advantage of it to make our binding work…
The idea is to create a class (I called it BindingProxy for reasons that should become obvious very soon) that inherits Freezable and declares a Data dependency property:
public class BindingProxy : Freezable
{
#region Overrides of Freezable
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
#endregion
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}
We can then declare an instance of this class in the resources of the DataGrid, and bind the Data property to the current DataContext:
<DataGrid.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>
The last step is to specify this BindingProxy object (easily accessible with StaticResource) as the Source for the binding:
<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
Visibility="{Binding Data.ShowPrice,
Converter={StaticResource visibilityConverter},
Source={StaticResource proxy}}"/>
Note that the binding path has been prefixed with “Data”, since the path is now relative to the BindingProxy object.
The binding now works correctly, and the column is properly shown or hidden based on the ShowPrice property.
Another thing to keep in mind is there are two different CASEs with MySQL: one like what @cdhowie and others describe here (and documented here: http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case) and something which is called a CASE, but has completely different syntax and completely different function, documented here: https://dev.mysql.com/doc/refman/5.0/en/case.html
Invariably, I first use one when I want the other.
This solution is what we are using:
def test_date_invalidformat():
"""
Test if input incorrect data will raises ValueError exception
"""
date = "06/21/2018 00:00:00"
with pytest.raises(ValueError):
app.func(date) #my function to be tested
Please refer to pytest, https://docs.pytest.org/en/latest/reference.html#pytest-raises
To return true or false depending on whether a checkbox is checked or not, I use this in JQuery
let checkState = $("#checkboxId").is(":checked") ? "true" : "false";
There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__
.
df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
For example, to get every 2 rows, you can do
df[::2]
a b c
0 x x x
2 x x x
4 x x x
There's also GroupBy.first
/GroupBy.head
, you group on the index:
df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')
df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)
a b c
0 x x x
1 x x x
2 x x x
The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do
# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()
a b c
0 x x x
1 x x x
2 x x x
The LDF stand for 'Log database file' and it is the transaction log. It keeps a record of everything done to the database for rollback purposes, you can restore a database even you lost .msf file because it contain all control information plus transaction information .
I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:
SELECT * FROM match WHERE id NOT IN
( SELECT id FROM email WHERE id IS NOT NULL) ;
SELECT
m.*
FROM
match m
LEFT OUTER JOIN email e ON
m.id = e.id
AND e.id IS NOT NULL
WHERE
e.id IS NULL
The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.
I use this function htmlentities($string):
$msg = "<script>alert("hello")</script> <h1> Hello World </h1>" $msg = htmlentities($msg); echo $msg;
As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary.
The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need this even if you use LoadLibrary.
To link with the library, you might have to add the .lib file to the project configuration under Linker/Input/Additional Dependencies.
Here's my method of fixing this issue.
Okay, so in this example, my .dll is definitely 2.0.5022.0 (so the Exception version number is wrong).
So, in this example, I would replace this...
<Reference Include="DocumentFormat.OpenXml, Version=2.5.5631.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
... with this...
<Reference Include="DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
Job done !
I depends on the version and the distro.
For example the default download pre-2.2 from the MongoDB site uses: /data/db
but the Ubuntu install at one point used to use: var/lib/mongodb
.
I think these have been standardised now so that 2.2+ will only use data/db
whether it comes from direct download on the site or from the repos.
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"_x000D_
_x000D_
let output = str.replace(/\?.+/g,"$'")_x000D_
_x000D_
console.log(output)
_x000D_
This is your array
products: any = [
{
"name": "John-Cena",
},
{
"name": "Brock-Lensar",
}
];
This is your ngFor loop Filter By :
<input type="text" [(ngModel)]='filterText' />
<ul *ngFor='let product of filterProduct'>
<li>{{product.name }}</li>
</ul>
There I'm using filterProduct instant of products, because i want to preserve my original data. Here model _filterText is used as a input box.When ever there is any change setter function will call. In setFilterText performProduct is called it will return the result only those who match with the input. I'm using lower case for case insensitive.
filterProduct = this.products;
_filterText : string;
get filterText() : string {
return this._filterText;
}
set filterText(value : string) {
this._filterText = value;
this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;
}
performProduct(value : string ) : any {
value = value.toLocaleLowerCase();
return this.products.filter(( products : any ) =>
products.name.toLocaleLowerCase().indexOf(value) !== -1);
}
This worked for me
python -m pip install cx_Oracle --upgrade
For details refer to the oracle quick start guide
https://cx-oracle.readthedocs.io/en/latest/installation.html#quick-start-cx-oracle-installation
You should check it against null
.
If you want to check if object x is null or not, you can do:
if(x != null)
But if it is not null, it can have properties which are null or empty. You will check those explicitly:
if(x.getProperty() != null)
For "empty" check, it depends on what type is involved. For a Java String
, you usually do:
if(str != null && !str.isEmpty())
As you haven't mentioned about any specific problem with this, difficult to tell.
The simplest (but not the fastest) way to iterate a directory tree and list relative file paths is to use FORFILES.
forfiles /s /m *.txt /c "cmd /c echo @relpath"
The relative paths will be quoted with a leading .\
as in
".\Doc1.txt"
".\subdir\Doc2.txt"
".\subdir\Doc3.txt"
To remove quotes:
for /f %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do echo %%~A
To remove quotes and the leading .\
:
setlocal disableDelayedExpansion
for /f "delims=" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do (
set "file=%%~A"
setlocal enableDelayedExpansion
echo !file:~2!
endlocal
)
or without using delayed expansion
for /f "tokens=1* delims=\" %%A in (
'forfiles /s /m *.txt /c "cmd /c echo @relpath"'
) do for %%F in (^"%%B) do echo %%~F
Do it like this...
if (!Array.prototype.indexOf) {
}
As recommended compatibility by MDC.
In general, browser detection code is a big no-no.
Try this, it will worked. I used it for Hashtable.
public static Hashtable<Integer, KioskStatusResource> parseModifued(String json) {
JsonObject object = (JsonObject) new com.google.gson.JsonParser().parse(json);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
Hashtable<Integer, KioskStatusResource> map = new Hashtable<Integer, KioskStatusResource>();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
Integer key = Integer.parseInt(entry.getKey());
KioskStatusResource value = new Gson().fromJson(entry.getValue(), KioskStatusResource.class);
if (value != null) {
map.put(key, value);
}
}
return map;
}
Replace KioskStatusResource to your class and Integer to your key class.
I know that the response is late, but the best way to execute sqlite queries in android is through a custom content provider. In that way the UI is decoupled with the database class(the class that extends the SQLiteOpenHelper class). Also the queries are executed in a background thread(Cursor Loader).
i was having some issues with windowhandle and tried this one. this one works good for me.
String parentWindowHandler = driver.getWindowHandle();
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
driver.switchTo().window(subWindowHandler);
System.out.println(subWindowHandler);
}
driver.switchTo().window(parentWindowHandler);
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.
How to create a resource:
In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.
How to use a resource:
Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.
There is a static class called Properties.Resources
that gives you access to all your resources, so my code ended up being as simple as:
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
Done! Finished! Everything is simple when you know how, isn't it?
The JavaScript function:
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
To use this function:
capitalizedString = someString.toLowerCase().capitalize();
Also, this would work on multiple words string.
To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.
Does this work?
display_errors = Off
Also, what version of php are you using?
actually you should only put in-line elements inside the p
, so in your case ol
is better outside
There's no need to use extra large tables or ALL_OBJECTS table:
SELECT TRUNC (SYSDATE - ROWNUM) dt
FROM DUAL CONNECT BY ROWNUM < 366
will do the trick.
Brad's method worked for me. If you use it you might want to make it a little safer.
id scrollView = [yourWebView.subviews objectAtIndex:0]; if( [scrollView respondsToSelector:@selector(setAllowsRubberBanding:)] ) { [scrollView performSelector:@selector(setAllowsRubberBanding:) withObject:NO]; }
If apple changes something then the bounce will come back - but at least your app won't crash.
According to Apache Tomcat 7 JNDI Datasource HOW-TO page there must be a resource configuration in web.xml:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
That works for me
Short version of (correct) tzaman answer will be (for fresh SVN)
svn switch ^/branches/v1p2p3
--relocate
switch is deprecated anyway, when it needed you'll have to use svn relocate
command
Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)
On Windows, the caret character (^
) must be escaped:
svn switch ^^/branches/v1p2p3
It's much more easier to add only the event for mousedown:
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var hti = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.Rows[hti.RowIndex].Selected = true;
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
}
This is easier. Of cource you have to init your mousedown-event as already mentioned with:
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
in your constructor.
The best way for me is this:
Dictionary<int, int> copy= new Dictionary<int, int>(yourListOrDictionary);
In Python 3 you can use a variation on:
def Deb(msg = None):
print(f"Debug {sys._getframe().f_back.f_lineno}: {msg if msg is not None else ''}")
In code, you can then use:
Deb("Some useful information")
Deb()
To produce:
123: Some useful information
124:
Where the 123 and 124 are the lines that the calls are made from.
When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:
%PATH%
environment variable for the executable file.If the file isn't found in either of those options you will need to either:
%PATH%
by apending it, (recommended only with extreme caution).You can see which locations are specified in %PATH%
from the Command prompt, Echo %Path%
.
Because of your reported error we can assume that Mobile.exe
is not in the current directory or in a location specified within the %Path%
variable, so you need to use 1.
, 2.
or 3.
.
Examples for 1.
C:\directory_path_without_spaces\My-App\Mobile.exe
or:
"C:\directory path with spaces\My-App\Mobile.exe"
Alternatively you may try:
Start C:\directory_path_without_spaces\My-App\Mobile.exe
or
Start "" "C:\directory path with spaces\My-App\Mobile.exe"
Where ""
is an empty title, (you can optionally add a string between those doublequotes).
Examples for 2.
CD /D C:\directory_path_without_spaces\My-App
Mobile.exe
or
CD /D "C:\directory path with spaces\My-App"
Mobile.exe
You could also use the /D
option with Start
to change the working directory for the executable to be run by the start command
Start /D C:\directory_path_without_spaces\My-App Mobile.exe
or
Start "" /D "C:\directory path with spaces\My-App" Mobile.exe
I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:
public enum CancelReasonsEnum
{
[Description("In rush")]
InRush,
[Description("Need more coffee")]
NeedMoreCoffee,
[Description("Call me back in 5 minutes!")]
In5Minutes
}
In a helper class (HelperMethods) I created the following method:
public static List<string> GetListOfDescription<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
}
When you call this helper you will get the list of item descriptions.
List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();
ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
/* how to use
MyEnum x = MyEnum.NeedMoreCoffee;
string description = x.GetDescription();
*/
}
With Java 8 you can write:
OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
To answer your comment, you can then convert it to a Date (unless you depend on legacy code I don't see any reason why) or to millis since the epochs:
Date date = Date.from(utc.toInstant());
long epochMillis = utc.toInstant().toEpochMilli();
You could also use INDEX MATCH
, which is more "powerful" than vlookup. This would give you exactly what you are looking for:
Add this to the beginning of the script:
set -e
This will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.
See the bash(1) man page on the "set" internal command for more details.
I personally start almost all shell scripts with "set -e". It's really annoying to have a script stubbornly continue when something fails in the middle and breaks assumptions for the rest of the script.
Fun fact!
The 'modulus' operation is defined as:
a % n ==> a - (a/n) * n
So you could roll your own, although it will be FAR slower than the built in % operator:
public static int Mod(int a, int n)
{
return a - (int)((double)a / n) * n;
}
Edit: wow, misspoke rather badly here originally, thanks @joren for catching me
Now here I'm relying on the fact that division + cast-to-int in C# is equivalent to Math.Floor
(i.e., it drops the fraction), but a "true" implementation would instead be something like:
public static int Mod(int a, int n)
{
return a - (int)Math.Floor((double)a / n) * n;
}
In fact, you can see the differences between % and "true modulus" with the following:
var modTest =
from a in Enumerable.Range(-3, 6)
from b in Enumerable.Range(-3, 6)
where b != 0
let op = (a % b)
let mod = Mod(a,b)
let areSame = op == mod
select new
{
A = a,
B = b,
Operator = op,
Mod = mod,
Same = areSame
};
Console.WriteLine("A B A%B Mod(A,B) Equal?");
Console.WriteLine("-----------------------------------");
foreach (var result in modTest)
{
Console.WriteLine(
"{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}",
result.A,
result.B,
result.Operator,
result.Mod,
result.Same);
}
Results:
A B A%B Mod(A,B) Equal?
-----------------------------------
-3 | -3 | 0 | 0 | True
-3 | -2 | -1 | -1 | True
-3 | -1 | 0 | 0 | True
-3 | 1 | 0 | 0 | True
-3 | 2 | -1 | 1 | False
-2 | -3 | -2 | -2 | True
-2 | -2 | 0 | 0 | True
-2 | -1 | 0 | 0 | True
-2 | 1 | 0 | 0 | True
-2 | 2 | 0 | 0 | True
-1 | -3 | -1 | -1 | True
-1 | -2 | -1 | -1 | True
-1 | -1 | 0 | 0 | True
-1 | 1 | 0 | 0 | True
-1 | 2 | -1 | 1 | False
0 | -3 | 0 | 0 | True
0 | -2 | 0 | 0 | True
0 | -1 | 0 | 0 | True
0 | 1 | 0 | 0 | True
0 | 2 | 0 | 0 | True
1 | -3 | 1 | -2 | False
1 | -2 | 1 | -1 | False
1 | -1 | 0 | 0 | True
1 | 1 | 0 | 0 | True
1 | 2 | 1 | 1 | True
2 | -3 | 2 | -1 | False
2 | -2 | 0 | 0 | True
2 | -1 | 0 | 0 | True
2 | 1 | 0 | 0 | True
2 | 2 | 0 | 0 | True
Instead of storing images in database store them in a folder in your disk and store their location in your data base.
If I understood your question, try something like this
declare @dd varchar(50)='Jan 30 2013 12:00:00:000AM'
Select convert(varchar,(CONVERT(date,@dd,103)),103)
Update
SELECT
PREFIX_TableName.ColumnName1 AS Name,
PREFIX_TableName.ColumnName2 AS E-Mail,
convert(varchar,(CONVERT(date,PREFIX_TableName.ColumnName3,103)),103) AS TransactionDate,
PREFIX_TableName.ColumnName4 AS OrderNumber
If you guys using the following method to check:
public static boolean isNumeric(String str) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
Then what happend with the input of very long String, such as I call this method:
System.out.println(isNumeric("94328948243242352525243242524243425452342343948923"));
The result is "true", also it is a too-large-size number! The same thing will happen if you using regex to check! So I'd rather using the "parsing" method to check, like this:
public static boolean isNumeric(String str) {
try {
int number = Integer.parseInt(str);
return true;
} catch (Exception e) {
return false;
}
}
And the result is what I expected!
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
The modern solution is an input field of type "search"!
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search https://www.w3schools.com/tags/tag_datalist.asp
Somewhere in your HTML you define a datalist for later reference:
<datalist id="mylist">
<option value="Option 1">
<option value="Option 2">
<option value="Option 3">
</datalist>
Then you can define your search input like this:
<input type="search" list="mylist">
Voilà. Very nice and easy.
execfile
runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.
If you want to run a program from within Python, use subprocess.call
. E.g.
import subprocess
subprocess.call(['./abc.py', arg1, arg2])
This works for me:
$('#element').click(function (e) {
if (e.offsetX > e.target.offsetLeft) {
// click on element
}
else{
// click on ::before element
}
});
In excel, hide the workbooks, and save them as hidden. When your app loads them they will not be shown.
Edit: upon re-reading, it became clear that these workbooks are not part of your application. Such a solution would be inappropriate for user workbooks.
This is one of the best suggestion in which is done using query. Good for those who has a lot of databases just like me. Can run it using a script.
USE DatabaseName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DatabaseName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DatabaseName_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE DatabaseName
SET RECOVERY FULL;
GO
From the Intel's manual - Instruction Set Reference, the JE
and JZ
have the same opcode (74
for rel8 / 0F 84
for rel 16/32) also JNE
and JNZ
(75
for rel8 / 0F 85
for rel 16/32) share opcodes.
JE
and JZ
they both check for the ZF
(or zero flag), although the manual differs slightly in the descriptions of the first JE
rel8 and JZ
rel8 ZF
usage, but basically they are the same.
Here is an extract from the manual's pages 464, 465 and 467.
Op Code | mnemonic | Description
-----------|-----------|-----------------------------------------------
74 cb | JE rel8 | Jump short if equal (ZF=1).
74 cb | JZ rel8 | Jump short if zero (ZF ? 1).
0F 84 cw | JE rel16 | Jump near if equal (ZF=1). Not supported in 64-bit mode.
0F 84 cw | JZ rel16 | Jump near if 0 (ZF=1). Not supported in 64-bit mode.
0F 84 cd | JE rel32 | Jump near if equal (ZF=1).
0F 84 cd | JZ rel32 | Jump near if 0 (ZF=1).
75 cb | JNE rel8 | Jump short if not equal (ZF=0).
75 cb | JNZ rel8 | Jump short if not zero (ZF=0).
0F 85 cd | JNE rel32 | Jump near if not equal (ZF=0).
0F 85 cd | JNZ rel32 | Jump near if not zero (ZF=0).
According to other answers I am adding the parallel stages scenario:
pipeline {
agent any
stages {
stage('some parallel stage') {
parallel {
stage('parallel stage 1') {
when {
expression { ENV == "something" }
}
steps {
echo 'something'
}
}
stage('parallel stage 2') {
steps {
echo 'something'
}
}
}
}
}
}
Use the tail.exe from the Windows 2003 Resource Kit
Try adding
word-break: break-all
to the CSS on your table element.
That will get the words in the table cells to break such that the table does not grow wider than its containing div, yet the table columns are still sized dynamically. jsfiddle demo.
I use the transform: translateZ(0);
method but in some cases it is not sufficient.
I'm not fan of adding and removing a class so i tried to find way to solve this and ended up with a new hack that works well :
@keyframes redraw{
0% {opacity: 1;}
100% {opacity: .99;}
}
// ios redraw fix
animation: redraw 1s linear infinite;
After some trial and error I came to this solution:
function center(img) {
var div = img.parentNode;
var divW = parseInt(div.style.width);
var divH = parseInt(div.style.height);
var srcW = img.width;
var srcH = img.height;
var ratio = Math.min(divW/srcW, divH/srcH);
var newW = img.width * ratio;
var newH = img.height * ratio;
img.style.width = newW + "px";
img.style.height = newH + "px";
img.style.marginTop = (divH-newH)/2 + "px";
img.style.marginLeft = (divW-newW)/2 + "px";
}
a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.
if you want real difference
select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);
if you want absolute difference
select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));
\n
is an escape character for strings that is replaced with the new line object. Writing \n
in a string that prints out will print out a new line instead of the \n
This also works for me:-
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATE_DATE_TIME", nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
public Date getCreateDateTime() {
return createDateTime;
}
public void setCreateDateTime(Date createDateTime) {
this.createDateTime = createDateTime;
}
AngularJS's Filter worked out for me.
Assuming the code/id
is unique, we can filter out that particular object with AngularJS's filter
and work with the selected objects properties. Considering the example above:
<select ng-options="size.code as size.name for size in sizes"
ng-model="item.size.code"
ng-change="update(MAGIC_THING); search.code = item.size.code">
</select>
<!-- OUTSIDE THE SELECT BOX -->
<h1 ng-repeat="size in sizes | filter:search:true"
ng-init="search.code = item.size.code">
{{size.name}}
</h1>
Now, there are 3 important aspects to this:
ng-init="search.code = item.size.code"
- on initializing h1
element outside select
box, set the filter query to the selected option.
ng-change="update(MAGIC_THING); search.code = item.size.code"
- when you change the select input, we'll run one more line which will set the "search" query to the currently selected item.size.code
.
filter:search:true
- Pass true
to filter to enable strict matching.
That's it. If the size.code
is uniqueID, we'll have only one h1
element with the text of size.name
.
I've tested this in my project and it works.
Good Luck
To understand what is going on, let's take one letter(repeated more than once) in the sentence string and follow what happens when it goes through the loop.
Remember that we start off with an empty characters dictionary
characters = {}
I will pick the letter 'e'. Let's pass the character 'e' (found in the word The) for the first time through the loop. I will assume it's the first character to go through the loop and I'll substitute the variables with their values:
for 'e' in "The quick brown fox jumped over the lazy dog.":
{}['e'] = {}.get('e', 0) + 1
characters.get('e', 0) tells python to look for the key 'e' in the dictionary. If it's not found it returns 0. Since this is the first time 'e' is passed through the loop, the character 'e' is not found in the dictionary yet, so the get method returns 0. This 0 value is then added to the 1 (present in the characters[character] = characters.get(character,0) + 1 equation). After completion of the first loop using the 'e' character, we now have an entry in the dictionary like this: {'e': 1}
The dictionary is now:
characters = {'e': 1}
Now, let's pass the second 'e' (found in the word jumped) through the same loop. I'll assume it's the second character to go through the loop and I'll update the variables with their new values:
for 'e' in "The quick brown fox jumped over the lazy dog.":
{'e': 1}['e'] = {'e': 1}.get('e', 0) + 1
Here the get method finds a key entry for 'e' and finds its value which is 1. We add this to the other 1 in characters.get(character, 0) + 1 and get 2 as result.
When we apply this in the characters[character] = characters.get(character, 0) + 1 equation:
characters['e'] = 2
It should be clear that the last equation assigns a new value 2 to the already present 'e' key. Therefore the dictionary is now:
characters = {'e': 2}
Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb
func compare(a, b T) bool {
if &a == &b {
return true
}
if a.X != b.X || a.Y != b.Y {
return false
}
if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
return false
}
for i, v := range a.Z {
if b.Z[i] != v {
return false
}
}
for k, v := range a.M {
if b.M[k] != v {
return false
}
}
return true
}
Okay, I was blind:
e.which
will contain the ASCII code of the key.
See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
You can embed websites into another website using the <embed>
tag, like so:
<embed src="http://www.example.com" style="width:500px; height: 300px;">
You can change the height, width, and URL to suit your needs.
The <embed>
tag is the most up-to-date way to embed websites, as it was introduced with HTML5.
I am currently using Rob de la Cruz's reply:
Object.keys(obj)
And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.
if (!Object.keys) {
Object.keys = function(object) {
var keys = [];
for (var o in object) {
if (object.hasOwnProperty(o)) {
keys.push(o);
}
}
return keys;
};
}
I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.
Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.
If you want to hide the cursor in the entire webpage, using body
will not work unless it covers the entire visible page, which is not always the case. To make sure the cursor is hidden everywhere in the page, use:
document.documentElement.style.cursor = 'none';
To reenable it:
document.documentElement.style.cursor = 'auto';
The analogue with static CSS notation is in the answer by Pavel Salaquarda (in essence: html * {cursor:none}
)
Check that the version of php you're running matches your codebase. For example, your local environment may be running php 5.4 (and things run fine) and maybe you're testing your code on a new machine that has php 5.3 installed. If you are using 5.4 syntax such as [] for array() then you'll get the situation you described above.
The question is rather vague. If you meant “how do I write a program so that a thread stops running when I want it to”, then various other responses should be helpful. But if you meant “I have an emergency with a server I cannot restart right now and I just need a particular thread to die, come what may”, then you need an intervention tool to match monitoring tools like jstack
.
For this purpose I created jkillthread. See its instructions for usage.
Have your tried using the 'return' keyword?
def rps():
return True
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
You are looking for --build-arg
and the ARG
instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg
to the Dockerfile
and then build with docker build --build-arg arg=2.3 .
.
Use LinkedList
instead. Than, you can create an array if necessary.
for more extendability for large scale apps use oop style with encapsulated fields.
Simple way :-
class Fruit implements JsonSerializable {
private $type = 'Apple', $lastEaten = null;
public function __construct() {
$this->lastEaten = new DateTime();
}
public function jsonSerialize() {
return [
'category' => $this->type,
'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
];
}
}
echo json_encode(new Fruit()); //which outputs:
{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}
Real Gson on PHP :-
Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.
The :nth-child
CSS3 selector is in fact more capable than you ever imagined!
For example, this will select the last 2 elements of #container
:
#container :nth-last-child(-n+2) {}
But this is just the beginning of a beautiful friendship.
#container :nth-last-child(-n+2) {
background-color: cyan;
}
_x000D_
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div>
<div>SELECT THIS</div>
</div>
_x000D_
Sydius outlined the types fairly well:
How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.
There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.
There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.
The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.
If you are using SQL Server 2012+ vote for Martin Smith's answer and use the OFFSET
and FETCH NEXT
extensions to ORDER BY
,
If you are unfortunate enough to be stuck with an earlier version, you could do something like this,
WITH Rows AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY [dbo].[SomeColumn]) [Row]
, *
FROM
[dbo].[SomeTable]
)
SELECT TOP 10
*
FROM
Rows
WHERE Row > 10
I believe is functionaly equivalent to
SELECT * FROM SomeTable LIMIT 10 OFFSET 10 ORDER BY SomeColumn
and the best performing way I know of doing it in TSQL, before MS SQL 2012.
If there are very many rows you may get better performance using a temp table instead of a CTE.
If you're using Bitnami RubyStack and ran across the similar problem. Try this one
sudo ln -s /Applications/rubystack-2.0.0-17/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
if you're on windows, make sure you 'unblock' the lombok.jar before you install it. if you don't do this, it will install but it wont work.
All the answers here suggest to use ipairs but beware, it does not work all the time.
t = {[2] = 44, [4]=77, [6]=88}
--This for loop prints the table
for key,value in next,t,nil do
print(key,value)
end
--This one does not print the table
for key,value in ipairs(t) do
print(key,value)
end
You can get the current URL location with a hash tag by using:
JavaScript:
// Using href
var URL = window.location.href;
// Using path
var URL = window.location.pathname;
jQuery:
$(location).attr('href');
To do this programatically in a fragment you can use following code
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
Place this in onResume()
I just wanted to add that "Include" is part of eager loading. It is described in Entity Framework 6 tutorial by Microsoft. Here is the link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
Excerpt from the linked page:
Here are several ways that the Entity Framework can load related data into the navigation properties of an entity:
Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. This results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved. The DbContext class enables lazy loading by default.
Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the
Include
method.Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace
Collection(x => x.Courses)
withReference(x => x.Administrator)
.) Typically you'd use explicit loading only when you've turned lazy loading off.Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.
If we don’t use ES2015 and don’t have fill(), just use .apply()
See https://stackoverflow.com/a/47041157/1851492
let Array2D = (r, c, fill) => Array.apply(null, new Array(r)).map(function() {return Array.apply(null, new Array(c)).map(function() {return fill})})_x000D_
_x000D_
console.log(JSON.stringify(Array2D(3,4,0)));_x000D_
console.log(JSON.stringify(Array2D(4,5,1)));
_x000D_
You can remove single char as follows:
String str="+919595354336";
String result = str.replaceAll("\\\\+","");
System.out.println(result);
OUTPUT:
919595354336
This link will help you out completely(the Shortest and Most Elegant way):
PdfPTable tbheader = new PdfPTable(3);
tbheader.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
tbheader.DefaultCell.Border = 0;
tbheader.AddCell(new Paragraph());
tbheader.AddCell(new Paragraph());
var _cell2 = new PdfPCell(new Paragraph("This is my header", arial_italic));
_cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
_cell2.Border = 0;
tbheader.AddCell(_cell2);
float[] widths = new float[] { 20f, 20f, 60f };
tbheader.SetWidths(widths);
tbheader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin), writer.DirectContent);
PdfPTable tbfooter = new PdfPTable(3);
tbfooter.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
tbfooter.DefaultCell.Border = 0;
tbfooter.AddCell(new Paragraph());
tbfooter.AddCell(new Paragraph());
var _cell2 = new PdfPCell(new Paragraph("This is my footer", arial_italic));
_cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
_cell2.Border = 0;
tbfooter.AddCell(_cell2);
tbfooter.AddCell(new Paragraph());
tbfooter.AddCell(new Paragraph());
var _celly = new PdfPCell(new Paragraph(writer.PageNumber.ToString()));//For page no.
_celly.HorizontalAlignment = Element.ALIGN_RIGHT;
_celly.Border = 0;
tbfooter.AddCell(_celly);
float[] widths1 = new float[] { 20f, 20f, 60f };
tbfooter.SetWidths(widths1);
tbfooter.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);
Note: In case you wish to use the already-mentioned algo for cases where you need to replace huge number of instances in the source string (e.g. new lines in long text) there is high probability you'll end up with StackOverflowException
because of the recursive call.
I resolved this issue thanks to Xalan's (didn't look how to do it in Saxon) built-in Java type embedding:
<xsl:stylesheet version="1.0" exclude-result-prefixes="xalan str"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xalan="http://xml.apache.org/xalan"
xmlns:str="xalan://java.lang.String"
>
...
<xsl:value-of select="str:replaceAll(
str:new(text()),
$search_string,
$replace_string)"/>
...
</xsl:stylesheet>
Okay If you want to change the gutter inside one row, but want those (first and last) inner divs to align with the grid surrounding the .no-gutter
row, you could copy-paste-merge most answers into the following snippet:
.row.no-gutter [class*='col-']:first-child:not(:only-child) {
padding-right: 0;
}
.row.no-gutter [class*='col-']:last-child:not(:only-child) {
padding-left: 0;
}
.row.no-gutter [class*='col-']:not(:first-child):not(:last-child):not(:only-child) {
padding-right: 0;
padding-left: 0;
}
If you like to have a smaller gutter instead of completly none, just change the 0's to what you like... (eg: 5px to get 10px gutter).
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
Some of the comments are right in saying that these answers do not correspond to the question.
One reason one might want to loop through a dictionary using "indexes" is for example to compute a distance matrix for a set of objects in a dictionary. To put it as an example (going a bit to the basics on the bullet below):
This is why most packages use a condensed distance matrix ( How does condensed distance matrix work? (pdist) )
But consider the case one is implementing the computation of a distance matrix, or any kind of permutation of the sort. In such case you need to skip the results from more than half of the cases. This means that a FOR loop that runs through all the dictionary is just hitting an IF and jumping to the next iteration without performing really any job most of the time. For large datasets this additional "IFs" and loops add up to a relevant amount on the processing time and could be avoided if, at each loop, one starts one "index" further on the dictionary.
Going than to the question, my conclusion right now is that the answer is NO. One has no way to directly access the dictionary values by any index except the key or an iterator.
I understand that most of the answers up to now applies different approaches to perform this task but really don't allow any index manipulation, that would be useful in a case such as exemplified.
The only alternative I see is to use a list or other variable as a sequential index to the dictionary. Here than goes an implementation to exemplify such case:
#!/usr/bin/python3
dishes = {'spam': 4.25, 'eggs': 1.50, 'sausage': 1.75, 'bacon': 2.00}
print("Dictionary: {}\n".format(dishes))
key_list = list(dishes.keys())
number_of_items = len(key_list)
condensed_matrix = [0]*int(round(((number_of_items**2)-number_of_items)/2,0))
c_m_index = 0
for first_index in range(0,number_of_items):
for second_index in range(first_index+1,number_of_items):
condensed_matrix[c_m_index] = dishes[key_list[first_index]] - dishes[key_list[second_index]]
print("{}. {}-{} = {}".format(c_m_index,key_list[first_index],key_list[second_index],condensed_matrix[c_m_index]))
c_m_index+=1
The output is:
Dictionary: {'spam': 4.25, 'eggs': 1.5, 'sausage': 1.75, 'bacon': 2.0}
0. spam-eggs = 2.75
1. spam-sausage = 2.5
2. spam-bacon = 2.25
3. eggs-sausage = -0.25
4. eggs-bacon = -0.5
5. sausage-bacon = -0.25
Its also worth mentioning that are packages such as intertools that allows one to perform similar tasks in a shorter format.
Yes: TIME_CREATED contains a date and a time. Use TRUNC
to strip the time:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')
UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED
if it exists. An alternative approach without this problem is this:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1
For anyone on MacOS (I'm on Mojave 10.14), the following helped me out: https://github.com/reactioncommerce/reaction/issues/1938#issuecomment-284207213
You'd run these commands
echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf
echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf
sudo sysctl -w kern.maxfiles=65536
sudo sysctl -w kern.maxfilesperproc=65536
ulimit -n 65536
Then try npm install
once more.
Your rows
object holds an Item
attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString()
on the row.
You should access each column from the row separately, use a for
or a foreach
to walk the array of columns.
Here, take a look at the class:
http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx
Bower uses semver syntax, but here are a few quick examples:
You can install a specific version:
$ bower install jquery#1.11.1
You can use ~ to specify 'any version that starts with this':
$ bower install jquery#~1.11
You can specify multiple version requirements together:
$ bower install "jquery#<2.0 >1.10"
Since the stack is already unwound when entering the catch block, the solution in my case was to not catch certain exceptions which then lead to a SIGABRT. In the signal handler for SIGABRT I then fork() and execl() either gdb (in debug builds) or Google breakpads stackwalk (in release builds). Also I try to only use signal handler safe functions.
GDB:
static const char BACKTRACE_START[] = "<2>--- backtrace of entire stack ---\n";
static const char BACKTRACE_STOP[] = "<2>--- backtrace finished ---\n";
static char *ltrim(char *s)
{
while (' ' == *s) {
s++;
}
return s;
}
void Backtracer::print()
{
int child_pid = ::fork();
if (child_pid == 0) {
// redirect stdout to stderr
::dup2(2, 1);
// create buffer for parent pid (2+16+1 spaces to allow up to a 64 bit hex parent pid)
char pid_buf[32];
const char* stem = " ";
const char* s = stem;
char* d = &pid_buf[0];
while (static_cast<bool>(*s))
{
*d++ = *s++;
}
*d-- = '\0';
char* hexppid = d;
// write parent pid to buffer and prefix with 0x
int ppid = getppid();
while (ppid != 0) {
*hexppid = ((ppid & 0xF) + '0');
if(*hexppid > '9') {
*hexppid += 'a' - '0' - 10;
}
--hexppid;
ppid >>= 4;
}
*hexppid-- = 'x';
*hexppid = '0';
// invoke GDB
char name_buf[512];
name_buf[::readlink("/proc/self/exe", &name_buf[0], 511)] = 0;
ssize_t r = ::write(STDERR_FILENO, &BACKTRACE_START[0], sizeof(BACKTRACE_START));
(void)r;
::execl("/usr/bin/gdb",
"/usr/bin/gdb", "--batch", "-n", "-ex", "thread apply all bt full", "-ex", "quit",
&name_buf[0], ltrim(&pid_buf[0]), nullptr);
::exit(1); // if GDB failed to start
} else if (child_pid == -1) {
::exit(1); // if forking failed
} else {
// make it work for non root users
if (0 != getuid()) {
::prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
}
::waitpid(child_pid, nullptr, 0);
ssize_t r = ::write(STDERR_FILENO, &BACKTRACE_STOP[0], sizeof(BACKTRACE_STOP));
(void)r;
}
}
minidump_stackwalk:
static bool dumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* context, bool succeeded)
{
int child_pid = ::fork();
if (child_pid == 0) {
::dup2(open("/dev/null", O_WRONLY), 2); // ignore verbose output on stderr
ssize_t r = ::write(STDOUT_FILENO, &MINIDUMP_STACKWALK_START[0], sizeof(MINIDUMP_STACKWALK_START));
(void)r;
::execl("/usr/bin/minidump_stackwalk", "/usr/bin/minidump_stackwalk", descriptor.path(), "/usr/share/breakpad-syms", nullptr);
::exit(1); // if minidump_stackwalk failed to start
} else if (child_pid == -1) {
::exit(1); // if forking failed
} else {
::waitpid(child_pid, nullptr, 0);
ssize_t r = ::write(STDOUT_FILENO, &MINIDUMP_STACKWALK_STOP[0], sizeof(MINIDUMP_STACKWALK_STOP));
(void)r;
}
::remove(descriptor.path()); // this is not signal safe anymore but should still work
return succeeded;
}
Edit: To make it work for breakpad I also had to add this:
std::set_terminate([]()
{
ssize_t r = ::write(STDERR_FILENO, EXCEPTION, sizeof(EXCEPTION));
(void)r;
google_breakpad::ExceptionHandler::WriteMinidump(std::string("/tmp"), dumpCallback, NULL);
exit(1); // avoid creating a second dump by not calling std::abort
});
Source: How to get a stack trace for C++ using gcc with line number information? and Is it possible to attach gdb to a crashed process (a.k.a "just-in-time" debugging)
After struggling for a while I finally got this to work with eclipse.ini
instead of the command line. After finally reading the documentation I realized that the -vm argument must be on a separate line, unquoted, and ahead of any -vmargs:
-vm
C:\Program Files\Java\jdk1.7.0_45\bin\javaw.exe
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
You're looking for the LOOKUP function. please see the following page for more info:
Hey I just had this problem and found that I wasn't looking at the folder location closely enough:
I had
require_once /vagrant/public/liberate/**APP**/vendor/autoload.php
What worked was:
require_once /vagrant/public/liberate/vendor/autoload.php
It was very easy (as a beginner) to overlook this very unnoticeable issue. Yes I do realize that the require issue being logged points directly to the issue at hand, but if you are a beginner, like me, these things can be easily overlooked.
FIX:
Have a good look at the debug of ( __ Dir __ '/etc/etc/etc/file.php') then have your file system open in a different window, and map the two directly. If there is even the slightest difference this require will not work and the above error will be spat out.
In addition of the modification of the file C:\wamp64\bin\apache\apache2.4.27\conf\httpd.conf
.
To get the url shortcuts working, edit the file C:\wamp64\wampmanager.conf
and change the port:
[apache]
apachePortUsed = "8080"
Then exit and relaunch wamp.
The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever
). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever
.
I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.
I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
<!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
<div class="container mh0 w-100">_x000D_
<div class="page-header text-center mb5">_x000D_
<h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
<p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
<div class="header-button">_x000D_
<button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container pa0 flex justify-center">_x000D_
<div class="listings card-columns">_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
<div class="card mv2">_x000D_
<img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
alt="Mazda hatchback">_x000D_
<div class="card-body">_x000D_
<h5 class="card-title">Card title</h5>_x000D_
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
content._x000D_
</p>_x000D_
<a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
buttons here_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
After trying both the Bootstrap .card-group
and .card-deck
card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns
class a shot. And it worked!
Your results may vary, but .card-columns
seems to be the most stable implementation here.
Although @BrianHart 's answer is correct, if you are connecting from a remote host, you'll also need to allow remote hosts to connect to the MySQL/MariaDB database.
My article describes the full instructions to connect to a MySQL/MariaDB database in Oracle SQL Developer:
=IF(B2="X",IF(B3="Y", TRUE, FALSE),FALSE)
, and choose to fill green when this is true=IF(B2="X",IF(B3="W", TRUE, FALSE),FALSE)
and choose to fill red when this is true.More details - conditional formatting with a formula applies the format when the formula evaluates to TRUE. You can use a compound IF
formula to return true or false based on the values of any cells.
Use \overset{above}{main}
in math mode. In your case, \overset{a}{\#}
.
Shed Skin is "a (restricted) Python-to-C++ compiler".
The only one that worked for me was a mix of all the answers:
convert in.png -background white -alpha remove -flatten -alpha off out.png
Good answer. Note that if the value to encode is undefined
or null
with jQuery 1.4.2 you might get errors such as:
jQuery("<div/>").text(value).html is not a function
OR
Uncaught TypeError: Object has no method 'html'
The solution is to modify the function to check for an actual value:
function htmlEncode(value){
if (value) {
return jQuery('<div/>').text(value).html();
} else {
return '';
}
}
var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);
Hi I'm also new to react and I also faced this problem after so many trouble I found solution: Just run in your command prompt or terminal :
npm config set registry http://registry.npmjs.org/
This will resolve your problem. Reference link: http://blog.csdn.net/zhalcie2011/article/details/78726679
This worked for me like charm. I went through multiple ways but then this helped me. Make sure you follow each step and name the XML files exactly same.
The process is a little tedious but yes it does work.
This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.
static byte[] toBytes(String s){
byte[] b=new byte[s.length()*2];
ByteBuffer.wrap(b).asCharBuffer().put(s);
return b;
}
Even with Rollin_s's tip, Dave Webb's answer didn't work for me. The text in the right TextView
was still overlapping the text in the left TextView
.
I eventually got the behavior I wanted with something like this:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<TextView
android:id="@+id/mytextview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/mytextview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/mytextview1"
android:gravity="right"/>
</RelativeLayout>
Note that mytextview2 has "android:layout_width"
set as "match_parent"
.
Hope this helps someone!
For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.
Here is my code that works just fine.
public async Task<bool> UpdateDeviceShutdownAsync(Guid id, DateTime shutdownAtTime, int areaID, decimal mileage,
decimal motohours, int driverID, List<int> commission,
string shutdownPlaceDescr, int deviceShutdownTypeID, string deviceShutdownDesc,
bool isTransportation, string violationConditions, DateTime shutdownStartTime,
DateTime shutdownEndTime, string notes, List<Guid> faultIDs )
{
try
{
using (var db = new GJobEntities())
{
var isExisting = await db.DeviceShutdowns.FirstOrDefaultAsync(x => x.ID == id);
if (isExisting != null)
{
isExisting.AreaID = areaID;
isExisting.DriverID = driverID;
isExisting.IsTransportation = isTransportation;
isExisting.Mileage = mileage;
isExisting.Motohours = motohours;
isExisting.Notes = notes;
isExisting.DeviceShutdownDesc = deviceShutdownDesc;
isExisting.DeviceShutdownTypeID = deviceShutdownTypeID;
isExisting.ShutdownAtTime = shutdownAtTime;
isExisting.ShutdownEndTime = shutdownEndTime;
isExisting.ShutdownStartTime = shutdownStartTime;
isExisting.ShutdownPlaceDescr = shutdownPlaceDescr;
isExisting.ViolationConditions = violationConditions;
// Delete children
foreach (var existingChild in isExisting.DeviceShutdownFaults.ToList())
{
db.DeviceShutdownFaults.Remove(existingChild);
}
if (faultIDs != null && faultIDs.Any())
{
foreach (var faultItem in faultIDs)
{
var newChild = new DeviceShutdownFault
{
ID = Guid.NewGuid(),
DDFaultID = faultItem,
DeviceShutdownID = isExisting.ID,
};
isExisting.DeviceShutdownFaults.Add(newChild);
}
}
// Delete all children
foreach (var existingChild in isExisting.DeviceShutdownComissions.ToList())
{
db.DeviceShutdownComissions.Remove(existingChild);
}
// Add all new children
if (commission != null && commission.Any())
{
foreach (var cItem in commission)
{
var newChild = new DeviceShutdownComission
{
ID = Guid.NewGuid(),
PersonalID = cItem,
DeviceShutdownID = isExisting.ID,
};
isExisting.DeviceShutdownComissions.Add(newChild);
}
}
await db.SaveChangesAsync();
return true;
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
return false;
}
You can use regular expressions, and it works:
boolean found = s1.matches("(?i).*" + s2+ ".*");
Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.
Quick fix:
helloWorld
inside the src
folder.helloWorld.java
file in that package. Just drag and drop on
the package. Error should disappear.Explanation:
Latest version of Eclipse required java11 or above. The module
feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules
When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java
file. If you select don't create
then module-info.java
will not create and your project will free from this issue.
Best practice is while crating project, after giving project name. Click on next
button instead of finish
. On next page at the bottom it ask for creation of module-info.java
file. Select or deselect as per need.
If selected: (by default) click on finish
button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.
If deselect: No issue
string is an alias for String in the .NET Framework.
Where "String" is in fact System.String.
I would say that they are interchangeable and there is no difference when and where you should use one or the other.
It would be better to be consistent with which one you did use though.
For what it's worth, I use string
to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - int, bool, var
etc (although Int32
and Boolean
are also correct).
I use String when using the static methods on the String class, like String.Split()
or String.IsNullOrEmpty()
. I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.
Try the following
var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];_x000D_
_x000D_
var myTotal = 0; // Variable to hold your total_x000D_
_x000D_
for(var i = 0, len = myData.length; i < len; i++) {_x000D_
myTotal += myData[i][1]; // Iterate over your first array and then grab the second element add the values up_x000D_
}_x000D_
_x000D_
document.write(myTotal); // 22 in this instance
_x000D_
A non-committed transaction can be reverted by issuing the command ROLLBACK
But if you are running in auto-commit mode there is nothing you can do....
If you are using the grid or alike component: In XAML, make sure that the elements in the grid have Grid.Row and Grid.Column defined, and ensure tha they don't have margins. If you used designer mode, or Expression Blend, it could have assigned margins relative to the whole grid instead of to particular cells. As for cell sizing, I add an extra cell that fills up the rest of the space:
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
UPDATE sourcecodes_tags
SET sourcecode_id = NULL
WHERE sourcecode_id NOT IN (
SELECT id FROM sourcecodes);
should help to get rid of those IDs. Or if null
is not allowed in sourcecode_id
, then remove those rows or add those missing values to the sourcecodes
table.
Try testing for DOM
element
if (!!$(selector)[0]) // do stuff
No JS needed really ...
Just add a type
attribute to the button with a value of button
<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>
By default, button elements are of the type "submit" which causes them to submit their enclosing form element (if any). Changing the type
to "button" prevents that.
There is a newer version of gradle (ver 2.4).
You can set this for your project(s) by opening up 'Project Structure' dialog from File menu,
Project Structure -> Project -> Gradle version
and set it to '2.4'.
You can read more about boosting performance at this link.
I'd like to show an example, where the 'valueForThis' argument is used:
Array.prototype.push = function(element) {
/*
Native code*, that uses 'this'
this.put(element);
*/
}
var array = [];
array.push(1);
array.push.apply(array,[2,3]);
Array.prototype.push.apply(array,[4,5]);
array.push.call(array,6,7);
Array.prototype.push.call(array,8,9);
//[1, 2, 3, 4, 5, 6, 7, 8, 9]
**details: http://es5.github.io/#x15.4.4.7*
Dont forget to add user agent since some server will block request if there's no server agent..(you would get Forbidden resource response) example :
curl -X POST -A 'Mozilla/5.0 (X11; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0' -d "field=acaca&name=afadxx" https://example.com
Other alternative:
JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
String.class, "Your message");
Then:
System.out.println(element.getValue()); // Result: Your message
Vohuman's answer lead me to my own implementation:
$(document).on("vclick", ".className", function() {
// Whatever you want to do
});
Instead of:
$(document).ready(function($) {
$('.className').click(function(){
// Whatever you want to do
});
});
I hope this helps!
GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL
. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.
Element.clientWidth
& Element.clientHeight
return the height/width of that element's content in addition any applicable padding.
The jQuery implementation of these are:
$(target).outerWidth()
& $(target).outerHeight()
.clientWidth
& .clientHeight
are included in the CSSOM View Module specification which is currently in the working draft stage. While modern browsers have a consistent implementation of this specification, to insure consistent performance across legacy platforms, the jQuery implementation should still be used.
Additional information:
Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:
SQL> create table t23
2 (ts0 timestamp(0)
3 , ts3 timestamp(3)
4 , ts6 timestamp(6)
5 )
6 /
Table created.
SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
2 /
1 row created.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
SQL>
If we don't specify a precision then the timestamp defaults to six places.
SQL> alter table t23 add ts_def timestamp;
Table altered.
SQL> update t23
2 set ts_def = systimestamp
3 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
SQL>
Note that I'm running on Linux so my TIMESTAMP
column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).
As might be expected, the documentation covers this. Find out more.
"when you create timestamp(9) this gives you nanos right"
Only if the OS supports it. As you can see, my OEL appliance does not:
SQL> alter table t23 add ts_nano timestamp(9)
2 /
Table altered.
SQL> update t23 set ts_nano = systimestamp(9)
2 /
1 row updated.
SQL> select * from t23
2 /
TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM
SQL>
(Those trailing zeroes could be a coincidence but they aren't.)
I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.
Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.
Use your console:
console.log(object);
Or if you are inspecting html dom elements use console.dir(object). Example:
let element = document.getElementById('alertBoxContainer');
console.dir(element);
Or if you have an array of js objects you could use:
console.table(objectArr);
If you are outputting a lot of console.log(objects) you can also write
console.log({ objectName1 });
console.log({ objectName2 });
This will help you label the objects written to console.
There is no way to make that check in C++. What should you do if other code passes you an invalid pointer? You should crash. Why? Check out this link: http://blogs.msdn.com/oldnewthing/archive/2006/09/27/773741.aspx
Have a look at this for some common errors in setting the java heap. You've probably set the heap size to a larger value than your computer's physical memory.
You should avoid solving this problem by increasing the heap size. Instead, you should profile your application to see where you spend such a large amount of memory.
The short answer is:
Thank you all for your help. This is my final version, and it works thanks to your combined help ! I am only showing the changes i made, all the rest is taken from Joe Chung's work
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
[DataMember]
public string responseDetails { get; set; }
[DataMember]
public int responseStatus { get; set; }
}
and
[DataContract]
public class ResponseData
{
[DataMember]
public List<Results> results { get; set; }
}
right click on app-->select
New-->Select Folder-->then click on Assets Folder
Its possible write a file directly to the DB server that hosts your database, and that will change all along with the execution of your PL/SQL program.
This uses the Oracle directory TMP_DIR
; you have to declare it, and create the below procedure:
CREATE OR REPLACE PROCEDURE write_log(p_log varchar2)
-- file mode; thisrequires
--- CREATE OR REPLACE DIRECTORY TMP_DIR as '/directory/where/oracle/can/write/on/DB_server/';
AS
l_file utl_file.file_type;
BEGIN
l_file := utl_file.fopen('TMP_DIR', 'my_output.log', 'A');
utl_file.put_line(l_file, p_log);
utl_file.fflush(l_file);
utl_file.fclose(l_file);
END write_log;
/
Here is how to use it:
1) Launch this from your SQL*PLUS client:
BEGIN
write_log('this is a test');
for i in 1..100 loop
DBMS_LOCK.sleep(1);
write_log('iter=' || i);
end loop;
write_log('test complete');
END;
/
2) on the database server, open a shell and
tail -f -n500 /directory/where/oracle/can/write/on/DB_server/my_output.log
IF your data includes an arbitrary sequence of blank characters (tab, space), and you want to replace each sequence with one comma, use the following:
sed 's/[\t ]+/,/g' input_file
or
sed -r 's/[[:blank:]]+/,/g' input_file
If you want to replace sequence of space characters, which includes other characters such as carriage return and backspace, etc, then use the following:
sed -r 's/[[:space:]]+/,/g' input_file
From the friendly Wikipedia:
The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.
The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.
Also, check Why size_t matters
import torch
t = torch.ones((2, 3, 4))
t.size()
>>torch.Size([2, 3, 4])
a = t.view(-1,t.size()[1]*t.size()[2])
a.size()
>>torch.Size([2, 12])
$ sudo killall -u username && sudo deluser --remove-home -f username
The killall
command is used if multiple processes are used by the user you want to delete.
The -f
option forces the removal of the user account, even if the user is still logged in. It also forces deluser
to remove the user's home directory and mail spool, even if another user uses the same home directory.
Please confirm that it works in the comments.
As for a tool I started using, I suggest firecamp Its like Postman, but it also supports websockets and socket.io.
I think op wants to know what the font that is used on a webpage is, and hoped that info might be findable in the 'inspect' pane.
Try adding the Whatfont Chrome extension.
That's HTML Encoding. There's no native javascript function to do that, but you can google and get some nicely done up ones.
E.g. http://sanzon.wordpress.com/2008/05/01/neat-little-html-encoding-trick-in-javascript/
EDIT:
This is what I've tested:
var div = document.createElement('div');
var text = document.createTextNode('<htmltag/>');
div.appendChild(text);
console.log(div.innerHTML);
Output: <htmltag/>
What you see is the interpreter echoing back the return value of next()
in addition to i
being printed each iteration:
>>> a = iter(list(range(10)))
>>> for i in a:
... print(i)
... next(a)
...
0
1
2
3
4
5
6
7
8
9
So 0
is the output of print(i)
, 1
the return value from next()
, echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.
If you assign the output of next()
things work as expected:
>>> a = iter(list(range(10)))
>>> for i in a:
... print(i)
... _ = next(a)
...
0
2
4
6
8
or print extra information to differentiate the print()
output from the interactive interpreter echo:
>>> a = iter(list(range(10)))
>>> for i in a:
... print('Printing: {}'.format(i))
... next(a)
...
Printing: 0
1
Printing: 2
3
Printing: 4
5
Printing: 6
7
Printing: 8
9
In other words, next()
is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.