This syntax worked for me in MVC 3 with Razor:
@Html.ActionLink("Delete", "DeleteList", "List", new { ID = item.ID, ListID = item.id }, new {@class= "delete"})
You can change the encoding of a file with an editor such as notepad++. Just go to Encoding and select what you want.
I always prefer the Windows 1252
you need to set the margin of the body to 0 for the table to stretch the full width. alternatively you can set the margin of the table to a negative number as well.
You cannot add a new property()
to an instance at runtime, because properties are data descriptors. Instead you must dynamically create a new class, or overload __getattribute__
in order to process data descriptors on instances.
The most versatile and safe method is putting the comment into a void quoted
here-document
, like this:
<<"COMMENT"
This long comment text includes ${parameter:=expansion}
`command substitution` and $((arithmetic++ + --expansion)).
COMMENT
Quoting the COMMENT
delimiter above is necessary to prevent parameter
expansion, command substitution and arithmetic expansion, which would happen
otherwise, as Bash manual states and POSIX shell standard specifies.
In the case above, not quoting COMMENT
would result in variable parameter
being assigned text expansion
, if it was empty or unset, executing command
command substitution
, incrementing variable arithmetic
and decrementing
variable expansion
.
Comparing other solutions to this:
Using if false; then comment text fi
requires the comment text to be
syntactically correct Bash code whereas natural comments are often not, if
only for possible unbalanced apostrophes. The same goes for : || { comment text }
construct.
Putting comments into a single-quoted void command argument, as in :'comment
text'
, has the drawback of inability to include apostrophes. Double-quoted
arguments, as in :"comment text"
, are still subject to parameter expansion,
command substitution and arithmetic expansion, the same as unquoted
here-document contents and can lead to the side-effects described above.
Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.
You can use a real like in Link to Entities quite easily
Add
<Function Name="String_Like" ReturnType="Edm.Boolean">
<Parameter Name="searchingIn" Type="Edm.String" />
<Parameter Name="lookingFor" Type="Edm.String" />
<DefiningExpression>
searchingIn LIKE lookingFor
</DefiningExpression>
</Function>
to your EDMX in this tag:
edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/Schema
Also remember the namespace in the <schema namespace="" />
attribute
Then add an extension class in the above namespace:
public static class Extensions
{
[EdmFunction("DocTrails3.Net.Database.Models", "String_Like")]
public static Boolean Like(this String searchingIn, String lookingFor)
{
throw new Exception("Not implemented");
}
}
This extension method will now map to the EDMX function.
More info here: http://jendaperl.blogspot.be/2011/02/like-in-linq-to-entities.html
Deep copy literally performs a deep copy. It means, that if your class has some fields that are references, their values will be copied, not references themselves. If, for example you have two instances of a class, A & B with fields of reference type, and perform a deep copy, changing a value of that field in A won't affect a value in B. And vise-versa. Things are different with shallow copy, because only references are copied, therefore, changing this field in a copied object would affect the original object.
What type of a copy does a copy constructor does?
It is implementation - dependent. This means that there are no strict rules about that, you can implement it like a deep copy or shallow copy, however as far as i know it is a common practice to implement a deep copy in a copy constructor. A default copy constructor performs a shallow copy though.
Here is the easiest solution.
There are a lot of environment special configurations needed if you are using Maven. So, if you start your program from maven, just run the mvnDebug
command instead of mvn
, it will take care of starting your app with remote debugging configurated. Now you can just attach a debugger on port 8000.
It'll take care of all the environment problems for you.
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:
column: 0 row: 0 value:1.0 column: 0 row: 1 value:4.0 column: 0 row: 2 value:7.0 column: 1 row: 0 value:2.0 column: 1 row: 1 value:5.0 column: 1 row: 2 value:8.0 column: 2 row: 0 value:3.0 column: 2 row: 1 value:6.0 column: 2 row: 2 value:9.0
I just copied and pasted your code into a Swift playground and defined two constants:
let NumColumns = 3, NumRows = 3
The question below has been moved here, but it seems this page doesn't directly answer to Farah El's question. How to find number 1s in 101 in R
So, I'll write an answer here, just in case.
library(magrittr)
n %>% # n is a number you'd like to inspect
as.character() %>%
str_count(pattern = "1")
How about using StringComparison.CurrentCultureIgnoreCase
instead?
You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/
Example:
@font-face {
font-family: MyHelvetica;
src: local("Helvetica Neue Bold"),
local("HelveticaNeue-Bold"),
url(MgOpenModernaBold.ttf);
font-weight: bold;
}
See also: MDN @font-face
OK kiddies, time for the pros.... This is one of my biggest complaints with inexperienced software engineers. They come in calculating transcendental functions from scratch (using Taylor's series) as if nobody had ever done these calculations before in their lives. Not true. This is a well defined problem and has been approached thousands of times by very clever software and hardware engineers and has a well defined solution. Basically, most of the transcendental functions use Chebyshev Polynomials to calculate them. As to which polynomials are used depends on the circumstances. First, the bible on this matter is a book called "Computer Approximations" by Hart and Cheney. In that book, you can decide if you have a hardware adder, multiplier, divider, etc, and decide which operations are fastest. e.g. If you had a really fast divider, the fastest way to calculate sine might be P1(x)/P2(x) where P1, P2 are Chebyshev polynomials. Without the fast divider, it might be just P(x), where P has much more terms than P1 or P2....so it'd be slower. So, first step is to determine your hardware and what it can do. Then you choose the appropriate combination of Chebyshev polynomials (is usually of the form cos(ax) = aP(x) for cosine for example, again where P is a Chebyshev polynomial). Then you decide what decimal precision you want. e.g. if you want 7 digits precision, you look that up in the appropriate table in the book I mentioned, and it will give you (for precision = 7.33) a number N = 4 and a polynomial number 3502. N is the order of the polynomial (so it's p4.x^4 + p3.x^3 + p2.x^2 + p1.x + p0), because N=4. Then you look up the actual value of the p4,p3,p2,p1,p0 values in the back of the book under 3502 (they'll be in floating point). Then you implement your algorithm in software in the form: (((p4.x + p3).x + p2).x + p1).x + p0 ....and this is how you'd calculate cosine to 7 decimal places on that hardware.
Note that most hardware implementations of transcendental operations in an FPU usually involve some microcode and operations like this (depends on the hardware). Chebyshev polynomials are used for most transcendentals but not all. e.g. Square root is faster to use a double iteration of Newton raphson method using a lookup table first. Again, that book "Computer Approximations" will tell you that.
If you plan on implmementing these functions, I'd recommend to anyone that they get a copy of that book. It really is the bible for these kinds of algorithms. Note that there are bunches of alternative means for calculating these values like cordics, etc, but these tend to be best for specific algorithms where you only need low precision. To guarantee the precision every time, the chebyshev polynomials are the way to go. Like I said, well defined problem. Has been solved for 50 years now.....and thats how it's done.
Now, that being said, there are techniques whereby the Chebyshev polynomials can be used to get a single precision result with a low degree polynomial (like the example for cosine above). Then, there are other techniques to interpolate between values to increase the accuracy without having to go to a much larger polynomial, such as "Gal's Accurate Tables Method". This latter technique is what the post referring to the ACM literature is referring to. But ultimately, the Chebyshev Polynomials are what are used to get 90% of the way there.
Enjoy.
with for-loop:
std::ifstream myFile;
std::string line;
int lines;
myFile.open(path);
for(lines = 0; std::getline(myFile,line); lines++);
std::cout << lines << std::endl;
Since this appears to be a simple parent/child relationship between pets
and pets_activities
, you would be better off creating your foreign key constraint with a deleting cascade.
That way, when a pets
row is deleted, the pets_activities
rows associated with it are automatically deleted as well.
Then your query becomes a simple:
delete from `pets`
where `order` > :order
and `pet_id` = :pet_id
If you throw an exception without a variable (the second example) the StackTrace will include the original method that threw the exception.
In the first example the StackTrace will be changed to reflect the current method.
Example:
static string ReadAFile(string fileName) {
string result = string.Empty;
try {
result = File.ReadAllLines(fileName);
} catch(Exception ex) {
throw ex; // This will show ReadAFile in the StackTrace
throw; // This will show ReadAllLines in the StackTrace
}
In Firefox - Firebug:
console.dir(<object>);
Standard JS to get object keys borrowed from Slashnick:
var fGetKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
// Example to call it:
var arrKeys = fGetKeys(document);
for (var i=0, n=arrKeys.length; i<n; i++){
console.log(i+1 + " - " + arrKeys[i] + document[arrKeys[i]] + "\n");
}
<object>
in the above is to be replaced with the variable reference to the object.console.log()
is to be used in the console, if you're unsure what that is, you can replace it with an alert()
By lines I assume you mean rows in the table person
. What you're looking for is:
select p.name
from person p
where p.name LIKE '%A%'; --contains the character 'A'
The above is case sensitive. For a case insensitive search, you can do:
select p.name
from person p
where UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'
For the special character, you can do:
select p.name
from person p
where p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)
The LIKE
operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the %
sign as it means match zero or more characters.
Source Code for Remote for VLC - VLC Remote
The pipe character |
has a special meaning in regular expressions. a|b
means "match either a
or b
". If you want to match a literal |
character, you need to escape it:
... | Select-String -Pattern 'H\|159' -NotMatch | ...
!important
, after your CSS declaration.
div {
color: blue !important;
/* This Is Now Working */
}
I figured it out from the PostgreSQL docs, the exact syntax is:
ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
Thanks Fred.
There is a promising answer at Problem updating bokeh: [WinError 126] The specified module could not be found.
It hints at https://github.com/conda/conda/issues/9313.
There, you find:
It's a library load issue. More details at github.com/conda/conda/issues/8836 You probably have a broken conda right now. You can use a standalone conda from repo.anaconda.com/pkgs/misc/conda-execs to repair it: standalone-conda.exe update -p C:\ProgramData\Anaconda3 conda-package-handling You should get version 1.6.0, and the problems should go away.
Thus, it might simply be a conda issue. Reinstalling standalone conda might repair the error. Please comment whoever can confirm this.
You have:
foreach (var category in Model.Categories)
and then
@foreach (var product in Model)
Based on that view and model it seems that Model
is of type Product
if yes then the second foreach
is not valid. Actually the first one could be the one that is invalid if you return a collection of Product
.
UPDATE:
You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?
I'm surprised your code compiles when you said you are returning a model of Product
type. Here's how you can do it:
@foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in category.Products)
{
<li>
put the rest of your code
</li>
}
</ul>
</div>
}
That suggest that instead of returning a Product
, you return a collection of Category
with Products. Something like this in EF:
// I am typing it here directly
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)
If your FK column table should contain that FK value as a primary key Value then data will be inserted.
Java 8 introduced a new API for working with dates and times: the java.time package.
With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant
.
Instant instant = Instant.ofEpochSecond( timeStamp );
If you need a java.util.Date
to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.
Date date = Date.from( instant );
Use the built-in python function quit() and that's it. No need to import any library. I'm using python 3.4
You can accomplish this with :before and :after without knowing the width of container or background color, and using them allows for greater styling of the line breaks. For example, this can be modified to make double-lines, dotted lines, etc.
CSS, and HTML usage:
.hr-sect {
display: flex;
flex-basis: 100%;
align-items: center;
color: rgba(0, 0, 0, 0.35);
margin: 8px 0px;
}
.hr-sect:before,
.hr-sect:after {
content: "";
flex-grow: 1;
background: rgba(0, 0, 0, 0.35);
height: 1px;
font-size: 0px;
line-height: 0px;
margin: 0px 8px;
}
_x000D_
<div class="hr-sect">CATEGORY</div>
_x000D_
SCSS Version:
.hr-sect {
display: flex;
flex-basis: 100%;
align-items: center;
color: rgba(0, 0, 0, 0.35);
margin: 8px 0;
&:before, &:after {
content: "";
flex-grow: 1;
background: rgba(0, 0, 0, 0.35);
height: 1px;
font-size: 0;
line-height: 0;
margin: 0 8px;
}
}
docker start -a -i `docker ps -q -l`
Explanation:
docker start
start a container (requires name or ID)
-a
attach to container
-i
interactive mode
docker ps
List containers
-q
list only container IDs
-l
list only last created container
I just copy all amazon.com "select list", you can see demo from following image.gif link.
I love amazon.com "select/option" css style and javascript tricks...
try it now....
/***javascript code***/
document.querySelector("#mySelect").addEventListener("click", () => {
var x = document.querySelector("#mySelect").selectedIndex;
let optionText = document.getElementsByTagName("option")[x].innerText;
document.querySelector(".nav-search-label").innerText = optionText;
});
_x000D_
/***style.css***/
.nav-left {
display: -webkit-box;
display: -moz-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
position: static;
float: none;
}
.nav-search-scope {
display: -webkit-box;
display: -moz-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
position: relative;
float: none;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.nav-search-facade {
position: relative;
float: left;
cursor: default;
overflow: hidden;
top: 3px;
}
.nav-search-label {
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: #555;
font-size: 12px;
line-height: 33px;
margin-right: 21px;
margin-left: 5px;
min-width: 19px;
}
.nav-icon {
position: absolute;
top: 14px;
right: 8px;
border-style: solid;
_border-style: dashed;
border-width: 4px;
border-color: transparent;
border-top: 4px solid #666;
border-bottom-width: 0;
width: 0;
height: 0;
font-size: 0;
line-height: 0;
}
.nav-search-dropdown {
position: absolute;
display: block;
top: -1px;
left: 0;
height: 35px;
width: auto;
font-family: inherit;
outline: 0;
margin: 0;
padding: 0;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
visibility: visible;
border: 0;
line-height: 35px;
}
_x000D_
<!--html code-->
<div class="nav-left">
<div id="nav-search-dropdown-card">
<div class="nav-search-scope nav-sprite">
<div class="nav-search-facade">
<span class="nav-search-label" style="width: auto">All</span>
<i class="nav-icon"></i>
</div>
<select
id="mySelect"
class="nav-search-dropdown searchSelect"
style="display: block; top: 3px"
tabindex="0"
title="Search in"
>
<option>All Departments</option>
<option>Arts & Crafts</option>
<option>Automotive</option>
<option>Baby</option>
<option>Beauty & Personal Care</option>
<option>Books</option>
<option>Computers</option>
<option>Digital Music</option>
<option>Electronics</option>
<option>Kindle Store</option>
<option>Prime Video</option>
<option>Women's Fashion</option>
<option>Men's Fashion</option>
<option>Girls' Fashion</option>
<option>Boys' Fashion</option>
<option>Deals</option>
<option>Health & Household</option>
<option>Home & Kitchen</option>
<option>Industrial & Scientific</option>
<option>Luggage</option>
<option>Movies & TV</option>
<option>Music, CDs & Vinyl</option>
<option>Pet Supplies</option>
<option>Software</option>
<option>Sports & Outdoors</option>
<option>Tools & Home Improvement</option>
<option>Toys & Games</option>
<option>Video Games</option>
</select>
</div>
</div>
</div>
_x000D_
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
I am using this simple one line code for years without a problem (it requires jQuery):
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>
Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.
<form id="form_id">
...
<input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>
To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:
Pattern 1 - using one-line methods for object creation
To use pattern 1 (testing a class called MyClass), you would replace a call like
Foo foo = new Foo( a, b, c );
with
Foo foo = makeFoo( a, b, c );
and write a one-line method
Foo makeFoo( A a, B b, C c ) { return new Foo( a, b, c ); }
It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.
When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.
Your test class might contain members like
@Mock private Foo mockFoo; private MyClass toTest = spy(new MyClass());
Lastly, inside your test method you mock out the call to makeFoo with a line like
doReturn( mockFoo ) .when( toTest ) .makeFoo( any( A.class ), any( B.class ), any( C.class ));
You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.
If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:
Just discovered that AlertDialogs
's boolean cancel(...);
I've been using everywhere actually does nothing. Great.
So...
public class MyTask extends AsyncTask<Void, Void, Void> {
private volatile boolean running = true;
private final ProgressDialog progressDialog;
public MyTask(Context ctx) {
progressDialog = gimmeOne(ctx);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});
}
@Override
protected void onPreExecute() {
progressDialog.show();
}
@Override
protected void onCancelled() {
running = false;
}
@Override
protected Void doInBackground(Void... params) {
while (running) {
// does the hard work
}
return null;
}
// ...
}
Accessing a single row
//Result as an Object
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row();
echo $result->age;
//Result as an Array
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row_array();
echo $result['age'];
Just press windows button and type %APPDATA% and type enter.
Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.
Suppose we have three anchor tags like ,
<a href="ID=1" class="testClick">Test1.</a>
<br />
<a href="ID=2" class="testClick">Test2.</a>
<br />
<a href="ID=3" class="testClick">Test3.</a>
now in script
$(".testClick").click(function () {
var anchorValue= $(this).attr("href");
alert(anchorValue);
});
use this keyword instead of className (testClick)
I think to be consistant it's nicer to use @throw with your own class that extends NSException. Then you use the same notations for try catch finally:
@try {
.....
}
@catch{
...
}
@finally{
...
}
Apple explains here how to throw and handle exceptions: Catching Exceptions Throwing Exceptions
If you want to checkout all the files 'anywhere'
git checkout -- $(git rev-parse --show-toplevel)
counter[row[11]]+=1
You don't show what data
is, but apparently when you loop through its rows, row[11]
is turning out to be a list
. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11]
as a key causes the defaultdict
to complain that it is a mutable, i.e. unhashable, object.
The easiest fix is to change row[11]
from a list
to a tuple
. Either by doing
counter[tuple(row[11])] += 1
or by fixing it in the caller before data
is passed to medications_minimum3
. A tuple simply an immutable list, so it behaves exactly like a list does except you cannot change it once it is created.
Typings can be configured with the ~/.typingsrc
config file. (~
means your home directory)
After finding this issue on github: https://github.com/typings/typings/issues/120, I was able to hack around this issue by creating ~/.typingsrc
and setting this configuration:
{
"proxy": "http://<server>:<port>",
"rejectUnauthorized": false
}
It also seemed to work without the proxy
setting, so maybe it was able to pick that up from the environment somewhere.
This is not a true solution, but was enough for typings
to ignore the corporate firewall issues so that I could continue working. I'm sure there is a better solution out there.
Actually I want timestamp based shorter unique identifier, hence tried the below program.
It is guessable with nanosecond + ( endians.length * endians.length )
combinations.
public class TimStampShorterUUID {
private static final Character [] endians =
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
private static ThreadLocal<Character> threadLocal = new ThreadLocal<Character>();
private static AtomicLong iterator = new AtomicLong(-1);
public static String generateShorterTxnId() {
// Keep this as secure random when we want more secure, in distributed systems
int firstLetter = ThreadLocalRandom.current().nextInt(0, (endians.length));
//Sometimes your randomness and timestamp will be same value,
//when multiple threads are trying at the same nano second
//time hence to differentiate it, utilize the threads requesting
//for this value, the possible unique thread numbers == endians.length
Character secondLetter = threadLocal.get();
if (secondLetter == null) {
synchronized (threadLocal) {
if (secondLetter == null) {
threadLocal.set(endians[(int) (iterator.incrementAndGet() % endians.length)]);
}
}
secondLetter = threadLocal.get();
}
return "" + endians[firstLetter] + secondLetter + System.nanoTime();
}
public static void main(String[] args) {
Map<String, String> uniqueKeysTestMap = new ConcurrentHashMap<>();
Thread t1 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t3 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t4 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t5 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t6 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t7 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
}
}
UPDATE: This code will work on single JVM, but we should think on distributed JVM, hence i am thinking two solutions one with DB and another one without DB.
with DB
Company name (shortname 3 chars) ---- Random_Number ---- Key specific redis COUNTER
(3 char) ------------------------------------------------ (2 char) ---------------- (11 char)
without DB
IPADDRESS ---- THREAD_NUMBER ---- INCR_NUMBER ---- epoch milliseconds
(5 chars) ----------------- (2char) ----------------------- (2 char) ----------------- (6 char)
will update you once coding is done.
Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.
For arrays:
{{#each myArray}}
Index: {{@index}} Value = {{this}}
{{/each}}
For objects:
{{#each myObject}}
Key: {{@key}} Value = {{this}}
{{/each}}
Note that only properties passing the hasOwnProperty
test will be enumerated.
attr_accessor
is getter
, setter
method.
whereas attr_accessible
is to say that particular attribute is accessible or not. that's it.
I wish to add we should use Strong parameter instead of attr_accessible
to protect from mass asignment.
Cheers!
You can do this in the 'Conditional Formatting' tool in the Home tab of Excel 2010.
Assuming the existing rule is 'Use a formula to dtermine which cells to format':
Edit the existing rule, so that the 'Formula' refers to relative rows and columns (i.e. remove $s), and then in the 'Applies to' box, click the icon to make the sheet current and select the cells you want the formatting to apply to (absolute cell references are ok here), then go back to the tool panel and click Apply.
This will work assuming the relative offsets are appropriate throughout your desired apply-to range.
You can copy conditional formatting from one cell to another or a range using copy and paste-special with formatting only, assuming you do not mind copying the normal formats.
You can use EL if you want to work as IF:
<h:outputLabel value="#{row==10? '10' : '15'}"/>
Changing styles or classes:
style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"
class="#{test eq testMB.test? 'divRred' : 'divGreen'}"
If you want to scroll the element you're over and prevent the window to scroll, here's a really useful function :
$('.Scrollable').on('DOMMouseScroll mousewheel', function(ev) {
var $this = $(this),
scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
height = $this.height(),
delta = (ev.type == 'DOMMouseScroll' ?
ev.originalEvent.detail * -40 :
ev.originalEvent.wheelDelta),
up = delta > 0;
var prevent = function() {
ev.stopPropagation();
ev.preventDefault();
ev.returnValue = false;
return false;
}
if (!up && -delta > scrollHeight - height - scrollTop) {
// Scrolling down, but this will take us past the bottom.
$this.scrollTop(scrollHeight);
return prevent();
} else if (up && delta > scrollTop) {
// Scrolling up, but this will take us past the top.
$this.scrollTop(0);
return prevent();
}
});
Apply the class "Scrollable" to your element and that's it!
We weren't happy with any of the purposed solutions.
So we've created a complete char counter solution for JQuery, built on top of jquery-jeditable. It's a textarea
plugin extension that can count to both ways, displays a custom message, limits char count and also supports jquery-datatables.
You can test it right away on JSFiddle.
GitHub link: https://github.com/HippotecLTD/realworld_jquery_jeditable_charcount
Add these lines to your HTML:
<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/[email protected]/dist/jquery.jeditable.charcounter.realworld.min.js"></script>
<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/[email protected]/dist/jquery.charcounter.realworld.min.js"></script>
And then:
$("#myTextArea4").charCounter();
After some test, I found that for bootstrap modal need to wait for some time before executing the $(.modal).modal('hide')
after executing $(.modal).modal('show')
. And i found in my case i need at least 500 milisecond interval between the two.
So this is my test case and solution:
$('.modal-loading').modal('show');
setTimeout(function() {
$('.modal-loading').modal('hide');
}, 500);
I believe I found the answer. Per the Xcode 12 beta 6 release notes:
"The Build Settings editor no longer includes the Valid Architectures build setting (VALID_ARCHS), and its use is discouraged. Instead, there is a new Excluded Architectures build setting (EXCLUDED_ARCHS). If a project includes VALID_ARCHS, the setting is displayed in the User-Defined section of the Build Settings editor. (15145028)"
I was able to resolve this issue by manually editing the project file (I could not figure out how to remove the item from the project file using Xcode) and removing all lines referring to VALID_ARCHS. After that, I am able to build for the simulator fine.
I run into the same error maybe you have already imported the module by using only import datetime
so change form datetime import datetime
to only import datetime
. It worked for me after I changed it back.
Just another repeat function:
function repeat(s, n) {
var str = '';
for (var i = 0; i < n; i++) {
str += s;
}
return str;
}
It allocates space on the heap equal to an integer array of size N, and returns a pointer to it, which is assigned to int* type pointer called "array"
Sometimes you still need to use FirstOrDefault if you have to do different tests. If the Key component of your dictionnary is nullable, you can do this:
thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }
Using FirstOrDefault, the returned KeyValuePair's key and value will both be null if no match is found.
And a minimal one (if you don't want to include Apache Commons or Gauva into project dependencies just for the sake of joining strings)
/**
*
* @param delim : String that should be kept in between the parts
* @param parts : parts that needs to be joined
* @return a String that's formed by joining the parts
*/
private static final String join(String delim, String... parts) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.length - 1; i++) {
builder.append(parts[i]).append(delim);
}
if(parts.length > 0){
builder.append(parts[parts.length - 1]);
}
return builder.toString();
}
Use RelativeLayout (container) and android:layout_centerHorizontal="true" ,my sample:
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" >
<CheckBox
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:button="@drawable/bg_fav_detail"
android:drawablePadding="5dp"
android:text=" Favorite" />
</RelativeLayout>
SELECT CONVERT(char(10), GetDate(),126)
Limiting the size of the varchar chops of the hour portion that you don't want.
Maintain a set
and remove a randomly picked-up element (with choice
) until the list is empty:
s = set(range(1, 6))
import random
while len(s) > 0:
s.remove(random.choice(list(s)))
print(s)
Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
First i tried with this sample code:
$(document).ready(function(){
$('#upload-file').click();
});
It didn't work for me. Then after, tried with this
$(document).ready(function(){
$('#upload-file')[0].click();
});
No change. At last, tried with this
$(document).ready(function(){
$('#upload-file')[0].click(function(){
});
});
Solved my problem. Helpful for anyone.
I liked Jed's solution but the issue with that was every time I built my project in debug mode, it would deploy my database project and removed the user again. so I added this MySQL script to the Post-Deployment script. it practically does what Jed said but creates the user every time I deploy.
CREATE USER [NT AUTHORITY\NETWORK SERVICE]
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE]
WITH DEFAULT_SCHEMA = dbo;
Go
EXEC sp_addrolemember 'db_owner', 'NT AUTHORITY\NETWORK SERVICE'
SSIS is a no-brainer for doing stuff like this and is very straight forward (and this is just the kind of thing it is for).
If you wanted, you could save the SSIS package as well (there's an option at the end of the wizard) so that you can do it on a schedule or something (and even open and modify to add more functionality if needed).
Re: changing opts to theme etc (for lazy folks):
theme(axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.position="none",
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
plot.background=element_blank())
You can also watch the video about this new featue
UPDATE as of angularjs 1.2, the way animations work has changed drastically, most of it is now controlled with CSS, without having to setup javascript callbacks, etc.. You can check the updated tutorial on Year Of Moo. @dfsq pointed out in the comments a nice set of examples.
You will get like this error
Try the following steps
1. Open Command Prompt (Press Windows key and type "cmd" and hit Enter)
Then type this command as show in picture
netstat -aon | find ":8080" | find "LISTENING"
How about
if (length ($name || '')) {
# do something with $name
}
This isn't quite equivalent to your original version, as it will also return false if $name
is the numeric value 0 or the string '0'
, but will behave the same in all other cases.
In perl 5.10 (or later), the appropriate approach would be to use the defined-or operator instead:
use feature ':5.10';
if (length ($name // '')) {
# do something with $name
}
This will decide what to get the length of based on whether $name
is defined, rather than whether it's true, so 0/'0'
will handle those cases correctly, but it requires a more recent version of perl than many people have available.
I usually sweep out a visual block (<C-V>
), then search and replace the first character with:
:'<,'>s/^/#
(Entering command mode with a visual block selected automatically places '<,'> on the command line) I can then uncomment the block by sweeping out the same visual block and:
:'<,'>s/^#//
To load other file(css ,js) and folder(images) , in codeigniter project
we have to follow two simple step:
1.create folder public (can give any name) in your codeigniters folder put your bootstrap files css and js folder in side public folder. https://i.stack.imgur.com/O2gr6.jpg
2.now we have to use two line of code 1.load->helper('url'); ?> 2.
go to your view file
put first line to load base URL
<?php $this->load->helper('url'); ?>
secondly in your html head tag put this
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/public/css/bootstrap.css">
now you can enjoy the bootstrap in your codeigniter
Note: This applies to pre-4 VirtualBox. In VB4, HDD expansion has been introduced.
According to the VirtualBox documentation:
When creating an image, its size needs to be specified, which determines this fixed geometry. It is therefore not possible to change the size of the virtual hard disk later.
So, the easiest way to add additional space to an existing VM is to attach a second hard disk. Go to the VM Settings > Hard Disks > Add New. Then, click the "Select Hard Drive" button and click on "New". Follow the wizard to create a new virtual hard disk. It will then show up as D:
or E:
in your guest OS.
All of the answers above are correct; attr_reader
and attr_writer
are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.
Bear in mind the consequences
SELECT REPLACE(REPLACE('TEST123','123','456'),'45','89') FROM DUAL;
will replace the 123 with 456, then find that it can replace the 45 with 89. For a function that had an equivalent result, it would have to duplicate the precedence (ie replacing the strings in the same order).
Similarly, taking a string 'ABCDEF', and instructing it to replace 'ABC' with '123' and 'CDE' with 'xyz' would still have to account for a precedence to determine whether it went to '123EF' or ABxyzF'.
In short, it would be difficult to come up with anything generic that would be simpler than a nested REPLACE (though something that was more of a sprintf style function would be a useful addition).
1) How do I make it so that the whole column is "checked" by default?
var doWork = new DataGridViewCheckBoxColumn();
doWork.Name = "IncludeDog" //Added so you can find the column in a row
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
//Make the default checked
doWork.CellTemplate.Value = true;
doWork.CellTemplate.Style.NullValue = true;
dataGridView1.Columns.Insert(0, doWork);
2) How can I make sure I'm only getting values from the "checked" rows?
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) continue;//If editing is enabled, skip the new row
//The Cell's Value gets it wrong with the true default, it will return
//false until the cell changes so use FormattedValue instead.
if (Convert.ToBoolean(row.Cells["IncludeDog"].FormattedValue))
{
//Do stuff with row
}
}
Basically an index is a map of all your keys that is sorted in order. With a list in order, then instead of checking every key, it can do something like this:
1: Go to middle of list - is higher or lower than what I'm looking for?
2: If higher, go to halfway point between middle and bottom, if lower, middle and top
3: Is higher or lower? Jump to middle point again, etc.
Using that logic, you can find an element in a sorted list in about 7 steps, instead of checking every item.
Obviously there are complexities, but that gives you the basic idea.
Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.
Use the below method for calculating the distance of two different locations.
public double getKilometers(double lat1, double long1, double lat2, double long2) {
double PI_RAD = Math.PI / 180.0;
double phi1 = lat1 * PI_RAD;
double phi2 = lat2 * PI_RAD;
double lam1 = long1 * PI_RAD;
double lam2 = long2 * PI_RAD;
return 6371.01 * acos(sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(lam2 - lam1));}
Here's a class I wrote do multiple inserts with purge option:
<?php
/**
* $pdo->beginTransaction();
* $pmi = new PDOMultiLineInserter($pdo, "foo", array("a","b","c","e"), 10);
* $pmi->insertRow($data);
* ....
* $pmi->insertRow($data);
* $pmi->purgeRemainingInserts();
* $pdo->commit();
*
*/
class PDOMultiLineInserter {
private $_purgeAtCount;
private $_bigInsertQuery, $_singleInsertQuery;
private $_currentlyInsertingRows = array();
private $_currentlyInsertingCount = 0;
private $_numberOfFields;
private $_error;
private $_insertCount = 0;
function __construct(\PDO $pdo, $tableName, $fieldsAsArray, $bigInsertCount = 100) {
$this->_numberOfFields = count($fieldsAsArray);
$insertIntoPortion = "INSERT INTO `$tableName` (`".implode("`,`", $fieldsAsArray)."`) VALUES";
$questionMarks = " (?".str_repeat(",?", $this->_numberOfFields - 1).")";
$this->_purgeAtCount = $bigInsertCount;
$this->_bigInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks.str_repeat(", ".$questionMarks, $bigInsertCount - 1));
$this->_singleInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks);
}
function insertRow($rowData) {
// @todo Compare speed
// $this->_currentlyInsertingRows = array_merge($this->_currentlyInsertingRows, $rowData);
foreach($rowData as $v) array_push($this->_currentlyInsertingRows, $v);
//
if (++$this->_currentlyInsertingCount == $this->_purgeAtCount) {
if ($this->_bigInsertQuery->execute($this->_currentlyInsertingRows) === FALSE) {
$this->_error = "Failed to perform a multi-insert (after {$this->_insertCount} inserts), the following errors occurred:".implode('<br/>', $this->_bigInsertQuery->errorInfo());
return false;
}
$this->_insertCount++;
$this->_currentlyInsertingCount = 0;
$this->_currentlyInsertingRows = array();
}
return true;
}
function purgeRemainingInserts() {
while ($this->_currentlyInsertingCount > 0) {
$singleInsertData = array();
// @todo Compare speed - http://www.evardsson.com/blog/2010/02/05/comparing-php-array_shift-to-array_pop/
// for ($i = 0; $i < $this->_numberOfFields; $i++) $singleInsertData[] = array_pop($this->_currentlyInsertingRows); array_reverse($singleInsertData);
for ($i = 0; $i < $this->_numberOfFields; $i++) array_unshift($singleInsertData, array_pop($this->_currentlyInsertingRows));
if ($this->_singleInsertQuery->execute($singleInsertData) === FALSE) {
$this->_error = "Failed to perform a small-insert (whilst purging the remaining rows; the following errors occurred:".implode('<br/>', $this->_singleInsertQuery->errorInfo());
return false;
}
$this->_currentlyInsertingCount--;
}
}
public function getError() {
return $this->_error;
}
}
I'm not a regex guru by any means. But try:
<[A-Z0-9][A-Z0-9]+>
< start of word
[A-Z0-9] one character
[A-Z0-9]+ and one or more of them
> end of word
I won't try for the bonus points of the whole upper case sentence. hehe
I find I rarely have need to use getCanonicalPath()
but, if given a File with a filename that is in DOS 8.3 format on Windows, such as the java.io.tmpdir
System property returns, then this method will return the "full" filename.
I made this short example which also works.
#include <iostream>
#include <type_traits>
class foo;
class bar;
template<class T>
struct is_bar
{
template<class Q = T>
typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
{
return true;
}
template<class Q = T>
typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
{
return false;
}
};
int main()
{
is_bar<foo> foo_is_bar;
is_bar<bar> bar_is_bar;
if (!foo_is_bar.check() && bar_is_bar.check())
std::cout << "It works!" << std::endl;
return 0;
}
Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)
You can see it in action here.
Set the background and text color of section area: (Thanks to William Jockusch
and Dj S
)
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
castView.contentView.backgroundColor = [UIColor grayColor];
[castView.textLabel setTextColor:[UIColor grayColor]];
}
}
I update my forked repos with this one line:
git pull https://github.com/forkuser/forkedrepo.git branch
Use this if you dont want to add another remote endpoint to your project, as other solutions posted here.
At last this post helps me on iOS: http://www.excellentwebworld.com/phonegap-open-a-link-in-safari-or-external-browser/.
Open "CDVwebviewDelegate.m" file and search "shouldStartLoadWithRequest", then add this code to the beginning of the function:
if([[NSString stringWithFormat:@"%@",request.URL] rangeOfString:@"file"].location== NSNotFound) { [[UIApplication sharedApplication] openURL:[request URL]]; return NO; }
While using navigator.app.loadUrl("http://google.com", {openExternal : true});
for Android is OK.
Via Cordova 3.3.0.
Of-course this is an old thread but to make it complete.
From SQL 2008 you can use DATE datatype so you can simply do:
SELECT CONVERT(DATE,GETDATE())
You may want to try changing the environment variable "PYTHONIOENCODING" to "utf_8". I have written a page on my ordeal with this problem.
Tl;dr of the blog post:
import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print(chr(246), chr(9786), chr(9787))
gives you
utf_8
False
ANSI_X3.4-1968
ascii
utf_8
ö ? ?
I use
SHOW CREATE TABLE mytable;
This shows you the SQL statement necessary to receate mytable
in its current form. You can see all the columns and their types (like DESC
) but it also shows you constraint information (and table type, charset, etc.).
Try using an ontouch listener instead of a clicklistener.
http://developer.android.com/reference/android/view/View.OnTouchListener.html
On Arch Linux run the following:
sudo pacman -S base-devel
You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.
Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it
After these configurations, you can manage your console with control characters like:
\t - tab.
\b - backspace (a step backward in the text or deletion of a single character).
\n - new line.
\r - carriage return. ()
\f - form feed.
More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php
No, its not possible, since static members are bound at compile time, while virtual members are bound at runtime.
On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755
Html:
<div class="outerDiv">
<div class="innerDiv">Content</div>
</div>
CSS:
.outerDiv{
background: #000;
padding: 10px;
}
.innerDiv{
border: 2px dashed #fff;
min-height: 200px; //adding min-height as there is no content inside
}
add list using
<asp:ListItem Value="United States" Text="Canada"></asp:ListItem>
and then try
DropDownList1.SelectedItem.Text
I found your mistake.
<asp:ListItem>United States</asp:ListItem>
change this to
<asp:ListItem>United States1</asp:ListItem>
Then you will got the actual value.
What was the issue is, there are two same values in your dropdown, when page postback, it take first value as selected and give the result accordingly. if you noticed when after postback United State Value is selected
:last-child
only works when the element in question is the last child of the container, not the last of a specific type of element. For that, you want :last-of-type
As per @BoltClock's comment, this is only checking for the last article
element, not the last element with the class of .comment
.
body {_x000D_
background: black;_x000D_
}_x000D_
_x000D_
.comment {_x000D_
width: 470px;_x000D_
border-bottom: 1px dotted #f0f0f0;_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
.comment:last-of-type {_x000D_
border-bottom: none;_x000D_
margin-bottom: 0;_x000D_
}
_x000D_
<div class="commentList">_x000D_
<article class="comment " id="com21"></article>_x000D_
_x000D_
<article class="comment " id="com20"></article>_x000D_
_x000D_
<article class="comment " id="com19"></article>_x000D_
_x000D_
<div class="something"> hello </div>_x000D_
</div>
_x000D_
Here's a simple example..
List<char> c = new List<char>() { 'A', 'B', 'C' };
List<string> s = c.Select(x => x.ToString()).ToList();
Wildcard Characters are used with like clause to sort records.
if we want to search a string which is starts with B then code is like the following:
select * from tablename where colname like 'B%' order by columnname ;
if we want to search a string which is ends with B then code is like the following: select * from tablename where colname like '%B' order by columnname ;
if we want to search a string which is contains B then code is like the following: select * from tablename where colname like '%B%' order by columnname ;
if we want to search a string in which second character is B then code is like the following: select * from tablename where colname like '_B%' order by columnname ;
if we want to search a string in which third character is B then code is like the following: select * from tablename where colname like '__B%' order by columnname ;
note : one underscore for one character.
To increase the memory or CPU count when using Vagrant 2, add this to your Vagrantfile
Vagrant.configure("2") do |config|
# usual vagrant config here
config.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 2
end
end
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
I know this question is a little old but the following worked for me in a Jupyter Notebook running pandas 0.22.0 and Python 3:
import pandas as pd
pd.set_option('display.max_columns', <number of columns>)
You can do the same for the rows too:
pd.set_option('display.max_rows', <number of rows>)
This saves importing IPython, and there are more options in the pandas.set_option documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html
declare @p varbinary(max)
set @p = 0x
declare @local table (col text)
SELECT @p = @p + 0x3B + CONVERT(varbinary(100), Email)
FROM tbCarsList
where email <> ''
group by email
order by email
set @p = substring(@p, 2, 100000)
insert @local values(cast(@p as varchar(max)))
select DATALENGTH(col) as collen, col from @local
result collen > 8000, length col value is more than 8000 chars
To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.
The following will return the string represention you wanted:
DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)
use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3
private void button1_Click(object sender, EventArgs e)
{
int h =3;
Button[] buttonArray = new Button[8];
for (int i = 0; i <= h-1; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(20, 43);
buttonArray[i].Name= ""+i+"";
buttonArray[i].Click += button_Click;//function
buttonArray[i].Location = new Point(40, 20 + (i * 20));
panel1.Controls.Add(buttonArray[i]);
} }
Look at the jQuery unload function. It handles all the things.
https://api.jquery.com/unload/
The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.
$(window).unload(
function(event) {
alert("navigating");
}
);
This one will solve all your problems not only for Mac but works on every basic shell -> Linux also:
If you have a Mac and you've installed python3 like most of us do :) (with brew install - ofc)
your file is located in:
/usr/local/Cellar/python/3.6.4_4/bin/python3
How do you know? -> you can run this on every basic shell Run:
which python3
You should get:
/usr/local/bin/python3
Now this is a symbolic link, how do you know? Run:
ls -al /usr/local/bin/python3
and you'll get:
/usr/local/bin/python3 -> /usr/local/Cellar/python/3.6.4_4/bin/python3
which means that your
/usr/local/bin/python3
is actually pointing to:
/usr/local/Cellar/python/3.6.4_4/bin/python3
If, for some reason, your
/usr/local/bin/python3
is not pointing to the place you want, which in our case:
/usr/local/Cellar/python/3.6.4_4/bin/python3
just backup it:
cp /usr/local/bin/python3{,.orig}
and run:
rm -rf /usr/local/bin/python3
now create a new symbolic link:
ln -s /usr/local/Cellar/python/3.6.4_4/bin/python3 /usr/local/bin/python3
and now your
/usr/local/bin/python3
is pointing to
/usr/local/Cellar/python/3.6.4_4/bin/python3
Check it out by running:
ls -al /usr/local/bin/python3
As mentioned by Roger Pate following code worked for me:
s = " \t foo \n bar "
"".join(s.split())
'foobar'
I am using Jupyter Notebook to run following code:
i=0
ProductList=[]
while i < len(new_list):
temp='' # new_list[i]=temp=' Plain Utthapam '
#temp=new_list[i].strip() #if we want o/p as: 'Plain Utthapam'
temp="".join(new_list[i].split()) #o/p: 'PlainUtthapam'
temp=temp.upper() #o/p:'PLAINUTTHAPAM'
ProductList.append(temp)
i=i+2
This is only a warning: your code still works, but probably won't work in the future as the method is deprecated. See the relevant source of Chromium and corresponding patch.
This has already been recognised and fixed in jQuery 1.11 (see here and here).
The "protected internal" access modifier is a union of both the "protected" and "internal" modifiers.
From MSDN, Access Modifiers (C# Programming Guide):
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal:
The type or member can be accessed by any code in the assembly in which it is declared, OR from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
Note that: protected internal
means "protected
OR internal
" (any class in the same assembly, or any derived class - even if it is in a different assembly).
...and for completeness:
The type or member can be accessed only by code in the same class or struct.
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
Access is limited to the containing class or types derived from the containing class within the current assembly.
(Available since C# 7.2)
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
It should be noted as well that this will of course only find all those subclasses that exist on your current classpath. Presumably this is OK for what you are currently looking at, and chances are you did consider this, but if you have at any point released a non-final
class into the wild (for varying levels of "wild") then it is entirely feasible that someone else has written their own subclass that you will not know about.
Thus if you happened to be wanting to see all subclasses because you want to make a change and are going to see how it affects subclasses' behaviour - then bear in mind the subclasses that you can't see. Ideally all of your non-private methods, and the class itself should be well-documented; make changes according to this documentation without changing the semantics of methods/non-private fields and your changes should be backwards-compatible, for any subclass that followed your definition of the superclass at least.
If you're swapping numbers and want a concise way to write the code without creating a separate function or using a confusing XOR hack, I find this is much easier to understand and it's also a one liner.
public static void swap(int[] arr, int i, int j) {
arr[i] = (arr[i] + arr[j]) - (arr[j] = arr[i]);
}
What I've seen from some primitive benchmarks is that the performance difference is basically negligible as well.
This is one of the standard ways for swapping array elements without using a temporary variable, at least for integers.
a = ['1', '2', '3', '4']
print len(a) - 1
3
OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.
The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.
For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream
to be changed, and as long as the API (interface) to FileInputStream
remains consistent, code built against previous versions will still work.
Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.
In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).
For example, the fields of a class can be made private
by default, and only if external access to these was required, would a get()
and/or set()
(or Property
) be exposed from the class. (In modern day OO languages, fields can be marked as readonly
/ final
/ immutable
which further restricts change, even within the class).
Example where NO information hiding has been applied (Bad Practice):
class Foo {
// BAD - NOT Encapsulated - code external to the class can change this field directly
// Class Foo has no control over the range of values which could be set.
public int notEncapsulated;
}
Example where field encapsulation has been applied:
class Bar {
// Improvement - access restricted only to this class
private int encapsulatedPercentageField;
// The state of Bar (and its fields) can now be changed in a controlled manner
public void setEncapsulatedField(int percentageValue) {
if (percentageValue >= 0 && percentageValue <= 100) {
encapsulatedPercentageField = percentageValue;
}
// else throw ... out of range
}
}
Example of immutable / constructor-only initialization of a field:
class Baz {
private final int immutableField;
public void Baz(int onlyValue) {
// ... As above, can also check that onlyValue is valid
immutableField = onlyValue;
}
// Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class
}
Re : Abstraction vs Abstract Class
Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new()
- abstract classes must be subclassed, and only concrete
(non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction
and an abstract class
was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.
Re : Encapsulation vs Information Hiding
The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation
can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.
Quoting Wikipedia:
In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.
For example, in the statement
I've encapsulated the data access code into its own class
.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.
[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed
No, not exactly. But it can inherit from a class and implement one or more interfaces.
Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.
If your compairing javascript you might find it not displaying.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=509820
Here is a workround...
- Window > Preferences > Compare/Patch > General Tab
- Deselect checkbox next to "Open structure compare automatically"
If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.
Quality Accepts 0 - 100
0 = MAX Compression (Least Quality which is suitable for Small images)
100 = Least Compression (MAX Quality which is suitable for Big images)
If you are using a local .mdf file, probably a sync software such Dropbox attempted to sync two log files (.ldf) in two different computers you can delete the log files from the bin Directory and make sure the .mdf properties->Copy to Output Directory ->Copy if newer that will copy the selected DB file and it's log to the bin Directory. !Alert- if your DB file has only changed in the bin Directory all the changes ill be discarded!
/b
parameterstart /b "" "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch
I reached this question because encountered the error message
fatal: not a git repository: '~/repos/abc'
and because I was afraid there was some incompatibilities between git versions (fortunately not),
none of the answers I read here was the solution for my case and I find some of this answers dangerous and misleading.
I got the error because I moved a repository from OpenBSD to Linux, but that could happen just by changing the shell, in OpenBSD I was using (in .kshrc
with ksh
) to invoke git
(note the form ~/
in the paths):
alias git-abc='git --git-dir=~/repos/abc --work-tree=~/Development/abc'
in OpenBSD with ksh
it works with that syntax to define aliases, while in linux with bash
the ~
inside such exact same alias definition quoted doesn't expand when the alias is invoked, I solved by removed the quotes in the alias definition.
alias git-abc=git --git-dir=~/repos/abc --work-tree=~/Development/abc
Or use my solution here www.my-mo.co.uk/device/deviceinfo.php will let you access UDID and email it to whoever you choose too.
EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,''
Notice the column Running, obviously 1 means that it is currently running, and [Current Step]. This returns job_id to you, so you'll need to look these up, e.g.:
SELECT top 100 *
FROM msdb..sysjobs
WHERE job_id IN (0x9DAD1B38EB345D449EAFA5C5BFDC0E45, 0xC00A0A67D109B14897DD3DFD25A50B80, 0xC92C66C66E391345AE7E731BFA68C668)
As the questioner writes
In the advanced tab, Valid OAuth redirect URIs is set to: ...
and I had the same problem (writing the redirect url into the wrong input field) I would like to highlight that
It's NOT
Settings -> Advanced -> Share Redirect Whitelist
but
Facebook Login -> Settings -> Valid OAuth redirect URIs
It would have saved me 2 hours of trial and error.
You should also have it in mind that
www.example.com
is not the same as example.com
. Add both formats to the redirect URL.
Thanks to both of you. This worked perfectly for me.
$("input[type='text'][id*=" + strID + "]:visible").each(function() {
this.value=strVal;
});
I found this url to be very useful: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/2cdcab2e-ea49-4fd5-b2b8-13824ab4619b/help-server-not-listening-on-1433
In particular, my problem was that I did not enable the TCP/IP in Sql Server Configuration Manager->SQL Server Network Configuration->Protocols for SQLEXPRESS.
Once you open it, you have to go to the IP Addresses tab and for me, changing IPAll to TCP port 1433 and deleting the TCP Dynamic Ports value worked.
Follow the other steps to make sure 1433 is listening (Use netstat -an to make sure 0.0.0.0:1433 is LISTENING.), and that you can telnet to the port from the client machine.
Finally, I second the suggestion to remove the \SQLEXPRESS from the connection.
EDIT: I should note I am using SQL Server 2014 Express.
The parent function needs the virtual
keyword, and the child function needs the override
keyword in front of the function definition.
you could also use rsync. It seems to work better for multiple files than scp IMHO.
rsync -avzh /path/to/dir/ user@remote:/path/to/remote/dir/
Update
You can use rsync via ssh by adding the '-e' switch:
rsync -avzh -e ssh /path/do/dir/ user@remote:/path/to/remote/dir/
$update = \DB::table('student') ->where('id', $data['id']) ->limit(1) ->update( [ 'name' => $data['name'], 'address' => $data['address'], 'email' => $data['email'], 'contactno' => $data['contactno'] ]);
I would use the yattag library. I think it's the most pythonic way:
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('food'):
with tag('name'):
text('French Breakfast')
with tag('price', currency='USD'):
text('6.95')
with tag('ingredients'):
for ingredient in ('baguettes', 'jam', 'butter', 'croissants'):
with tag('ingredient'):
text(ingredient)
print(doc.getvalue())
for future reference :
As of Babel version 7.0.0-beta.55 stage presets have been removed
refer blog https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets
async await can be still be used by
https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator#usage
installation
npm install --save-dev @babel/plugin-transform-async-to-generator
usage in .babelrc
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-transform-async-to-generator"]
}
and using babel polyfill https://babeljs.io/docs/en/babel-polyfill
installation
npm install --save @babel/polyfill
webpack.config.js
module.exports = {
entry: ["@babel/polyfill", "./app/js"],
};
Overlapping occurences:
def olpcount(string,pattern,case_sensitive=True):
if case_sensitive != True:
string = string.lower()
pattern = pattern.lower()
l = len(pattern)
ct = 0
for c in range(0,len(string)):
if string[c:c+l] == pattern:
ct += 1
return ct
test = 'my maaather lies over the oceaaan'
print test
print olpcount(test,'a')
print olpcount(test,'aa')
print olpcount(test,'aaa')
Results:
my maaather lies over the oceaaan
6
4
2
With Linq...
string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
var count = s.Split(new[] {',', ':'}).Count(s => s == "true" );
If you are already using jQuery UI in your project, you can use the built-in datepicker method for formatting your date object:
$.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));
However, the datepicker only formats dates, and cannot format times.
Have a look at jQuery UI datepicker formatDate, the examples.
% ps -o args -C nginx
COMMAND
build/sbin/nginx -c ../test.conf
If nginx was run without the -c
option, then you can use the -V
option to find out the configure arguments that were set to non-standard values. Among them the most interesting for you are:
--prefix=PATH set installation prefix
--sbin-path=PATH set nginx binary pathname
--conf-path=PATH set nginx.conf pathname
# list packages that can be updated
conda search --outdated
# update all packages prompted(by asking the user yes/no)
conda update --all
# update all packages unprompted
conda update --all -y
For those of you using Spring, you can simply reference any classpath-resource using the classpath-protocol. So in case of the wsdlLocation, this becomes:
<wsdlLocation>classpath:META-INF/webservice.wsdl</wsdlLocation>
Note that is not standard Java behavior. See also: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/resources.html
You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'
The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.
docker rmi --force $(docker images -q --filter "dangling=true")
You can try this in your web form with a button called btnSave for example:
<input type="button" id="btnSave" onclick="javascript:SaveWithParameter('Hello Michael')" value="click me"/>
<script type="text/javascript">
function SaveWithParameter(parameter)
{
__doPostBack('btnSave', parameter)
}
</script>
And in your code behind add something like this to read the value and operate upon it:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // parameter
// Request["__EVENTTARGET"]; // btnSave
}
Give that a try and let us know if that worked for you.
Question has a good pagerank on google, so for anyone who's looking for answer to this question this might be helpful.
There is an extension in google chrome marketspace to do exactly that: https://chrome.google.com/webstore/detail/hccmhjmmfdfncbfpogafcbpaebclgjcp
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime()
to get the UTC time from your local time or myDateTime.ToLocalTime()
to convert the UTC time to the local machine's time.
// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();
// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();
If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime()
or TimeZoneInfo.ConvertTimeFromUtc()
.
// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);
// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
TYPE variable = jsonbody["key"]?.Value<TYPE>() ?? DEFAULT_VALUE;
e.g.
bool attachMap = jsonbody["map"]?.Value<bool>() ?? false;
For a Swift 3 & 4 version of nevyn's answer:
UIApplication.shared.sendAction(#selector(UIView.resignFirstResponder), to: nil, from: nil, for: nil)
Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.
try if you really want to use class:
document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};
or you may assign function in html itself:
<div class="drill_cursor" onclick='alert("1");'>
</div>
Instead of using regex to remove those "crazy" characters, just convert them to ASCII, which will remove accents, but will keep the letters.
astr <- "Ábcdêãçoàúü"
iconv(astr, from = 'UTF-8', to = 'ASCII//TRANSLIT')
which results in
[1] "Abcdeacoauu"
When using bootstrap 4 or 5, flexbox could be used to achieve desired effect:
<body class="d-flex flex-column min-vh-100">
<header>HEADER</header>
<content>CONTENT</content>
<footer class="mt-auto"></footer>
</body>
Please check the examples: Bootstrap 4 Bootstrap 5
In bootstrap 3 and without use of bootstrap. The simplest and cross browser solution for this problem is to set a minimal height for body
object. And then set absolute
position for the footer with bottom: 0
rule.
body {
min-height: 100vh;
position: relative;
margin: 0;
padding-bottom: 100px; //height of the footer
box-sizing: border-box;
}
footer {
position: absolute;
bottom: 0;
height: 100px;
}
Please check this example: Bootstrap 3
Alternatively, you could invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
I liked this example.
.bashrc
is not sourced when you log in using SSH. You need to source it in your .bash_profile
like this:
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
Use bind for future calls to the function. Both apply
and call
invoke the function.
bind()
also allows for additional arguments to be perpended to the args array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
I faced the same issues. To solve this, I used export PYTHONPATH="$PWD"
. However, in this case, you will need to modify imports in your Scripts
dir depending on the below:
Case 1: If you are in the user_management
dir, your scripts
should use this style from Modules import LDAPManager
to import module.
Case 2: If you are out of the user_management
1 level like main
, your scripts
should use this style from user_management.Modules import LDAPManager
to import modules.
Easiest way to install Apache + php7 tested using Debian 10:
apt-get update -y
apt-get install apache2 php7.0 libapache2-mod-php -y
sudo service apache2 restart
// not familiar with C#, but C#'s equivalent of PHP's:
$count = count($productIds); // where $productIds is the array you also use in IN (...)
SELECT IF ((SELECT COUNT(*) FROM Products WHERE ProductID IN (1, 10, 100)) = $count, 1, 0)
Have you tried getFilesDir().getAbsolutePath()
?
Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.
The data would probably have been posted originally from a web form looking a bit like this (but probably much more complicated):
<form action="http://example.com" method="post">
User login <input name="user[login]" /><br />
User password <input name="user[password]" /><br />
<input type="submit" />
</form>
If the method were "get" instead of "post", clicking the submit button would take you to a URL looking a bit like this:
http://example.com/?user%5Blogin%5D=username&user%5Bpassword%5D=123456
or:
http://example.com/?user[login]=username&user[password]=123456
The web server on the other end will likely take the user[login]
and user[password]
parameters, and make them into a user
object with login
and password
fields containing those values.
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
I finally understood what was going on.
When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.
When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.
My test now works just fine.
In cpp, you need to pay special attention to string types when using execvp
:
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());
// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
string arg;
cin >> arg;
if (arg.empty()) {
argv[arg_i] = nullptr;
break;
} else {
argv[arg_i] = strdup(arg.c_str());
}
++arg_i;
}
// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
// Print error if command not found
cerr << "command '" << command << "' not found\n";
}
Reference: execlp?execvp?????
Replace the table name and use the below query to get the data on your local environment:
aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT" --endpoint-url http://localhost:8000
Replace the table name and remove the endpoint url to get the data on production environment
aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT"
=
, the indent command can take motions. So, gg
to get the start of the file, =
to indent, G
to the end of the file, gg=G
.
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
One is essentially a toy, designed for writing small pieces of code, and traditionally used and abused by inexperienced programmers.
The other is a scripting language for web browsers.
XSD files are used to validate that XML files conform to a certain format.
In that respect they are similar to DTDs that existed before them.
The main difference between XSD and DTD is that XSD is written in XML and is considered easier to read and understand.
$("#mydropdown option").length
Or if you already got a reference to it,
$(myDropdown).find("option").length
You can use native win command:
WMIC /node:ComputerName process call create “cmd.exe /c start.exe”
The WMIC is part of wbem win folder: C:\Windows\System32\wbem
It's pretty strange for FB not to be loaded in your javascript if you have the script tag there correctly. Check that you don't have any javascript blockers, ad blockers, tracking blockers etc installed in your browser that are neutralizing your FB Connect code.
Note: If you have written any crash handler yourself, then the core might not get generated. So search for code with something on the line:
signal(SIGSEGV, <handler> );
so the SIGSEGV will be handled by handler and you will not get the core dump.
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
Take a very common pattern. Class Factory makes Widgets. The Factory class needs to muck about with the internals, because, it is the Factory. Both are implemented in the same file and are, by design and desire and nature, tightly coupled classes -- in fact, Widget is really just an output type from factory.
In C++, make the Factory a friend of Widget class.
In C#, what can we do? The only decent solution that has occurred to me is to invent an interface, IWidget, which only exposes the public methods, and have the Factory return IWidget interfaces.
This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.
Your code was compiled with Java 8.
Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.
Hope this helps...
Another way to get a subset of columns from your DataFrame, assuming you want all the rows, would be to do:
data[['a','b']]
and data[['c','d','e']]
If you want to use numerical column indexes you can do:
data[data.columns[:2]]
and data[data.columns[2:]]
You need to normalise the version strings so they can be compared. Something like
import java.util.regex.Pattern;
public class Main {
public static void main(String... args) {
compare("1.0", "1.1");
compare("1.0.1", "1.1");
compare("1.9", "1.10");
compare("1.a", "1.9");
}
private static void compare(String v1, String v2) {
String s1 = normalisedVersion(v1);
String s2 = normalisedVersion(v2);
int cmp = s1.compareTo(s2);
String cmpStr = cmp < 0 ? "<" : cmp > 0 ? ">" : "==";
System.out.printf("'%s' %s '%s'%n", v1, cmpStr, v2);
}
public static String normalisedVersion(String version) {
return normalisedVersion(version, ".", 4);
}
public static String normalisedVersion(String version, String sep, int maxWidth) {
String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
StringBuilder sb = new StringBuilder();
for (String s : split) {
sb.append(String.format("%" + maxWidth + 's', s));
}
return sb.toString();
}
}
Prints
'1.0' < '1.1' '1.0.1' < '1.1' '1.9' < '1.10' '1.a' > '1.9'
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
In Java 8 you can skip server name checking with the following code:
HttpsURLConnection.setDefaultHostnameVerifier ((hostname, session) -> true);
However this should be used only in development!
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
motivated by previous contributors, this is an example of three axes.
import matplotlib.pyplot as plt
x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]
x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]
x_values3=[150,200,250,300,350]
y_values3=[-10,-20,-30,-40,-50]
fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)
ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")
ax2.scatter(x_values2, y_values2, color="C1")
ax2.set_xlabel('x label 2', color="C1")
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 36))
ax2.tick_params(axis='x', colors="C1")
ax2.set_ylabel('y label 2', color="C1")
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.tick_params(axis='y', colors="C1")
ax3.plot(x_values3, y_values3, color="C2")
ax3.set_xlabel('x label 3', color='C2')
ax3.xaxis.set_label_position('bottom')
ax3.spines['bottom'].set_position(('outward', 72))
ax3.tick_params(axis='x', colors='C2')
ax3.set_ylabel('y label 3', color='C2')
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position('right')
ax3.spines['right'].set_position(('outward', 36))
ax3.tick_params(axis='y', colors='C2')
plt.show()
In case someone wants to do this in the programming way! Do the following: Update the color file in your values folder with this.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="transparent">#00ffffff</color> <!--This is the transparency line-->
</resources>
then call the transparency programitically
your_textview.setBackgroundResource(R.color.transparent);
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
We can use params
, new feature of the UI-Router:
API Reference / ui.router.state / $stateProvider
params
A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.
See the part: "...or defines additional non-url parameters..."
So the state def would be:
$stateProvider
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
params: { hiddenOne: null, }
})
Few examples form the doc mentioned above:
// define a parameter's default value
params: {
param1: { value: "defaultValue" }
}
// shorthand default values
params: {
param1: "defaultValue",
param2: "param2Default"
}
// param will be array []
params: {
param1: { array: true }
}
// handling the default value in url:
params: {
param1: {
value: "defaultId",
squash: true
} }
// squash "defaultValue" to "~"
params: {
param1: {
value: "defaultValue",
squash: "~"
} }
EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info
Here is an example of a state definition:
$stateProvider
.state('home', {
url: "/home",
params : { veryLongParamHome: null, },
...
})
.state('parent', {
url: "/parent",
params : { veryLongParamParent: null, },
...
})
.state('parent.child', {
url: "/child",
params : { veryLongParamChild: null, },
...
})
This could be a call using ui-sref:
<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
})">home</a>
<a ui-sref="parent({
veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
})">parent</a>
<a ui-sref="parent.child({
veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',
veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
})">parent.child</a>
Check the example here
If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()
in such cases getContext() is safe
then the code for starting the activity will be slightly changed like,
Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);
Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class GetJsonFromUrl {
String url = null;
public GetJsonFromUrl(String url) {
this.url = url;
}
public String GetJsonData() {
try {
URL Url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
line = sb.toString();
connection.disconnect();
is.close();
sb.delete(0, sb.length());
return line;
} catch (Exception e) {
return null;
}
}
}
and this class use for post data
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by user on 11/2/16.
*/
public class sendDataToServer {
public String postdata(String requestURL,HashMap<String,String> postDataParams){
try {
String response = "";
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
Log.d("test", response);
return response;
}catch (Exception e){
return e.toString();
}
}
public String postjson(String url,String json){
try {
URL obj = new URL(url);
HttpURLConnection con= (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
String urlParameters = ""+json;
// Send post request
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}catch(Exception e){
return e.toString();
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
/* public String postdata(String url) {
}*/
}
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
This I have found on the internet.
You can do $this->getRequest()->query->all();
to get all GET params and $this->getRequest()->request->all();
to get all POST params.
So in your case:
$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];
For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html
Not exactly "exporting," but you can select the rows (or Ctrl-A to select all of them) in the grid you'd like to export, and then copy with Ctrl-C.
The default is tab-delimited. You can paste that into Excel or some other editor and manipulate the delimiters all you like.
Also, if you use Ctrl-Shift-C instead of Ctrl-C, you'll also copy the column headers.
Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):
var ListenerTracker=new function(){
var is_active=false;
// listener tracking datas
var _elements_ =[];
var _listeners_ =[];
this.init=function(){
if(!is_active){//avoid duplicate call
intercep_events_listeners();
}
is_active=true;
};
// register individual element an returns its corresponding listeners
var register_element=function(element){
if(_elements_.indexOf(element)==-1){
// NB : split by useCapture to make listener easier to find when removing
var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
_elements_.push(element);
_listeners_.push(elt_listeners);
}
return _listeners_[_elements_.indexOf(element)];
};
var intercep_events_listeners = function(){
// backup overrided methods
var _super_={
"addEventListener" : HTMLElement.prototype.addEventListener,
"removeEventListener" : HTMLElement.prototype.removeEventListener
};
Element.prototype["addEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["addEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])listeners[useCapture][type]=[];
listeners[useCapture][type].push(listener);
};
Element.prototype["removeEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["removeEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])return;
var lid = listeners[useCapture][type].indexOf(listener);
if(lid>-1)listeners[useCapture][type].splice(lid,1);
};
Element.prototype["getEventListeners"]=function(type){
var listeners=register_element(this);
// convert to listener datas list
var result=[];
for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
if(typeof(type)=="string"){// filtered by type
if(list[type]){
for(var id in list[type]){
result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
}
}
}else{// all
for(var _type in list){
for(var id in list[_type]){
result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
}
}
}
}
return result;
};
};
}();
ListenerTracker.init();
It's the other way around: =
and ==
are for string comparisons, -eq
is for numeric ones. -eq
is in the same family as -lt
, -le
, -gt
, -ge
, and -ne
, if that helps you remember which is which.
==
is a bash-ism, by the way. It's better to use the POSIX =
. In bash the two are equivalent, and in plain sh =
is the only one guaranteed to work.
$ a=foo
$ [ "$a" = foo ]; echo "$?" # POSIX sh
0
$ [ "$a" == foo ]; echo "$?" # bash specific
0
$ [ "$a" -eq foo ]; echo "$?" # wrong
-bash: [: foo: integer expression expected
2
(Side note: Quote those variable expansions! Do not leave out the double quotes above.)
If you're writing a #!/bin/bash
script then I recommend using [[
instead. The doubled form has more features, more natural syntax, and fewer gotchas that will trip you up. Double quotes are no longer required around $a
, for one:
$ [[ $a == foo ]]; echo "$?" # bash specific
0
See also:
Using your code with some random data, this would work:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(10):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
axs[i].set_title(str(250+i))
The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).
Just a tiny update with built-in wireless debugging in Android 11:
adb pair [IP_ADDRESS]:[PORT]
and type pairing code.You could do it like this:
iterations = 10
variables = 2
output <- matrix(ncol=variables, nrow=iterations)
for(i in 1:iterations){
output[i,] <- runif(2)
}
output
and then turn it into a data.frame
output <- data.frame(output)
class(output)
what this does:
Your equals2()
method always will return the same as equals()
!!
Your code with my comments:
public boolean equals2(Object object2) { // equals2 method
if(a.equals(object2)) { // if equals() method returns true
return true; // return true
}
else return false; // if equals() method returns false, also return false
}
no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.
The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of asp.net.
edit:
here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:
public ActionResult GetData()
{
var data = new { Name="kevin", Age=40 };
return Json(data, JsonRequestBehavior.AllowGet);
}
This return data could be called via JQuery as an ajax call thusly:
$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });
I have 2.0 and found the above to help; however, the selecting of a static did not highlight the cell for some reason. I followed these steps:
Now your column headers should repeat on each page.
Set the environment variable in the script command:
...
"scripts": {
"start": "node app.js",
"test": "NODE_ENV=test mocha --reporter spec"
},
...
Then use process.env.NODE_ENV
in your app.
Note: This is for Mac & Linux only. For Windows refer to the comments.
Generally speaking, for boolean
or bit
data types, you would use 0
or 1
like so:
UPDATE tbl SET bitCol = 1 WHERE bitCol = 0
See also:
To quote the documentation:
Key words and unquoted identifiers are case insensitive. Therefore:
UPDATE MY_TABLE SET A = 5;
can equivalently be written as:
uPDaTE my_TabLE SeT a = 5;
You could also write it using quoted identifiers:
UPDATE "my_table" SET "a" = 5;
Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO
, foo
, and "foo"
are considered the same by PostgreSQL, but "Foo"
and "FOO"
are different from these three and each other.
If you want to write portable applications you are advised to always quote a particular name or never quote it.
These steps work for me:
You can use ExpandoObject Class
which is in System.Dynamic
namespace.
dynamic MyDynamic = new ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.SomeProperty = SomeValue
MyDynamic.number = 10;
MyDynamic.Increment = (Action)(() => { MyDynamic.number++; });
More Info can be found at ExpandoObject MSDN
I didn't see the C# anwer to this question here. The trick is to set the BrowserExecutableLocation property on a FirefoxOptions instance, and pass that into the driver constructor:
var opt = new FirefoxOptions
{
BrowserExecutableLocation = @"c:\program files\mozilla firefox\firefox.exe"
};
var driver = new FirefoxDriver(opt);