You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
You could try doing it through R:
For Stata <= 15 you can use the haven package to read the dataset and then you simply write it to external CSV file:
library(haven)
yourData = read_dta("path/to/file")
write.csv(yourData, file = "yourStataFile.csv")
Alternatively, visit the link pointed by huntaub in a comment below.
For Stata <= 12 datasets foreign package can also be used
library(foreign)
yourData <- read.dta("yourStataFile.dta")
You missed the closing tag for the input fields, and you can choose any one of the events, ex: onload, onclick etc.
(a) Onload event:
<script type="text/javascript">
$(document).ready(function(){
$('#frm1').submit();
});
</script>
(b) Onclick Event:
<form name="frm1" id="frm1" action="../somePage" method="post">
Please Waite...
<input type="hidden" name="uname" id="uname" value=<?php echo $uname;?> />
<input type="hidden" name="price" id="price" value=<?php echo $price;?> />
<input type="text" name="submit" id="submit" value="submit">
</form>
<script type="text/javascript">
$('#submit').click(function(){
$('#frm1').submit();
});
</script>
I had the same issue after adding the library icepick to my gradle dependencies. After removing the dependencie, everything seems to be fine. As soon as i know why this issue appeared i'll write here again
Mockito is not a DI framework and even DI frameworks encourage constructor injections over field injections.
So you just declare a constructor to set dependencies of the class under test :
@Mock
private SomeService serviceMock;
private Demo demo;
/* ... */
@BeforeEach
public void beforeEach(){
demo = new Demo(serviceMock);
}
Using Mockito spy
for the general case is a terrible advise. It makes the test class brittle, not straight and error prone : What is really mocked ? What is really tested ?
@InjectMocks
and @Spy
also hurts the overall design since it encourages bloated classes and mixed responsibilities in the classes.
Please read the spy()
javadoc before using that blindly (emphasis is not mine) :
Creates a spy of the real object. The spy calls real methods unless they are stubbed. Real spies should be used carefully and occasionally, for example when dealing with legacy code.
As usual you are going to read the
partial mock warning
: Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.
Check for the value of the parameter:
// .NET < 4.0
if (string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]))
{
// not there!
}
// .NET >= 4.0
if (string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"]))
{
// not there!
}
If it does not exist, the value will be null
, if it does exist, but has no value set it will be an empty string.
I believe the above will suit your needs better than just a test for null
, as an empty string is just as bad for your specific situation.
Push annotated tags, keep lightweight local
man git-tag
says:
Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.
And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:
annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.
Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.
git describe
without command line options only sees annotated tagsInternals differences
both lightweight and annotated tags are a file under .git/refs/tags
that contains a SHA-1
for lightweight tags, the SHA-1 points directly to a commit:
git tag light
cat .git/refs/tags/light
prints the same as the HEAD's SHA-1.
So no wonder they cannot contain any other metadata.
annotated tags point to a tag object in the object database.
git tag -as -m msg annot
cat .git/refs/tags/annot
contains the SHA of the annotated tag object:
c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
and then we can get its content with:
git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
sample output:
object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
type commit
tag annot
tagger Ciro Santilli <[email protected]> 1411478848 +0200
msg
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
<YOUR PGP SIGNATURE>
-----END PGP SIGNAT
And this is how it contains extra metadata. As we can see from the output, the metadata fields are:
A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?
Bonuses
Determine if a tag is annotated:
git cat-file -t tag
Outputs
commit
for lightweight, since there is no tag object, it points directly to the committag
for annotated, since there is a tag object in that caseList only lightweight tags: How can I list all lightweight tags?
Above answers give you a hardcoded path solution. This is bad on so many levels (java version change, OS change, etc).
Cleaner solution is to add:
JAVA_HOME = $(shell dirname $$(readlink -f $$(which java))|sed 's^jre/bin^^')
near the top of your makefile, then add:
-I$(JAVA_HOME)/include
To your include flags.
I am posting this because I ran into the same problem and spent too much time googling for wrong answers (I am building an app on multiple platforms so the build environment needs to be transportable).
I know this doesn't help you, but I have to say that this is one of the reasons I jumped from XAMPP to WampServer. WampServer lets you install multiple versions of PHP, Apache and/or MySQL, and switch between them all via a menu option.
See here for a CodePen that demonstrates the difference in how ng-if/ng-show work, DOM-wise.
@markovuksanovic has answered the question well. But I'd come at it from another perspective: I'd always use ng-if
and get those elements out of DOM, unless:
$watch
-es on your elements to remain active while they're invisible. Forms might be a good case for this, if you want to be able to check validity on inputs that aren't currently visible, in order to determine whether the whole form is valid.Angular is written really well. It's fast, considering what it does. But what it does is a whole bunch of magic that makes hard things (like 2-way data-binding) look trivially easy. Making all those things look easy entails some performance overhead. You might be shocked to realize how many hundreds or thousands of times a setter function gets evaluated during the $digest
cycle on a hunk of DOM that nobody's even looking at. And then you realize you've got dozens or hundreds of invisible elements all doing the same thing...
Desktops may indeed be powerful enough to render most JS execution-speed issues moot. But if you're developing for mobile, using ng-if whenever humanly possible should be a no-brainer. JS speed still matters on mobile processors. Using ng-if is a very easy way to get potentially-significant optimization at very, very low cost.
I came here because I was trying to do the same thing; I knew I had dupes in the source data but only wanted to update the target data and not add the dupes.
I think a MERGE works great here because you can UPDATE or DELETE things that are different and INSERT things that are missing.
I ended up doing this and it worked great. I use SSIS to loop through Excel files and load them into a "RAW" SQL table with dupes and all. Then I run a MERGE to merge the "raw" table with the production table. Then I TRUNCATE the "raw" table and move to the next Excel file.
Lets us assume you have a numpy
array that has contains the value from 0 all the way up to 20 and you want to replace numbers greater than 10 with 0
import numpy as np
my_arr = np.arange(0,21) # creates an array
my_arr[my_arr > 10] = 0 # modifies the value
_x000D_
Note this will however modify the original array to avoid overwriting the original array try using
arr.copy()
to create a new detached copy of the original array and modify that instead.
import numpy as np
my_arr = np.arange(0,21)
my_arr_copy = my_arr.copy() # creates copy of the orignal array
my_arr_copy[my_arr_copy > 10] = 0
_x000D_
In my case, I was creating an object declared and initialized together. I just initialized in the constructor or what you can initialize the object when required.
I found the GNU Introduction to PDF to be helpful in understanding the structure. It includes an easily readable example PDF file that they describe in complete detail.
Other helpful links:
var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function
var input_date="2015/04/22 11:12 AM";
var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime = new Date(Date.parse(input_date));
if (inputDateTime <= currentDateTime){
//Do something...
}
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0'+hours : hours ;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours+":"+minutes+ ' ' + ampm;
return date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
(date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
date.getDate()) + " " + strTime;
}
write that on your Command Prompt:
set Path=%path%
Replace %path% by the Path of your Python Folder Example:
set Path=C:/Python27
Now, you don't need to use FormBuilder
and all this complicated valiation angular stuff. I put more details from this (Angular 2.0.8 - 3march2016):
https://github.com/angular/angular/commit/38cb526
Example from repo :
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
I test it and it works :) - here is my code:
<form (ngSubmit)="onSubmit(room)" #roomForm='ngForm' >
...
<input
id='room-capacity'
type="text"
class="form-control"
[(ngModel)]='room.capacity'
ngControl="capacity"
required
pattern="[0-9]+"
#capacity='ngForm'>
Validation is ONLY on server side. If something is wrong then server return error code e.g HTTP 400 and following json object in response body (as example):
this.err = {
"capacity" : "too_small"
"filed_name" : "error_name",
"field2_name" : "other_error_name",
...
}
In html template I use separate tag (div/span/small etc.)
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
If in 'capacity' is error then tag with msg translation will be visible. This approach have following advantages:
<small>
tag)Of course sometimes I make exception if validation is needed on frontend side (e.g. retypePassword
field on registration is never send to server).
This is what works for me:
pip --proxy proxy url:port command package
You can separate list entities by a comma like this:
//phones is a list of PhoneModel
var phoneNumbers = phones.Select(m => m.PhoneNumber)
.Aggregate(new StringBuilder(),
(current, next) => current.Append(next).Append(" , ")).ToString();
// Remove the trailing comma and space
if (phoneNumbers.Length > 1)
phoneNumbers = phoneNumbers.Remove(phoneNumbers.Length - 2, 2);
Try like this...
<script>
function getPaging(str) {
$("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
</script>
<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>
or unobtrusively
$(function() {
$("li").on("click",function() {
showLoader();
$("#loading-content").load("dataSearch.php?"+this.id, hideLoader);
});
});
using just
<li id="1">1</li>
<li id="2">2</li>
==
and !=
do not take into account the data type of the variables you compare. So these would all return true:
'0' == 0
false == 0
NULL == false
===
and !==
do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:
'0' === 0
false === 0
NULL === false
You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos()
:
// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false); // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned
if you use Bootstrap 2.2.1 then maybe is this what you are looking for.
Sample file index.html
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title></title>_x000D_
<link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
<link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
<menu>_x000D_
<div class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="/">Application name</a>_x000D_
</div>_x000D_
<div class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="/">Home</a></li>_x000D_
<li><a href="/Home/About">About</a></li>_x000D_
<li><a href="/Home/Contact">Contact</a></li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
<li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
</ul>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</menu>_x000D_
_x000D_
<nav>_x000D_
<div class="col-md-2">_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
</div>_x000D_
_x000D_
</nav>_x000D_
<content>_x000D_
<div class="col-md-10">_x000D_
_x000D_
<h2>About.</h2>_x000D_
<h3>Your application description page.</h3>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<hr />_x000D_
</div>_x000D_
</content>_x000D_
_x000D_
<footer>_x000D_
<div class="navbar navbar-default navbar-fixed-bottom">_x000D_
<div class="container" style="font-size: .8em">_x000D_
<p class="navbar-text">_x000D_
© Some info_x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
</footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
body {_x000D_
padding-bottom: 70px;_x000D_
padding-top: 70px;_x000D_
}
_x000D_
no such table found is mainly when you have not opened the SQLiteOpenHelper
class with getwritabledata()
and before this you also have to call make constructor with databasename & version.
And OnUpgrade
is called whenever there is upgrade value in version number given in SQLiteOpenHelper
class.
Below is the code snippet (No such column found may be because of spell in column name):
public class database_db {
entry_data endb;
String file_name="Record.db";
SQLiteDatabase sq;
public database_db(Context c)
{
endb=new entry_data(c, file_name, null, 8);
}
public database_db open()
{
sq=endb.getWritableDatabase();
return this;
}
public Cursor getdata(String table)
{
return sq.query(table, null, null, null, null, null, null);
}
public long insert_data(String table,ContentValues value)
{
return sq.insert(table, null, value);
}
public void close()
{
sq.close();
}
public void delete(String table)
{
sq.delete(table,null,null);
}
}
class entry_data extends SQLiteOpenHelper
{
public entry_data(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase sqdb) {
// TODO Auto-generated method stub
sqdb.execSQL("CREATE TABLE IF NOT EXISTS 'YOUR_TABLE_NAME'(Column_1 text not null,Column_2 text not null);");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
}
This is an expansion of one of the solutions provided in Jakub's answer
I was faced with a situation where the commits I needed to roll back were somewhat complex, with several of the commits being merge commits, and I needed to avoid rewriting history. I was not able to use a series of git revert
commands because I eventually ran into conflicts between the reversion changes being added. I ended up using the following steps.
First, check out the contents of the target commit while leaving HEAD at the tip of the branch:
$ git checkout -f <target-commit> -- .
(The -- makes sure <target-commit>
is interpreted as a commit rather than a file; the . refers to the current directory.)
Then, determine what files were added in the commits being rolled back, and thus need to be deleted:
$ git diff --name-status --cached <target-commit>
Files that were added should show up with an "A" at the beginning of the line, and there should be no other differences. Now, if any files need to be removed, stage these files for removal:
$ git rm <filespec>[ <filespec> ...]
Finally, commit the reversion:
$ git commit -m 'revert to <target-commit>'
If desired, make sure that we're back to the desired state:
$git diff <target-commit> <current-commit>
There should be no differences.
The simplest way to log to stdout:
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
Yes I know it is over half a year later and a tad late, BUT
row.names(df) <- NULL
does work. For me at least :-)
And if you have important information in row.names like dates for example, what I do is just :
df$Dates <- as.Date(row.names(df))
This will add a new column on the end but if you want it at the beginning of your data frame
df <- df[,c(7,1,2,3,4,5,6,...)]
Hope this helps those from Google :)
If any of your .env
variables contains white space, make sure you wrap them in double-quotes. For example:
SITE_NAME="My website"
Don't forget to clear your cache before testing:
php artisan config:cache
php artisan config:clear
Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...
list = [1,2,3,4,5]
deleteList = []
processNo = 0
for item in list:
if condition:
print item
deleteList.insert(0, processNo)
processNo += 1
if len(deleteList) > 0:
for item in deleteList:
del list[item]
It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.
Simply go to project Explorer and change your View
from Android to project from drop Down and you are good to go.There you can simply create folder like we do in Eclipse.
And in android project view it is hidden but when you switch to project. You can create folder like drawable-hdpi,drawable-xhdpi
.
If you write it as the following in SQL server then there would be no danger of wiping the database table unless all of the values in that table happen to actually be between those values:
DELETE FROM [dbo].[TableName] WHERE [TableName].[IdField] BETWEEN 79 AND 296
The best way is:
public interface IDeepClonable<T> where T : class
{
T DeepClone();
}
public class MyObj : IDeepClonable<MyObj>
{
public MyObj Clone()
{
var myObj = new MyObj();
myObj._field1 = _field1;//value type
myObj._field2 = _field2;//value type
myObj._field3 = _field3;//value type
if (_child != null)
{
myObj._child = _child.DeepClone(); //reference type .DeepClone() that does the same
}
int len = _array.Length;
myObj._array = new MyObj[len]; // array / collection
for (int i = 0; i < len; i++)
{
myObj._array[i] = _array[i];
}
return myObj;
}
private bool _field1;
public bool Field1
{
get { return _field1; }
set { _field1 = value; }
}
private int _field2;
public int Property2
{
get { return _field2; }
set { _field2 = value; }
}
private string _field3;
public string Property3
{
get { return _field3; }
set { _field3 = value; }
}
private MyObj _child;
private MyObj Child
{
get { return _child; }
set { _child = value; }
}
private MyObj[] _array = new MyObj[4];
}
Check your short_open_tag setting (use <?php phpinfo() ?>
to see its current setting).
Just adding that using the first approach it can be done as -
pd.DataFrame(list(map(list, zip(lst1,lst2,lst3))))
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Thanks guys the proxy pattern really helped.....Actually I wanted to call a global function foo.. In certain pages i need do to some checks. So I did the following.
//Saving the original func
var org_foo = window.foo;
//Assigning proxy fucnc
window.foo = function(args){
//Performing checks
if(checkCondition(args)){
//Calling original funcs
org_foo(args);
}
};
Thnx this really helped me out
You could declare a table variable (Declaring a variable of type table):
declare @MonthsSale table(monthnr int)
insert into @MonthsSale (monthnr) values (1)
insert into @MonthsSale (monthnr) values (2)
....
You can add extra columns as you like:
declare @MonthsSale table(monthnr int, totalsales tinyint)
You can update the table variable like any other table:
update m
set m.TotalSales = sum(s.SalesValue)
from @MonthsSale m
left join Sales s on month(s.SalesDt) = m.MonthNr
Using base graphics, the standard way to do this is to use axes=FALSE, then create your own axes using Axis (or axis). For example,
x <- 1:20
y <- runif(20)
plot(x, y, axes=FALSE, frame.plot=TRUE)
Axis(side=1, labels=FALSE)
Axis(side=2, labels=FALSE)
The lattice equivalent is
library(lattice)
xyplot(y ~ x, scales=list(alternating=0))
I'll offer an oddball alternative. Sometimes it's easier to use different encoding, especially if you're dealing with a variety of systems that don't all handle the details of URL encoding the same way. This isn't the most mainstream approach but can come in handy in certain situations.
Rather than URL-encoding the data, you can base64-encode it. The benefit of this is the encoded data is very generic, consisting only of alpha characters and sometimes trailing =
's. Example:
JSON array-of-strings:
["option", "Fred's dog", "Bill & Trudy", "param=3"]
That data, URL-encoded as the data
param:
"data=%5B%27option%27%2C+%22Fred%27s+dog%22%2C+%27Bill+%26+Trudy%27%2C+%27param%3D3%27%5D"
Same, base64-encoded:
"data=WyJvcHRpb24iLCAiRnJlZCdzIGRvZyIsICJCaWxsICYgVHJ1ZHkiLCAicGFyYW09MyJd"
The base64 approach can be a bit shorter, but more importantly it's simpler. I often have problems moving URL-encoded data between cURL, web browsers and other clients, usually due to quotes, embedded %
signs and so on. Base64 is very neutral because it doesn't use special characters.
Normal array
can serve as a dictionary data structure. In general it has multipurpose usage: array, list (vector), hash table, dictionary, collection, stack, queue etc.
$names = [
'bob' => 27,
'billy' => 43,
'sam' => 76,
];
$names['bob'];
And because of wide design it gains no full benefits of specific data structure. You can implement your own dictionary by extending an ArrayObject
or you can use SplObjectStorage
class which is map (dictionary) implementation allowing objects to be assigned as keys.
For Mac Terminal
cd .. # one up
cd ../ # two up
cd # home directory
cd / # root directory
cd "yaya-13" # use quotes if the file name contains punctuation or spaces
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
To revert to upstream/master do:
git checkout upstream/master -- myfile.txt
Consider that the files you need to delete have an extension txt
and is located in the location D:\My Folder
, then you could use the below code inside the bat file.
cd "D:\My Folder"
DEL *.txt
Try the correct constructor http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String)
You can directly instanciate the BigDecimal with the String ;)
Example:
BigDecimal bigDecimalValue= new BigDecimal("0.5");
Without using an overlay, you can use pointer-events: none
on the div
in CSS, but this does not work in IE or Opera.
div.disabled
{
pointer-events: none;
/* for "disabled" effect */
opacity: 0.5;
background: #CCC;
}
Wolfram has a closed form solution for fitting an exponential. They also have similar solutions for fitting a logarithmic and power law.
I found this to work better than scipy's curve_fit. Especially when you don't have data "near zero". Here is an example:
import numpy as np
import matplotlib.pyplot as plt
# Fit the function y = A * exp(B * x) to the data
# returns (A, B)
# From: https://mathworld.wolfram.com/LeastSquaresFittingExponential.html
def fit_exp(xs, ys):
S_x2_y = 0.0
S_y_lny = 0.0
S_x_y = 0.0
S_x_y_lny = 0.0
S_y = 0.0
for (x,y) in zip(xs, ys):
S_x2_y += x * x * y
S_y_lny += y * np.log(y)
S_x_y += x * y
S_x_y_lny += x * y * np.log(y)
S_y += y
#end
a = (S_x2_y * S_y_lny - S_x_y * S_x_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
b = (S_y * S_x_y_lny - S_x_y * S_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
return (np.exp(a), b)
xs = [33, 34, 35, 36, 37, 38, 39, 40, 41, 42]
ys = [3187, 3545, 4045, 4447, 4872, 5660, 5983, 6254, 6681, 7206]
(A, B) = fit_exp(xs, ys)
plt.figure()
plt.plot(xs, ys, 'o-', label='Raw Data')
plt.plot(xs, [A * np.exp(B *x) for x in xs], 'o-', label='Fit')
plt.title('Exponential Fit Test')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
For MySQL, MariaDB
ALTER TABLE [table name] MODIFY COLUMN [column name] [data type] NULL
Use MODIFY COLUMN
instead of ALTER COLUMN
.
see event.data
commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
var data = event.data;
alert(data.id);
alert(data.name);
});
If your data is initialized before binding the event, then simply capture those variables in a closure.
// assuming id and name are defined in this scope
commentBtn.click(function() {
alert(id), alert(name);
});
In Stored procedure, you return the values using OUT
parameter ONLY. As you have defined two variables in your example:
outstaticip OUT VARCHAR2, outcount OUT NUMBER
Just assign the return values to the out parameters i.e. outstaticip
and outcount
and access them back from calling location. What I mean here is: when you call the stored procedure, you will be passing those two variables as well. After the stored procedure call, the variables will be populated with return values.
If you want to have RETURN value
as return from the PL/SQL call, then use FUNCTION
. Please note that in case, you would be able to return only one variable as return variable.
If the command line way of configuring your proxy server doesn't work, you can probably just edit .gitconfig (in the root of your profile, which may hide both in C:\Documents and Settings and on some network drive) and add this:
[http]
proxy = http://username:[email protected]:8080
YMMV though, this only covers the first step of the command line configuration. You may have to edit the system git configuration too and I have no idea where they hid that.
I done it, below code is working for me....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
Button newPage = (Button)v.findViewById(R.id.click);
newPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
and Please make sure that your destination activity should be register in Manifest.xml file,
but in my case all tabs are not shown in HomeActivity, is any solution for that ?
I encountered a similar problem. I am using WinNMP. When I started it, MariaDB was also not running and prompts "Can't connect to MySQL server on '127.0.0.1' (10061) (2003)" whenever I try to connect to a database.
Just want to help. For WinNMP users like me, this worked for me:
msyqld
installer located at "C:\WinNMP\bin\MariaDB\bin"
.Hope this helps someone! :D
function setjdk() {
if [ $# -ne 0 ]; then
removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin'
if [ -n "${JAVA_HOME+x}" ]; then
removeFromPath $JAVA_HOME
fi
export JAVA_HOME=`/usr/libexec/java_home -v $@`
export PATH=$JAVA_HOME/bin:$PATH
fi
}
put this in your ~/.profile and use it in your terminal like so setjdk 1.8
, setjdk 1.7
, setjdk 9
etc etc...
If you don't have removeFromPath
then it is:
function removeFromPath() {
export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
}
using System.Windows.Forms;
...
MessageBox.Show("Hello World!");
It is nothing you can do in the client side.
I added @CrossOrigin
in the controller in the server side and it works.
@RestController
@CrossOrigin(origins = "*")
public class MyController
Please refer to docs.
Lin
Try and see if this works:
OK, I've found it. This is probably the cleanest and easiest solution out there and does not rely on JavaScript being turned on.
@-moz-document url-prefix() {
h1 {
color: red;
}
}
_x000D_
<h1>This should be red in FF</h1>
_x000D_
It's based on yet another Mozilla specific CSS extension. There's a whole list for these CSS extensions right here: Mozilla CSS Extensions.
This worked for me using Select2 v4.0.3
//Initialize Select2
jQuery('.js-select').select2();
// Make Select2 respect tab focus
function select2Focus(){
jQuery(window).keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9 && jQuery('.select2-search__field:focus').length) {
jQuery('.js-select').select2('open');
}
});
}
select2Focus();
Fork of Irvin Dominin's demo: http://jsfiddle.net/163cwdrw/
What is wrong with List.Find ??
I think we need more information on what you've done, and why it fails, before we can provide truly helpful answers.
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
I think the short answer is "because it is of zero usefulness". To call an interface method, you need an instance of the type. From instance methods you can call any static methods you want to.
git pull origin master
this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.
From Wikipedia:
The HTTP response status code 302 Found is the most common way of performing a redirection. It is an example of industrial practice contradicting the standard.
This will be helpful for the right bottom rounded button
HTML :
<a class="fixedButton" href>
<div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
</a>
CSS:
.fixedButton{
position: fixed;
bottom: 0px;
right: 0px;
padding: 20px;
}
.roundedFixedBtn{
height: 60px;
line-height: 80px;
width: 60px;
font-size: 2em;
font-weight: bold;
border-radius: 50%;
background-color: #4CAF50;
color: white;
text-align: center;
cursor: pointer;
}
Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/
Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.
var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.5472,12.282715),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
I am not experienced at all so feel free to correct things. However, I tried all these answers, but always had a problem in some screen. So I tried the following that worked for me and looks as I want it in almost all screens with the exception of mobile.
<div class="wrapper">
<div id="Section-Title">
<div id="h2"> YOUR TITLE
<div id="line"><hr></div>
</div>
</div>
</div>
CSS:
.wrapper{
background:#fff;
max-width:100%;
margin:20px auto;
padding:50px 5%;}
#Section-Title{
margin: 2% auto;
width:98%;
overflow: hidden;}
#h2{
float:left;
width:100%;
position:relative;
z-index:1;
font-family:Arial, Helvetica, sans-serif;
font-size:1.5vw;}
#h2 #line {
display:inline-block;
float:right;
margin:auto;
margin-left:10px;
width:90%;
position:absolute;
top:-5%;}
#Section-Title:after{content:""; display:block; clear:both; }
.wrapper:after{content:""; display:block; clear:both; }
You only need to parse String values using Double
String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);
This search engine was made to solve exactly the kind of problem you're having: http://symbolhound.com/
I am the developer of SymbolHound.
Creation of DB Link
CREATE DATABASE LINK dblinkname
CONNECT TO $usename
IDENTIFIED BY $password
USING '$sid';
(Note: sid is being passed between single quotes above. )
Example Queries for above DB Link
select * from tableA@dblinkname;
insert into tableA(select * from tableA@dblinkname);
The algorithm that Git uses when calculating diff's to be reverted requires that
The definition of "adjacent" is based on the default number of lines from a context diff, which is 3. So if 'myfile' was constructed like this:
$ cat >myfile <<EOF
line 1
junk
junk
junk
junk
line 2
junk
junk
junk
junk
line 3
EOF
$ git add myfile
$ git commit -m "initial check-in"
1 files changed, 11 insertions(+), 0 deletions(-)
create mode 100644 myfile
$ perl -p -i -e 's/line 2/this is the second line/;' myfile
$ git commit -am "changed line 2 to second line"
[master d6cbb19] changed line 2
1 files changed, 1 insertions(+), 1 deletions(-)
$ perl -p -i -e 's/line 3/this is the third line/;' myfile
$ git commit -am "changed line 3 to third line"
[master dd054fe] changed line 3
1 files changed, 1 insertions(+), 1 deletions(-)
$ git revert d6cbb19
Finished one revert.
[master 2db5c47] Revert "changed line 2"
1 files changed, 1 insertions(+), 1 deletions(-)
Then it all works as expected.
The second answer was very interesting. There is a feature which has not yet been officially released (though it is available in Git v1.7.2-rc2) called Revert Strategy. You can invoke git like this:
git revert --strategy resolve <commit>
and it should do a better job figuring out what you meant. I do not know what the list of available strategies is, nor do I know the definition of any strategy.
Also If you want you result set data in list .please use below LOC:
public List<String> dbselect(String query)
{
List<String> dbdata=new ArrayList<String>();
try {
dbResult=statement.executeQuery(query);
ResultSetMetaData metadata=dbResult.getMetaData();
for(int i=0;i>=metadata.getColumnCount();i++)
{
dbdata.add(dbResult.getString(i));
}
return dbdata;
} catch (SQLException e) {
return null;
}
}
Also OneToOneField
is useful to be used as primary key to avoid key duplication. One may do not have implicit / explicit autofield
models.AutoField(primary_key=True)
but use OneToOneField
as primary key instead (imagine UserProfile
model for example):
user = models.OneToOneField(
User, null=False, primary_key=True, verbose_name='Member profile')
Listview lv = (ListView) findViewById(R.id.previewlist);
final BaseAdapter adapter = new PreviewAdapter(this, name, age);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
View view = null;
String value;
for (int i = 0; i < adapter.getCount(); i++) {
view = adapter.getView(i, view, lv);
Textview et = (TextView) view.findViewById(R.id.passfare);
value=et.getText().toString();
Toast.makeText(getApplicationContext(), value,
Toast.LENGTH_SHORT).show();
}
}
});
Comment as an answer:
if (timetime[0].value)
This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.
Well, this is my final solution for a simple db, for Linux:
# Read this before!
#
# * roles in postgres are users, and can be used also as group of users
# * $ROLE_LOCAL will be the user that access the db for maintenance and
# administration. $ROLE_REMOTE will be the user that access the db from the webapp
# * you have to change '$ROLE_LOCAL', '$ROLE_REMOTE' and '$DB'
# strings with your desired names
# * it's preferable that $ROLE_LOCAL == $DB
#-------------------------------------------------------------------------------
//----------- SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - START ----------//
cd /etc/postgresql/$VERSION/main
sudo cp pg_hba.conf pg_hba.conf_bak
sudo -e pg_hba.conf
# change all `md5` with `scram-sha-256`
# save and exit
//------------ SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - END -----------//
sudo -u postgres psql
# in psql:
create role $ROLE_LOCAL login createdb;
\password $ROLE_LOCAL
create role $ROLE_REMOTE login;
\password $ROLE_REMOTE
create database $DB owner $ROLE_LOCAL encoding "utf8";
\connect $DB $ROLE_LOCAL
# Create all tables and objects, and after that:
\connect $DB postgres
revoke connect on database $DB from public;
revoke all on schema public from public;
revoke all on all tables in schema public from public;
grant connect on database $DB to $ROLE_LOCAL;
grant all on schema public to $ROLE_LOCAL;
grant all on all tables in schema public to $ROLE_LOCAL;
grant all on all sequences in schema public to $ROLE_LOCAL;
grant all on all functions in schema public to $ROLE_LOCAL;
grant connect on database $DB to $ROLE_REMOTE;
grant usage on schema public to $ROLE_REMOTE;
grant select, insert, update, delete on all tables in schema public to $ROLE_REMOTE;
grant usage, select on all sequences in schema public to $ROLE_REMOTE;
grant execute on all functions in schema public to $ROLE_REMOTE;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on tables to $ROLE_LOCAL;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on sequences to $ROLE_LOCAL;
alter default privileges for role $ROLE_LOCAL in schema public
grant all on functions to $ROLE_LOCAL;
alter default privileges for role $ROLE_REMOTE in schema public
grant select, insert, update, delete on tables to $ROLE_REMOTE;
alter default privileges for role $ROLE_REMOTE in schema public
grant usage, select on sequences to $ROLE_REMOTE;
alter default privileges for role $ROLE_REMOTE in schema public
grant execute on functions to $ROLE_REMOTE;
# CTRL+D
Using exit
directly may be tricky as the script may be sourced from other places (e.g. from terminal). I prefer instead using subshell with set -e
(plus errors should go into cerr, not cout) :
set -e
ERRCODE=0
my_command || ERRCODE=$?
test $ERRCODE == 0 ||
(>&2 echo "My command failed ($ERRCODE)"; exit $ERRCODE)
The smallest unit you can work with is a byte (which is of char
type). You can work with bits though by using bitwise operators.
As for integer literals, you can only work with decimal (base 10), octal (base 8) or hexadecimal (base 16) numbers. There are no binary (base 2) literals in C nor C++.
Octal numbers are prefixed with 0
and hexadecimal numbers are prefixed with 0x
. Decimal numbers have no prefix.
In C++0x you'll be able to do what you want by the way via user defined literals.
You shouldn't need to set the value in the attributes parameter. MVC should automatically bind it for you.
@Html.HiddenFor(model => model.title, new { id= "natureOfVisitField" })
As @Kanmani hinted, an easier to interpret implementation may use numpy.flip
, as in the following:
import numpy as np
avgDists = np.array([1, 8, 6, 9, 4])
ids = np.flip(np.argsort(avgDists))
print(ids)
By using the visitor pattern rather than member functions, it is easier to read the order of operations.
Use the ssh2
functions. Anything you'd do via an exec() call can be done directly using these functions, saving you a lot of connections and shell invocations.
I expanded on @BenMcCormicks a bit. His worked for regular strings but not if I had escaped characters or wildcards. Here's what I did
str = "[curl] 6: blah blah 234433 blah blah";
mapObj = {'\\[curl] *': '', '\\d: *': ''};
function replaceAll (str, mapObj) {
var arr = Object.keys(mapObj),
re;
$.each(arr, function (key, value) {
re = new RegExp(value, "g");
str = str.replace(re, function (matched) {
return mapObj[value];
});
});
return str;
}
replaceAll(str, mapObj)
returns "blah blah 234433 blah blah"
This way it will match the key in the mapObj and not the matched word'
$docker-compose build
If there is something new it will be rebuilt.
I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)
<meta name="304workaround" content="2013-10-24 21:17:23">
Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...
Just a delegate that returns a boolean. It is used a lot in filtering lists but can be used wherever you'd like.
List<DateRangeClass> myList = new List<DateRangeClass<GetSomeDateRangeArrayToPopulate);
myList.FindAll(x => (x.StartTime <= minDateToReturn && x.EndTime >= maxDateToReturn):
I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:
Yourhostname here -vvvvvvvvvv
s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state
When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.
The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.
You are clearly sending a certificate. The server is clearly rejecting it.
The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.
Add condition in Click event to restrict the clickable area .
$('#thing').click(function(e) {
if (e.clientX > $(this).offset().left + 90 &&
e.clientY < $(this).offset().top + 10) {
// action when clicking on after-element
// your code here
}
});
First, remove the float
attribute on the inner div
s. Then, put text-align: center
on the main outer div
. And for the inner div
s,
use display: inline-block
. Might also be wise to give them explicit widths too.
<div style="margin: auto 1.5em; display: inline-block;">
<img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
<br/>
Nadia Bjorlin
</div>
you can use substring()
method. ex,
var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);
From @Jon Skeet comment, really the String
value is "null"
. Following code solved it
if (userEmail != null && !userEmail.isEmpty() && !userEmail.equals("null"))
$facebook->api('/'.$facebook_uid)
instead of
$facebook->api('/me')
it works.
For reference purpose, for anyone searching how to change the path via code, I am quoting a useful post by a Delphi programmer from this web page: http://www.tek-tips.com/viewthread.cfm?qid=686382
TonHu (Programmer) 22 Oct 03 17:57 I found where I read the original posting, it's here: http://news.jrsoftware.org/news/innosetup.isx/msg02129....
The excerpt of what you would need is this:
You must specify the string "Environment" in LParam. In Delphi you'd do it this way:
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar('Environment')));
It was suggested by Jordan Russell, http://www.jrsoftware.org, the author of (a.o.) InnoSetup, ("Inno Setup is a free installer for Windows programs. First introduced in 1997, Inno Setup today rivals and even surpasses many commercial installers in feature set and stability.") (I just would like more people to use InnoSetup )
HTH
I had the same problem. Just after enabling Internet Virtualization from BIOS. After that let the system boot and install HAXM once again. Now emulator will run faster than before and HAXM will work. Enjoy!!
For knowing any version of the python library then if your library is installed using the pip then use the following command.
pip show tensorflow
The Output of the above command will be shown below:-
Name: tensorflow
Version: 2.3.0
Summary: TensorFlow is an open source machine learning framework for everyone.
Home-page: https://www.tensorflow.org/
Author: Google Inc.
Author-email: [email protected]
License: Apache 2.0
Location: /usr/local/lib/python3.6/dist-packages
Requires: astunparse, wheel, keras-preprocessing, gast, tensorflow-estimator, opt-einsum, tensorboard, protobuf, absl-py, six, wrapt, termcolor, numpy, grpcio, scipy, google-pasta, h5py
Required-by: fancyimpute
Actually, this is subtler than it looks.
The code above would give the incorrect answer for a lower case character whose code point was above U+FFFF (such as U+1D4C3, MATHEMATICAL SCRIPT SMALL N). String.charAt would return a UTF-16 surrogate pair, which is not a character, but rather half the character, so to speak. So you have to use String.codePointAt, which returns an int above 0xFFFF (not a char). You would do:
Character.isUpperCase(s.codePointAt(0));
Don't feel bad overlooked this; almost all Java coders handle UTF-16 badly, because the terminology misleadingly makes you think that each "char" value represents a character. UTF-16 sucks, because it is almost fixed width but not quite. So non-fixed-width edge cases tend not to get tested. Until one day, some document comes in which contains a character like U+1D4C3, and your entire system blows up.
Here is an expanded solution based on DrewT's answer above that uses cookies if localStorage is not available. It uses Mozilla's docCookies library:
function localStorageGet( pKey ) {
if( localStorageSupported() ) {
return localStorage[pKey];
} else {
return docCookies.getItem( 'localstorage.'+pKey );
}
}
function localStorageSet( pKey, pValue ) {
if( localStorageSupported() ) {
localStorage[pKey] = pValue;
} else {
docCookies.setItem( 'localstorage.'+pKey, pValue );
}
}
// global to cache value
var gStorageSupported = undefined;
function localStorageSupported() {
var testKey = 'test', storage = window.sessionStorage;
if( gStorageSupported === undefined ) {
try {
storage.setItem(testKey, '1');
storage.removeItem(testKey);
gStorageSupported = true;
} catch (error) {
gStorageSupported = false;
}
}
return gStorageSupported;
}
In your source, just use:
localStorageSet( 'foobar', 'yes' );
...
var foo = localStorageGet( 'foobar' );
...
If you want to use Graph API to get current user ID then just send a request to:
https://graph.facebook.com/me?access_token=...
Thanks to @HBP for paving the way here!
I found this to add a little flexibility to the solution.
The RegEx has been updated to accommodate times before noon.
This solution allows you to pass any string to it. As long as a valid time (in this format 18:00 || 18:00:00 || 3:00 || 3:00:00) is somewhere in that string, you're good to go.
Note: you can use just the militaryToTweleveHourConverter
or take the guts out of the parseTime
variable. However, I'm formatting a date from a database with date-fns
then passing that formatted date to the converter.
Totally works. Hope this helps.
import dateFns from 'date-fns';
//* +---------------------------+
//* Format ex. Sat 1/1/18 1:00pm
//* +---------------------------+
const formatMonthDayYearTime = date =>
militaryToTweleveHourConverter(
dateFns.format(new Date(date), 'ddd M/DD/YY H:mm')
);
//* +-------------------------------+
//* Convert MILITARY TIME to 12 hour
//* +-------------------------------+
const militaryToTweleveHourConverter = time => {
const getTime = time.split(' ');
const parseTime = getTime.map(res => {
// Check for correct time format and split into components or return non-time units unaltered
let timeUnit = res
.toString()
.match(/^([\d]|[0-1]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [res];
console.log('timeUnit', timeUnit);
// If the time format is matched, it will break the components into an array
// ie. ["19:00", "19", ":", "00", undefined]
if (timeUnit.length > 1) {
// Remove full string match value
timeUnit = timeUnit.slice(1);
// Set am/pm and assign it to the last index in the array
timeUnit[5] = timeUnit[0] < 12 ? 'am' : 'pm';
// Adjust hours by subtracting 12 from anything greater than 12 and replace the value in the hours index
timeUnit[0] = timeUnit[0] % 12 || 12;
}
// return adjusted time or original string
return timeUnit.join('');
});
// Re-assemble the array pieces into a string
return parseTime.join(' ');
};
console.log(formatMonthDayYearTime('Sat 9/17/18 18:30'));
// console log returns the following
// Mon 9/17/18 6:30pm
console.log(militaryToTweleveHourConverter('18:30'));
// console log returns the following
// 6:30pm
console.log(militaryToTweleveHourConverter('18:30:09'));
// console log returns the following
// 6:30:09pm
console.log(militaryToTweleveHourConverter('8:30:09'));
// console log returns the following
// 8:30:09am
While exec(open("filename").read())
is often given as an alternative to execfile("filename")
, it misses important details that execfile
supported.
The following function for Python3.x is as close as I could get to having the same behavior as executing a file directly. That matches running python /path/to/somefile.py
.
def execfile(filepath, globals=None, locals=None):
if globals is None:
globals = {}
globals.update({
"__file__": filepath,
"__name__": "__main__",
})
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), globals, locals)
# execute the file
execfile("/path/to/somefile.py")
Notes:
__main__
, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__"
__file__
is nicer for exception messages and some scripts use __file__
to get the paths of other files relative to them.Takes optional globals & locals arguments, modifying them in-place as execfile
does - so you can access any variables defined by reading back the variables after running.
Unlike Python2's execfile
this does not modify the current namespace by default. For that you have to explicitly pass in globals()
& locals()
.
you can search in registry.Actually I do'nt have vs2012 but I have vs2010.
There are 3 different (but very similar) registry keys for each of the 3 platform packages. Each key has a DWORD value called “Installed” with a value of 1.
HKLM\SOFTWARE\Microsoft\VisualStudio\10.0\VC\VCRedist\x86
HKLM\SOFTWARE\Microsoft\VisualStudio\10.0\VC\VCRedist\x64
HKLM\SOFTWARE\Microsoft\VisualStudio\10.0\VC\VCRedist\ia64
You can use registry function for that......
Not quite sure what the 300 is supposed to mean? Miss typo? However for iframes it would be best to use CSS :) - Ive found befor when importing youtube videos that it ignores inline things.
<style>
#myFrame { width:100%; height:100%; }
</style>
<iframe src="html_intro.asp" id="myFrame">
<p>Hi SOF</p>
</iframe>
I faced a similar issue. After ensuring the token field was actually rendered (see accepted answer) I checked my cookies. There were 2(!) cookies for the domain in my Chrome browser, apparently because I was running the application on the same domain as another app, but with a different port (i.e. mydomain.com set the original cookie while the buggy app was running on mydomain.com:123) Now apparently Chrome sent the wrong cookie so the CSRF protection was unable to link the token to the correct session.
Fix: clear all the cookies for the domain in question, make sure you don't run multiple applications on the same domain with differing ports.
There's some good answers here already, but I thought I might mention that pdftk might be useful for this task. Instead of producing one PDF directly, you could produce each PDF you need and then combine them together as a post-process with pdftk. This could even be done from within your program using a system() or ShellExecute() call.
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
I still found that with the solutions above, it didn't work (for example) with the Rails plugin for TextMate. I got a similar error (when retrieving the database schema).
So what did is, open terminal:
cd /usr/local/lib
sudo ln -s ../mysql-5.5.8-osx10.6-x86_64/lib/libmysqlclient.16.dylib .
Replace mysql-5.5.8-osx10.6-x86_64 with your own path (or mysql).
This makes a symbol link to the lib, now rails runs from the command line, as-well as TextMate plugin(s) like ruby-on-rails-tmbundle.
To be clear: this also fixes the error you get when starting rails server.
The MultiCell
is used for print text with multiple lines. It has the same atributes of Cell
except for ln
and link
.
$pdf->MultiCell( 200, 40, $reportSubtitle, 1);
What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
You can read the full documentation here.
* * * * * myjob.sh >> /var/log/myjob.log 2>&1
will log all output from the cron job to /var/log/myjob.log
You might use mail
to send emails. Most systems will send unhandled cron
job output by email to root or the corresponding user.
Open Safari Desktop iOS
Develop -> Responsive Design Mode
Click "Other" under device
Paste this: Mozilla/5.0 (iPad; CPU OS 10_2_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.79 Mobile/14D27 Safari/602.1
Use Safari inspect tools.
Like that:
class Zoo {
AnimalClass: typeof Animal;
constructor(AnimalClass: typeof Animal ) {
this.AnimalClass = AnimalClass
let Hector = new AnimalClass();
}
}
Or just:
class Zoo {
constructor(public AnimalClass: typeof Animal ) {
let Hector = new AnimalClass();
}
}
typeof Class
is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.
Here's the relevant part of TypeScript docs. Search for the typeof
. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.
Very late to the thread, but a technique I've used, pre-Angular, is to take advantage of JSON and the flexibility of JS to dynamically reference collection keys, and use inalienable facts of the environment (host server name, current browser language, etc.) as inputs to selectively discriminate/prefer suffixed key names within a JSON data structure.
This provides not merely deploy-environment context (per OP) but any arbitrary context (such as language) to provide i18n or any other variance required simultaneously, and (ideally) within a single configuration manifest, without duplication, and readably obvious.
IN ABOUT 10 LINES VANILLA JS
Overly-simplified but classic example: An API endpoint base URL in a JSON-formatted properties file that varies per environment where (natch) the host server will also vary:
...
'svcs': {
'VER': '2.3',
'API@localhost': 'http://localhost:9090/',
'[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
'[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
},
...
A key to the discrimination function is simply the server hostname in the request.
This, naturally, can be combined with an additional key based on the user's language settings:
...
'app': {
'NAME': 'Ferry Reservations',
'NAME@fr': 'Réservations de ferry',
'NAME@de': 'Fähren Reservierungen'
},
...
The scope of the discrimination/preference can be confined to individual keys (as above) where the "base" key is only overwritten if there's a matching key+suffix for the inputs to the function -- or an entire structure, and that structure itself recursively parsed for matching discrimination/preference suffixes:
'help': {
'BLURB': 'This pre-production environment is not supported. Contact Development Team with questions.',
'PHONE': '808-867-5309',
'EMAIL': '[email protected]'
},
'[email protected]': {
'BLURB': 'Please contact Customer Service Center',
'BLURB@fr': 'S\'il vous plaît communiquer avec notre Centre de service à la clientèle',
'BLURB@de': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
'PHONE': '1-800-CUS-TOMR',
'EMAIL': '[email protected]'
},
SO, if a visiting user to the production website has German (de) language preference setting, the above configuration would collapse to:
'help': {
'BLURB': 'Bitte kontaktieren Sie unseren Kundendienst!!1!',
'PHONE': '1-800-CUS-TOMR',
'EMAIL': '[email protected]'
},
What does such a magical preference/discrimination JSON-rewriting function look like? Not much:
// prefer(object,suffix|[suffixes]) by/par/durch storsoc
// prefer({ a: 'apple', a@env: 'banana', b: 'carrot' },'env') -> { a: 'banana', b: 'carrot' }
function prefer(o,sufs) {
for (var key in o) {
if (!o.hasOwnProperty(key)) continue; // skip non-instance props
if(key.split('@')[1]) { // suffixed!
// replace root prop with the suffixed prop if among prefs
if(o[key] && sufs.indexOf(key.split('@')[1]) > -1) o[key.split('@')[0]] = JSON.parse(JSON.stringify(o[key]));
// and nuke the suffixed prop to tidy up
delete o[key];
// continue with root key ...
key = key.split('@')[0];
}
// ... in case it's a collection itself, recurse it!
if(o[key] && typeof o[key] === 'object') prefer(o[key],sufs);
};
};
In our implementations, which include Angular and pre-Angular websites, we simply bootstrap the configuration well ahead of other resource calls by placing the JSON within a self-executing JS closure, including the prefer() function, and fed basic properties of hostname and language-code (and accepts any additional arbitrary suffixes you might need):
(function(prefs){ var props = {
'svcs': {
'VER': '2.3',
'API@localhost': 'http://localhost:9090/',
'[email protected]': 'https://www.uat.productionwebsite.com:9090/res/',
'[email protected]': 'https://www.productionwebsite.com:9090/api/res/'
},
...
/* yadda yadda moar JSON und bisque */
function prefer(o,sufs) {
// body of prefer function, broken for e.g.
};
// convert string and comma-separated-string to array .. and process it
prefs = [].concat( ( prefs.split ? prefs.split(',') : prefs ) || []);
prefer(props,prefs);
window.app_props = JSON.parse(JSON.stringify(props));
})([location.hostname, ((window.navigator.userLanguage || window.navigator.language).split('-')[0]) ] );
A pre-Angular site would now have a collapsed (no @ suffixed keys) window.app_props to refer to.
An Angular site, as a bootstrap/init step, simply copies the dead-dropped props object into $rootScope, and (optionally) destroys it from global/window scope
app.constant('props',angular.copy(window.app_props || {})).run( function ($rootScope,props) { $rootScope.props = props; delete window.app_props;} );
to be subsequently injected into controllers:
app.controller('CtrlApp',function($log,props){ ... } );
or referred to from bindings in views:
<span>{{ props.help.blurb }} {{ props.help.email }}</span>
Caveats? The @ character is not valid JS/JSON variable/key naming, but so far accepted. If that's a deal-breaker, substitute for any convention you like, such as "__" (double underscore) as long as you stick to it.
The technique could be applied server-side, ported to Java or C# but your efficiency/compactness may vary.
Alternately, the function/convention could be part of your front-end compile script, so that the full gory all-environment/all-language JSON is never transmitted over the wire.
UPDATE
We've evolved usage of this technique to allow multiple suffixes to a key, to avoid being forced to use collections (you still can, as deeply as you want), and as well to honor the order of the preferred suffixes.
Example (also see working jsFiddle):
var o = { 'a':'apple', 'a@dev':'apple-dev', 'a@fr':'pomme',
'b':'banana', 'b@fr':'banane', 'b@dev&fr':'banane-dev',
'c':{ 'o':'c-dot-oh', 'o@fr':'c-point-oh' }, 'c@dev': { 'o':'c-dot-oh-dev', 'o@fr':'c-point-oh-dev' } };
/*1*/ prefer(o,'dev'); // { a:'apple-dev', b:'banana', c:{o:'c-dot-oh-dev'} }
/*2*/ prefer(o,'fr'); // { a:'pomme', b:'banane', c:{o:'c-point-oh'} }
/*3*/ prefer(o,'dev,fr'); // { a:'apple-dev', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*4*/ prefer(o,['fr','dev']); // { a:'pomme', b:'banane-dev', c:{o:'c-point-oh-dev'} }
/*5*/ prefer(o); // { a:'apple', b:'banana', c:{o:'c-dot-oh'} }
1/2 (basic usage) prefers '@dev' keys, discards all other suffixed keys
3 prefers '@dev' over '@fr', prefers '@dev&fr' over all others
4 (same as 3 but prefers '@fr' over '@dev')
5 no preferred suffixes, drops ALL suffixed properties
It accomplishes this by scoring each suffixed property and promoting the value of a suffixed property to the non-suffixed property when iterating over the properties and finding a higher-scored suffix.
Some efficiencies in this version, including removing dependence on JSON to deep-copy, and only recursing into objects that survive the scoring round at their depth:
function prefer(obj,suf) {
function pr(o,s) {
for (var p in o) {
if (!o.hasOwnProperty(p) || !p.split('@')[1] || p.split('@@')[1] ) continue; // ignore: proto-prop OR not-suffixed OR temp prop score
var b = p.split('@')[0]; // base prop name
if(!!!o['@@'+b]) o['@@'+b] = 0; // +score placeholder
var ps = p.split('@')[1].split('&'); // array of property suffixes
var sc = 0; var v = 0; // reset (running)score and value
while(ps.length) {
// suffix value: index(of found suffix in prefs)^10
v = Math.floor(Math.pow(10,s.indexOf(ps.pop())));
if(!v) { sc = 0; break; } // found suf NOT in prefs, zero score (delete later)
sc += v;
}
if(sc > o['@@'+b]) { o['@@'+b] = sc; o[b] = o[p]; } // hi-score! promote to base prop
delete o[p];
}
for (var p in o) if(p.split('@@')[1]) delete o[p]; // remove scores
for (var p in o) if(typeof o[p] === 'object') pr(o[p],s); // recurse surviving objs
}
if( typeof obj !== 'object' ) return; // validate
suf = ( (suf || suf === 0 ) && ( suf.length || suf === parseFloat(suf) ) ? suf.toString().split(',') : []); // array|string|number|comma-separated-string -> array-of-strings
pr(obj,suf.reverse());
}
That's because abc
is undefined at the moment of the template rendering. You can use safe navigation operator (?
) to "protect" template until HTTP call is completed:
{{abc?.xyz?.name}}
You can read more about safe navigation operator here.
Update:
Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf
directive to overcome this problem:
<div *ngIf="arr && arr.length > 0">
{{arr[0].name}}
</div>
Read more about NgIf
directive here.
It will replace all new line with break
str = str.replace(/\n/g, '<br>')
If you want to replace all new line with single break line
str = str.replace(/\n*\n/g, '<br>')
Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm this will help you everytime.
In Java, List
is an interface. That is, it cannot be instantiated directly.
Instead you can use ArrayList
which is an implementation of that interface that uses an array as its backing store (hence the name).
Since ArrayList
is a kind of List
, you can easily upcast it:
List<T> mylist = new ArrayList<T>();
This is in contrast with .NET, where, since version 2.0, List<T>
is the default implementation of the IList<T>
interface.
You can convert your date in many formats, for example :
CONVERT(NVARCHAR(10), DATE_OF_DAY, 103) => 15/09/2016
CONVERT(NVARCHAR(10), DATE_OF_DAY, 3) => 15/09/16
Syntaxe :
CONVERT('TheTypeYouWant', 'TheDateToConvert', 'TheCodeForFormating' * )
In your case, i've just converted and restrict size by nvarchar(6) like this :
CONVERT(NVARCHAR(6), DATE_OF_DAY, 112) => 201609
See more at : http://www.w3schools.com/sql/func_convert.asp
If you think you'll be using more than 1 db for any reason, go with the variable because you'll be able to change one parameter to switch to an entirely different db. I.e. for testing , autobackup, etc.
Quick and dirty:
head -16428 < file.in | tail -259 > file.out
Probably not the best way to do it but it should work.
BTW: 259 = 16482-16224+1.
If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do
str = "file_" + i.to_s.rjust(n, "0")
What about GLM?
It's based on the OpenGL Shading Language (GLSL) specification and released under the MIT license. Clearly aimed at graphics programmers
On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.
Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")
If you need to get the name and PublicKeyToken see this question.
Yes, the order of elements in a python list is persistent.
I'm not sure what you're trying to do. Python is a very dynamic language; you don't usually need to declare variables until you're actually going to assign to or use them. I think what you want to do is just
foo = None
which will assign the value None
to the variable foo
.
EDIT: What you really seem to want to do is just this:
#note how I don't do *anything* with value here
#we can just start using it right inside the loop
for index in sequence:
if conditionMet:
value = index
break
try:
doSomething(value)
except NameError:
print "Didn't find anything"
It's a little difficult to tell if that's really the right style to use from such a short code example, but it is a more "Pythonic" way to work.
EDIT: below is comment by JFS (posted here to show the code)
for item in sequence:
if some_condition(item):
found = True
break
else: # no break or len(sequence) == 0
found = False
if found:
do_something(item)
NOTE: if some_condition()
raises an exception then found
is unbound.
NOTE: if len(sequence) == 0 then item
is unbound.
The above code is not advisable. Its purpose is to illustrate how local variables work, namely whether "variable" is "defined" could be determined only at runtime in this case. Preferable way:
for item in sequence:
if some_condition(item):
do_something(item)
break
Or
found = False
for item in sequence:
if some_condition(item):
found = True
break
if found:
do_something(item)
To delete the last element from the list just do this.
a = [1,2,3,4,5]
a = a[:-1]
#Output [1,2,3,4]
A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.
A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.
By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!
If only the incoming stream stalls for more than a millisecond you are running into a timeout.
string[]
is an array (vector) of strings
string
is just a string (a list/array of characters)
Depending on how you want to convert this, the canonical answer could be:
return String.Join(" ", myStringArray);
return new []{ myString };
yum install -y yum-utils
yum-config-manager --add-repo http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo
yum-config-manager --enable epel-apache-maven
yum install -y apache-maven
for JVM developer, this is a SDK manager for all the tool you need.
Install sdkman:
yum install -y zip unzip
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
Install Maven:
sdk install maven
I do the following, if you want to use it then paste it in some where and set your handler code in locationHashChanged(qs) where commented, and then call changeHashValue(hashQuery) every time you load an ajax request. Its not a quick-fix answer and there are none, so you will need to think about it and pass sensible hashQuery args (ie a=1&b=2) to changeHashValue(hashQuery) and then cater for each combination of said args in your locationHashChanged(qs) callback ...
// Add code below ...
function locationHashChanged(qs)
{
var q = parseQs(qs);
// ADD SOME CODE HERE TO LOAD YOUR PAGE ELEMS AS PER q !!
// YOU SHOULD CATER FOR EACH hashQuery ATTRS COMBINATION
// THAT IS PASSED TO changeHashValue(hashQuery)
}
// CALL THIS FROM YOUR AJAX LOAD CODE EACH LOAD ...
function changeHashValue(hashQuery)
{
stopHashListener();
hashValue = hashQuery;
location.hash = hashQuery;
startHashListener();
}
// AND DONT WORRY ABOUT ANYTHING BELOW ...
function checkIfHashChanged()
{
var hashQuery = getHashQuery();
if (hashQuery == hashValue)
return;
hashValue = hashQuery;
locationHashChanged(hashQuery);
}
function parseQs(qs)
{
var q = {};
var pairs = qs.split('&');
for (var idx in pairs) {
var arg = pairs[idx].split('=');
q[arg[0]] = arg[1];
}
return q;
}
function startHashListener()
{
hashListener = setInterval(checkIfHashChanged, 1000);
}
function stopHashListener()
{
if (hashListener != null)
clearInterval(hashListener);
hashListener = null;
}
function getHashQuery()
{
return location.hash.replace(/^#/, '');
}
var hashListener = null;
var hashValue = '';//getHashQuery();
startHashListener();
This answer copies the @abosancic answer but adds extra safety to avoid CORS exploit.
Tip 1: Do not reflect the incoming Origin as is without checking the list of allowed hosts to access.
Tip 2: Allow credentialed request only for whitelisted hosts.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class SimpleCORSFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
private List<String> allowedOrigins;
public SimpleCORSFilter() {
log.info("SimpleCORSFilter init");
allowedOrigins = new ArrayList<>();
allowedOrigins.add("https://mysafeorigin.com");
allowedOrigins.add("https://itrustthissite.com");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String allowedOrigin = getOriginToAllow(request.getHeader("Origin"));
if(allowedOrigin != null) {
response.setHeader("Access-Control-Allow-Origin", allowedOrigin);
response.setHeader("Access-Control-Allow-Credentials", "true");
}
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
public String getOriginToAllow(String incomingOrigin) {
if(allowedOrigins.contains(incomingOrigin.toLowerCase())) {
return incomingOrigin;
} else {
return null;
}
}
}
For iOS 13+
in SceneDelegate:
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options
connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
let storyboard = UIStoryboard(name: "Main", bundle: nil) // Where "Main" is the storyboard file name
let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") // Where "ViewController" is the ID of your viewController
window?.rootViewController = vc
window?.makeKeyAndVisible()
}
Came across this question, while trying to uninstall the many random Python packages installed over time.
Using information from this thread, this is what I came up with:
cat package_list | xargs -n1 sudo pip uninstall -y
The package_list
is cleaned up (awk) from a pip freeze
in a virtualenv.
To remove almost all Python packages:
yolk -l | cut -f 1 -d " " | grep -v "setuptools|pip|ETC.." | xargs -n1 pip uninstall -y
You can solve Q2 if you have the sum of both lists and the product of both lists.
(l1 is the original, l2 is the modified list)
d = sum(l1) - sum(l2)
m = mul(l1) / mul(l2)
We can optimise this since the sum of an arithmetic series is n times the average of the first and last terms:
n = len(l1)
d = (n/2)*(n+1) - sum(l2)
Now we know that (if a and b are the removed numbers):
a + b = d
a * b = m
So we can rearrange to:
a = s - b
b * (s - b) = m
And multiply out:
-b^2 + s*b = m
And rearrange so the right side is zero:
-b^2 + s*b - m = 0
Then we can solve with the quadratic formula:
b = (-s + sqrt(s^2 - (4*-1*-m)))/-2
a = s - b
Sample Python 3 code:
from functools import reduce
import operator
import math
x = list(range(1,21))
sx = (len(x)/2)*(len(x)+1)
x.remove(15)
x.remove(5)
mul = lambda l: reduce(operator.mul,l)
s = sx - sum(x)
m = mul(range(1,21)) / mul(x)
b = (-s + math.sqrt(s**2 - (-4*(-m))))/-2
a = s - b
print(a,b) #15,5
I do not know the complexity of the sqrt, reduce and sum functions so I cannot work out the complexity of this solution (if anyone does know please comment below.)
The code from Jaldhi Bhatt doesn't works for me.
Flutter throws a 'Navigator operation requested with a context that does not include a Navigator.'
I fixed the code wrapping the Navigator consumer component inside of another component that initialize the Navigator context using routes, as mentioned in this article.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:my-app/view/main-view.dart';
class SplashView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: Builder(
builder: (context) => new _SplashContent(),
),
routes: <String, WidgetBuilder>{
'/main': (BuildContext context) => new MainView()}
);
}
}
class _SplashContent extends StatefulWidget{
@override
_SplashContentState createState() => new _SplashContentState();
}
class _SplashContentState extends State<_SplashContent>
with SingleTickerProviderStateMixin {
var _iconAnimationController;
var _iconAnimation;
startTimeout() async {
var duration = const Duration(seconds: 3);
return new Timer(duration, handleTimeout);
}
void handleTimeout() {
Navigator.pushReplacementNamed(context, "/main");
}
@override
void initState() {
super.initState();
_iconAnimationController = new AnimationController(
vsync: this, duration: new Duration(milliseconds: 2000));
_iconAnimation = new CurvedAnimation(
parent: _iconAnimationController, curve: Curves.easeIn);
_iconAnimation.addListener(() => this.setState(() {}));
_iconAnimationController.forward();
startTimeout();
}
@override
Widget build(BuildContext context) {
return new Center(
child: new Image(
image: new AssetImage("images/logo.png"),
width: _iconAnimation.value * 100,
height: _iconAnimation.value * 100,
)
);
}
}
Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.
e.g.,
// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);
// use icon here
game.frame.setIconImage(myImg);
DECLARE @test nvarchar(100)
SET @test = 'Foreign Tax Credit - 1997'
SELECT @test, left(@test, charindex('-', @test) - 2) AS LeftString,
right(@test, len(@test) - charindex('-', @test) - 1) AS RightString
Include the sunfire and jacoco plugins in the pom.xml and Run the maven command as given below.
mvn jacoco:prepare-agent jacoco:report sonar:sonar
<properties>
<surefire.version>2.17</surefire.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals><goal>prepare-agent</goal></goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals><goal>report</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
Well you would need to get a file with JFileChooser and then read through the lines of the file using a scanner and the hasNext() function
http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html
once you do that you can save the line into a variable and manipulate the contents.
You can also try this way
<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
jquery
$('.select_continent').click(function () {
alert($(this).data('value'));
});
Good luck !!!!
Imagine it like this: When your sub-class inherits properties from a super-class, they don't magically appear. You still have to construct the object. So, you call the base constructor. Imagine if you class inherits a variable, which your super-class constructor initializes to an important value. If we didn't do this, your code could fail because the variable wasn't initialized.
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
If you already have the figure object use:
f.set_figheight(15)
f.set_figwidth(15)
But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:
f, axs = plt.subplots(2,2,figsize=(15,15))
<a href="1.html"><input type="text" class="button_active" value="1"></a>
<a href="2.html"><input type="text" class="button" value="2"></a>
<a href="3.html"><input type="text" class="button" value="3"></a>
Try that. Unless you truly need to stick with the type as submit, then what I provided should work. If you are going to stick with submit, then everything mentioned above is correct, it makes no sense.
That is a default behaviour of each browser; your browser seems to be Safari, in Google Chrome it is orange in color!
Use this to remove this effect:
button {
outline: none; // this one
}
In a nutshell, sys.argv
is a list of the words that appear in the command used to run the program. The first word (first element of the list) is the name of the program, and the rest of the elements of the list are any arguments provided. In most computer languages (including Python), lists are indexed from zero, meaning that the first element in the list (in this case, the program name) is sys.argv[0]
, and the second element (first argument, if there is one) is sys.argv[1]
, etc.
The test len(sys.argv) >= 2
simply checks wither the list has a length greater than or equal to 2, which will be the case if there was at least one argument provided to the program.
$("element").on("event1 event2 event..n", function() {
//execution
});
This tutorial is about handling multiple events.
Its always better to go for a generic reusable function in your project which returns whether the extension loaded. You can use the following function to check -
function isExtensionLoaded($extension_name){
return extension_loaded($extension_name);
}
Usage
echo isExtensionLoaded('curl');
echo isExtensionLoaded('gd');
Use the Counter.most_common()
method, it'll sort the items for you:
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq
is used instead of a straight sort:
>>> x.most_common(1)
[('c', 7)]
Outside of counters, sorting can always be adjusted based on a key
function; .sort()
and sorted()
both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True)
would give you the same sorting as x.most_common()
, but only return the keys, for example:
>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']
or you can sort on only the value given (key, value)
pairs:
>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]
See the Python sorting howto for more information.
It depends on what you are trying to do with the XML files. If you are just trying to read the XML file (like a configuration file), The Wicked Flea is correct in suggesting SimpleXML since it creates what amounts to nested ArrayObjects. e.g. value will be accessible by $xml->root->child.
If you are looking to manipulate the XML files you're probably best off using DOM XML
UPDATE January, 2017:
According to Can I use, the user-select
is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).
All of the correct CSS variations are:
.noselect {_x000D_
-webkit-touch-callout: none; /* iOS Safari */_x000D_
-webkit-user-select: none; /* Safari */_x000D_
-khtml-user-select: none; /* Konqueror HTML */_x000D_
-moz-user-select: none; /* Firefox */_x000D_
-ms-user-select: none; /* Internet Explorer/Edge */_x000D_
user-select: none; /* Non-prefixed version, currently_x000D_
supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
Unselectable text._x000D_
</p>
_x000D_
Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.
More information can be found in Mozilla Developer Network documentation.
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
One totally different approach is to put things in a grid, such as ui-grid or Kendo's grid, and have the columns be resizable. A downside is that users would not be able to resize the rows, though the row size could be set programmatically.
Yes of course, just add the response y
as first column in the dataframe and call lm()
on it:
d2<-data.frame(y,d)
> d2
y x1 x2 x3
1 1 4 3 4
2 4 -1 9 -4
3 6 3 8 -2
> lm(d2)
Call:
lm(formula = d2)
Coefficients:
(Intercept) x1 x2 x3
-5.6316 0.7895 1.1579 NA
Also, my information about R points out that assignment with <-
is recommended over =
.
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.logger.org.hibernate.hql.ast.AST=info
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.cache=info
log4j.logger.org.hibernate.jdbc=debug
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
log4j.appender.hb.layout.ConversionPattern=HibernateLog --> %d{HH:mm:ss} %-5p %c - %m%n
log4j.appender.hb.Threshold=TRACE
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
Some frameworks use persistence.xml
:
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
Algorithm example (Java):
public boolean search(/* for */Integer K,/* in */List</* of */Integer> L)
{
for(/* each */Integer i:/* in */L)
{
if(i == K)
{
return true;
}
}
return false;
}
Algorithm description:
This algorithm searches a list, item by item, looking for a key,
Iterating on each item in the list, if it's the key then return True,
If the loop has finished without finding the key, return False.
Big-O notation represents the upper-bound on the Complexity (Time, Space, ..)
To find The Big-O on Time Complexity:
Calculate how much time (regarding input size) the worst case takes:
Worst-Case: the key doesn't exist in the list.
Time(Worst-Case) = 4n+1
Time: O(4n+1) = O(n) | in Big-O, constants are neglected
O(n) ~ Linear
There's also Big-Omega, which represent the complexity of the Best-Case:
Best-Case: the key is the first item.
Time(Best-Case) = 4
Time: O(4) = O(1) ~ Instant\Constant
To align the text in the proper format -
Ctrl + K + D for front end pages like .aspx
or .cshtml
Ctrl + K + F for a .cs
page
But observe to press all buttons in sequence...
In Normal mode:
:set hlsearch
Then search for a pattern with the command /
in Normal mode, or <Ctrl>o
followed by /
in Insert mode. *
in Normal mode will search for the next occurrence of the word under the cursor. The hlsearch
option will highlight all of them if set. #
will search for the previous occurrence of the word.
To remove the highlight of the previous search:
:nohlsearch
You might wish to map :nohlsearch<CR>
to some convenient key.
mAgendaListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//view.setBackgroundColor(Color.RED);
for(int i=0; i<parent.getChildCount(); i++)
{
if(i == position)
{
parent.getChildAt(i).setBackgroundColor(Color.BLUE);
}
else
{
parent.getChildAt(i).setBackgroundColor(Color.BLACK);
}
}
There's a few ways of doing this. However, here is one of the easiest ways to do this and it's reusable.
What is happening is that we're getting all the properties of the parent class and updating those same properties on the child class. Where baseObj would be the parent object and T would be the child class.
public static T ConvertToDerived<T>(object baseObj) where T : new()
{
var derivedObj = new T();
var members = baseObj.GetType().GetMembers();
foreach (var member in members)
{
object val = null;
if (member.MemberType == MemberTypes.Field)
{
val = ((FieldInfo)member).GetValue(baseObj);
((FieldInfo)member).SetValue(derivedObj, val);
}
else if (member.MemberType == MemberTypes.Property)
{
val = ((PropertyInfo)member).GetValue(baseObj);
if (val is IList && val.GetType().IsGenericType)
{
var listType = val.GetType().GetGenericArguments().Single();
var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(listType));
foreach (var item in (IList)val)
{
list.Add(item);
}
((PropertyInfo)member).SetValue(baseObj, list, null);
}
if (((PropertyInfo)member).CanWrite)
((PropertyInfo)member).SetValue(derivedObj, val);
}
}
return derivedObj;
}
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
I've always used:
unique = (arr) => arr.filter((item, i, s) => s.lastIndexOf(item) == i);
But recently I had to get unique values for:
["1", 1, "2", 2, "3", 3]
And my old standby didn't cut it, so I came up with this:
uunique = (arr) => Object.keys(Object.assign({}, ...arr.map(a=>({[a]:true}))));
I'm not sure if this answers your question, but for example:
if (A || B)
{
Console.WriteLine("Or");
}
if (A && B)
{
Console.WriteLine("And");
}
I have created a solution which may be of use to some people. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.
I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.
Even I had also observed the similar problem. I had closed my eclipse project because of some reason and on restart some of my file added were not visible in explorer even though corresponding file were existing.
Following solution worked for me: Select whole workspace (Ctrl+A) ==> Righ click and press Refresh.
On the Mac you can also use ?+K
just like in Terminal.
Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
Try this:
import sys
def Factorial(n): # return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
print Factorial(10)
Ciro's solution about an SVG Data URI background containing the text is very clever.
However, it won't work in IE if you just add the plain SVG source to the data URI.
In order to get around this and make it work in IE9 and up, encode the SVG to base64. This is a great tool.
So this:
background:url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><text x="5%" y="5%" font-size="30" fill="red">I love SVG!</text></svg>');
Becomes this:
background:url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjUlIiB5PSI1JSIgZm9udC1zaXplPSIzMCIgZmlsbD0icmVkIj5JIGxvdmUgU1ZHITwvdGV4dD48L3N2Zz4=');
Tested and it works in IE9-10-11, WebKit (Chrome 37, Opera 23) and Gecko (Firefox 31).
/proc/net/tcp -a list of open tcp sockets
/proc/net/udp -a list of open udp sockets
/proc/net/raw -a list all the 'raw' sockets
These are the files, use cat
command to view them. For example:
cat /proc/net/tcp
You can also use the lsof
command.
lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.
The npm view <pkg> version
prints the last version by release date. That might very well be an hotfix release for a older stable branch at times.
The solution is to list all versions and fetch the last one by version number
$ npm view <pkg> versions --json | jq -r '.[-1]'
Or with awk instead of jq:
$ npm view <pkg> --json | awk '/"$/{print gensub("[ \"]", "", "G")}'
Check if you're using some Chrome extension (Night mode or something else). Disable that and see if the 'inject' gone.
If you want to get values in Javascript on frontend, you can use the native way to do it by using :
document.getElementsByName("movie")[0].value;
Where "movie"
is the name of your input
<input type="text" name="movie">
If you want to get it on angular.js controller, you can use;
$scope.movie
//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
//Get the error message ID, if any.
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0) {
return std::string(); //No error message has been recorded
}
LPSTR messageBuffer = nullptr;
//Ask Win32 to give us the string version of that message ID.
//The parameters we pass in, tell Win32 to create the buffer that holds the message for us (because we don't yet know how long the message string will be).
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
//Copy the error message into a std::string.
std::string message(messageBuffer, size);
//Free the Win32's string's buffer.
LocalFree(messageBuffer);
return message;
}
To change database owner:
ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa
As of SQL Server 2014 you can still use sp_changedbowner
as well, even though Microsoft promised to remove it in the "future" version after SQL Server 2012. They removed it from SQL Server 2014 BOL though.
you can try with awk:
awk '/blah/{getline; print}' logfile
function Get-ADDWebBindings {
param([string]$Name="*",[switch]$http,[switch]$https)
try {
if (-not (Get-Module WebAdministration)) { Import-Module WebAdministration }
Get-WebBinding | ForEach-Object { $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1' } | Sort | Get-Unique | Where-Object {$_ -like $Name} | ForEach-Object {
$n=$_
Get-WebBinding | Where-Object { ($_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1') -like $n } | ForEach-Object {
if ($http -or $https) {
if ( ($http -and ($_.protocol -like "http")) -or ($https -and ($_.protocol -like "https")) ) {
New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
}
} else {
New-Object psobject -Property @{Name = $n;Protocol=$_.protocol;Binding = $_.bindinginformation}
}
}
}
}
catch {
$false
}
}
I took the answer from @newtover and extended it using the new json_table function in MySql 8. This allows you to create a stored procedure to handle the workload rather than building your own SQL text in code:
drop table if exists `test`;
create table `test` (
`Id` int,
`Number` int,
PRIMARY KEY (`Id`)
);
insert into test (Id, Number) values (1, 1), (2, 2);
DROP procedure IF EXISTS `Test`;
DELIMITER $$
CREATE PROCEDURE `Test`(
p_json json
)
BEGIN
update test s
join json_table(p_json, '$[*]' columns(`id` int path '$.id', `number` int path '$.number')) v
on s.Id=v.id set s.Number=v.number;
END$$
DELIMITER ;
call `Test`('[{"id": 1, "number": 10}, {"id": 2, "number": 20}]');
select * from test;
drop table if exists `test`;
It's a few ms slower than pure SQL but I'm happy to take the hit rather than generate the sql text in code. Not sure how performant it is with huge recordsets (the JSON object has a max size of 1Gb) but I use it all the time when updating 10k rows at a time.
You have two choices here. The first is to have two result sets which will set 'Test1' or 'Test2' based on the condition in the WHERE
clause, and then UNION
them together:
select
'Test1', *
from
TABLE
Where
CCC='D' AND DDD='X' AND exists(select ...)
UNION
select
'Test2', *
from
TABLE
Where
CCC<>'D' AND DDD='X' AND exists(select ...)
This might be an issue, because you are going to effectively scan/seek on TABLE twice.
The other solution would be to select from the table once, and set 'Test1' or 'Test2' based on the conditions in TABLE:
select
case
when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1'
when CCC<>'D' AND DDD='X' AND exists(select ...) then 'Test2'
end,
*
from
TABLE
Where
(CCC='D' AND DDD='X' AND exists(select ...)) or
(CCC<>'D' AND DDD='X' AND exists(select ...))
The catch here being that you will have to duplicate the filter conditions in the CASE
statement and the WHERE
statement.
var map = new google.maps.Map(document.getElementById("map"),{
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++){
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
bounds.extend(marker.position);
}
map.fitBounds(bounds);
Phil Haak has an example that I think is a bit more stable when dealing with paths with crazy "\" style directory separators. It also safely handles path concatenation. It comes for free in System.IO
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
However, you could also try "AppDomain.CurrentDomain.BaseDirector" instead of "Server.MapPath".
Kind of old question, but with the latest XCode, codesign
is easy:
$ codesign -s my_certificate example.ipa
$ codesign -vv example.ipa
example.ipa: valid on disk
example.ipa: satisfies its Designated Requirement
Look for books by Ted Padova. Over the years, he has written a series of books called The Acrobat PDF {5,6,7,8,9...} Bible. They contain chapter(s) on JavaScript in PDF files. They are not as comprehensive as the reference documentation listed here, but in the books there are some realistic use-cases discussed in context.
There was also a talk on hacking PDF files by a computer scientist, given at a conference in 2010. The link on the talk's announcement-page to the slides is dead, but Google is your friend-. The talk is not exclusively on JavaScript, though. YouTube video - JavaScript starts at 06:00.
If you are using ndk r10c or later, simply add APP_STL=c++_static to Application.mk
As stated by Taylor L, you can't just "stop" a thread (by calling a simple method) due to the fact that it could leave your system in an unstable state as the external calling thread may not know what is going on inside your thread.
With this said, the best way to "stop" a thread is to have the thread keep an eye on itself and to have it know and understand when it should stop.
You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).
You specify sigma
and hsize
in fspecial
.
%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)
Taking a point from both Boycs Answer and mtmurdock's subsequent answer I have the following stored proc on all of my development or staging databases. I've added some switches to fit my own requirement if I need to add in statements to reseed the data for certain columns.
(Note: I would have added this as a comment to Boycs brilliant answer but I haven't got enough reputation to do that yet. So please accept my apologies for adding this as an entirely new answer.)
ALTER PROCEDURE up_ResetEntireDatabase
@IncludeIdentReseed BIT,
@IncludeDataReseed BIT
AS
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
IF @IncludeIdentReseed = 1
BEGIN
EXEC sp_MSForEachTable 'DBCC CHECKIDENT (''?'' , RESEED, 1)'
END
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
IF @IncludeDataReseed = 1
BEGIN
-- Populate Core Data Table Here
END
GO
And then once ready the execution is really simple:
EXEC up_ResetEntireDatabase 1, 1
hi here is a simple example: <div id="test">content</div>
and
var test = 5;
document.getElementById('test').innerHTML = test;
and you can test it here : http://jsfiddle.net/SLbKX/
That's not even valid syntax. And you're trying to compare to a string. For arrays you would have to walk the array yourself:
public class T {
public static void main( String args[] ) {
char[] list = {'m', 'e', 'y'};
int index = -1;
for (int i = 0; (i < list.length) && (index == -1); i++) {
if (list[i] == 'e') {
index = i;
}
}
System.out.println(index);
}
}
If you are using a collection, such as ArrayList<Character>
you can also use the indexOf()
method:
ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');
System.out.println(list.indexOf('e'));
There is also the Arrays
class which shortens above code:
List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));
To your secondary question
var elem1 = $('#elem1'),
elem2 = $('#elem2'),
elem3 = $('#elem3');
You can use the variable as the replacement of selector.
elem1.css({'display':'none'}); //will work
In the below case selector is already stored in a variable.
$(elem1,elem2,elem3).css({'display':'none'}); // will not work
If you're running a CentOS container, you can install ps using this command:
yum install -y procps
Running this command on Dockerfile:
RUN yum install -y procps
Since API 21 there is an option set letter spacing. You can call method setLetterSpacing or set it in XML with attribute letterSpacing.
I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).
public class ResourceLoader {
public static URL getResource(String resource) {
final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
classLoaders.add(Thread.currentThread().getContextClassLoader());
classLoaders.add(ResourceLoader.class.getClassLoader());
for (ClassLoader classLoader : classLoaders) {
final URL url = getResourceWith(classLoader, resource);
if (url != null) {
return url;
}
}
final URL systemResource = ClassLoader.getSystemResource(resource);
if (systemResource != null) {
return systemResource;
} else {
try {
return new File(resource).toURI().toURL();
} catch (MalformedURLException e) {
return null;
}
}
}
private static URL getResourceWith(ClassLoader classLoader, String resource) {
if (classLoader != null) {
return classLoader.getResource(resource);
}
return null;
}
}
git branch -d branch1 branch2 branch3
already works, but will be faster with Git 2.31 (Q1 2021).
Before, when removing many branches and tags, the code used to do so one ref at a time.
There is another API it can use to delete multiple refs, and it makes quite a lot of performance difference when the refs are packed.
See commit 8198907 (20 Jan 2021) by Phil Hord (phord
).
(Merged by Junio C Hamano -- gitster
-- in commit f6ef8ba, 05 Feb 2021)
8198907795
:usedelete_refs
when deleting tags or branchesAcked-by: Elijah Newren
Signed-off-by: Phil Hord
'
git tag -d
'(man) accepts one or more tag refs to delete, but each deletion is done by callingdelete_ref
on eachargv
.
This is very slow when removing from packed refs.
Usedelete_refs
instead so all the removals can be done inside a single transaction with a single update.Do the same for '
git branch -d
'(man).Since
delete_refs
performs all the packed-refs delete operations inside a single transaction, if any of the deletes fail then all them will be skipped.
In practice, none of them should fail since we verify the hash of each one before callingdelete_refs
, but some network error or odd permissions problem could have different results after this change.Also, since the file-backed deletions are not performed in the same transaction, those could succeed even when the packed-refs transaction fails.
After deleting branches, remove the branch config only if the branch ref was removed and was not subsequently added back in.
A manual test deleting 24,000 tags took about 30 minutes using
delete_ref
.
It takes about 5 seconds usingdelete_refs
.
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
Microsoft Virtual WiFi Miniport
should start and bind automatically to the underlying function driver. Try disabling and reenabling the AR9285
driver.
For Eclipse STS (3.5 at least) you don't need to install anything. Right click on schema.xsd -> Generate -> JAXB Classes. You'll have to specify the package & location in the next step and that's all, your classes should be generated. I guess all the above mentioned solutions work, but this seems by far the easiest (for STS users).
[UPDATE] Eclipse STS version 3.6 (based on Kepler) comes with the same functionality.
Using VS Professional 2019, I was trying to run a downloaded solution from a Udemy class on selenium automation testing, and most of the projects had errors in the project references sections. I tried cleaning, rebuilding, closing VS. Then, in VS, when I right clicked on the solution in Solution Explorer and chose Manage Nuget Packages for Solution, there were 2 available updates: for MSTest.TestAdapter and MSTest.TestFramework, and when I installed those, the error messages on the references for all the projects went away, for the references to those, as well as for the references to System and System.Core.
Given
std::vector<Rule>& topPriorityRules;
The correct way to remove the first element of the referenced vector is
topPriorityRules.erase(topPriorityRules.begin());
which is exactly what you suggested.
Looks like i need to do iterator overloading.
There is no need to overload an iterator in order to erase first element of std::vector
.
P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.
For Python 3, try the following:
import sys
!conda install --yes --prefix {sys.prefix} scikit-image
This isn't so much an answer as a non-answer, i.e. an example showing why one of the highly voted answers above is actually wrong.
I thought that answer looked good. In fact, it gave me what I was looking for: :nth-of-type
which, for my situation, worked. (So, thanks for that, @Bdwey.)
I initially read the comment by @BoltClock (which says that the answer is essentially wrong) and dismissed it, as I had checked my use case, and it worked. Then I realized @BoltClock had a reputation of 300,000+(!) and has a profile where he claims to be a CSS guru. Hmm, I thought, maybe I should look a little closer.
Turns out as follows: div.myclass:nth-of-type(2)
does NOT mean "the 2nd instance of div.myclass". Rather, it means "the 2nd instance of div, and it must also have the 'myclass' class". That's an important distinction when there are intervening div
s between your div.myclass
instances.
It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1
, h2
, h3
and h4
elements to essentially be div
s. I've put an A
class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?)
. (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h
level) or similar (i.e. same h
level) un-classed element into some of the groups.
Note, in particular, the last grouping of 3. Here, an un-classed h3
element is inserted between the first and second h3.A
elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A
. This shows that the n
in h3.A:nth-of-type(n)
is counting the h3
s, not the h3.A
s.
Well, hope that helps. And thanks, @BoltClock.
div {_x000D_
margin-bottom: 2em;_x000D_
border: red solid 1px;_x000D_
background-color: lightyellow;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
font-size: 12pt;_x000D_
margin: 5px;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(1),_x000D_
h2.A:nth-of-type(1),_x000D_
h3.A:nth-of-type(1) {_x000D_
background-color: cyan;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(2),_x000D_
h2.A:nth-of-type(2),_x000D_
h3.A:nth-of-type(2) {_x000D_
background-color: orange;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(3),_x000D_
h2.A:nth-of-type(3),_x000D_
h3.A:nth-of-type(3) {_x000D_
background-color: lightgreen;_x000D_
}
_x000D_
<div>_x000D_
<h1 class="A">h1.A #1</h1>_x000D_
<h1 class="A">h1.A #2</h1>_x000D_
<h1 class="A">h1.A #3</h1>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<h2 class="A">h2.A #1</h2>_x000D_
<h4>this intervening element is a different type, i.e. h4 not h2</h4>_x000D_
<h2 class="A">h2.A #2</h2>_x000D_
<h2 class="A">h2.A #3</h2>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<h3 class="A">h3.A #1</h3>_x000D_
<h3>this intervening element is the same type, i.e. h3, but has no class</h3>_x000D_
<h3 class="A">h3.A #2</h3>_x000D_
<h3 class="A">h3.A #3</h3>_x000D_
</div>
_x000D_
In my case I'm using the same markup for editing an existing entity, or creating a brand new one (so far anyway).
I want to display a default-value that is "selected" in the select-elements when in creationMode, while displaying the values form the backend in editMode.
My solution is:
<select [(ngModel)]="entity.property" id="property" name="property" required>
<option disabled hidden value="undefined">Enter prop</option>
<option *ngFor="let prop of sortedProps" value="{{prop.value}}">{{prop.displayName}}</option>
</select>
for the regular available options I'm using a sortedProps
Array to provide option choices. But that's not the important part here.
What did the trick for me is setting value="undefined"
to let the angular-model-binding (?) select this option automatically when in creationMode. Not sure if its a hack, but does exactly what i want. No addtionally typeScript necessary.
Additionally, sepcifing hidden
makes sure the option in my case is not selectable, while required
makes sure the form is invalid unless something gets selected there.
Just start emulator by command line as follow:
emulator -avd <your avd name> -partition-size 1024 -wipe-data