You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)
Explanation:
ABC: # match literal characters 'ABC:'
* # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses
* # zero or more spaces
(.+) # capture one or more of any character (except newlines)
To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+)
Use something like this -
SELECT DISTINCT COL_NAME FROM myTable WHERE UPPER(COL_NAME) LIKE UPPER('%PriceOrder%')
or
SELECT DISTINCT COL_NAME FROM myTable WHERE LOWER(COL_NAME) LIKE LOWER('%PriceOrder%')
try this one : java.net.URL;
JOptionPane.showMessageDialog(null, getDomainName(new URL("https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains")));
public String getDomainName(URL url){
String strDomain;
String[] strhost = url.getHost().split(Pattern.quote("."));
String[] strTLD = {"com","org","net","int","edu","gov","mil","arpa"};
if(Arrays.asList(strTLD).indexOf(strhost[strhost.length-1])>=0)
strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else if(strhost.length>2)
strDomain = strhost[strhost.length-3]+"."+strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else
strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
return strDomain;}
This worked for me. It also prints the output returned by the child process
child = subprocess.Popen(serial_script_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
retValRunJobsSerialScript = 0
for line in child.stdout.readlines():
child.wait()
print line
retValRunJobsSerialScript= child.returncode
Java doesn't support multiple inheritance. You can implement multiple interfaces, but not extend multiple classes.
Just click on "Build" on the top menu and then click on "Publish ".... Then a pop up will open and there u can define the folder which u want to save the .exe file and by clicking "Next" will allow u to set up the advanced settings... DONE!
Step 1 : Create file named : my_button_bg.xml
Step 2 : Place this file in res/drawables.xml
Step 3 : Insert below code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#FFFFFF"
android:endColor="#00FF00"
android:angle="270" />
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#000000" />
</shape>
Step 4: Use code "android:background="@drawable/my_button_bg" where needed eg below:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Text"
android:background="@drawable/my_button_bg"
/>
In short, yes, the order is preserved. In long:
In general the following definitions will always apply to objects like lists:
A list is a collection of elements that can contain duplicate elements and has a defined order that generally does not change unless explicitly made to do so. stacks and queues are both types of lists that provide specific (often limited) behavior for adding and removing elements (stacks being LIFO, queues being FIFO). Lists are practical representations of, well, lists of things. A string can be thought of as a list of characters, as the order is important ("abc" != "bca"
) and duplicates in the content of the string are certainly permitted ("aaa"
can exist and != "a"
).
A set is a collection of elements that cannot contain duplicates and has a non-definite order that may or may not change over time. Sets do not represent lists of things so much as they describe the extent of a certain selection of things. The internal structure of set, how its elements are stored relative to each other, is usually not meant to convey useful information. In some implementations, sets are always internally sorted; in others the ordering is simply undefined (usually depending on a hash function).
Collection is a generic term referring to any object used to store a (usually variable) number of other objects. Both lists and sets are a type of collection. Tuples and Arrays are normally not considered to be collections. Some languages consider maps (containers that describe associations between different objects) to be a type of collection as well.
This naming scheme holds true for all programming languages that I know of, including Python, C++, Java, C#, and Lisp (in which lists not keeping their order would be particularly catastrophic). If anyone knows of any where this is not the case, please just say so and I'll edit my answer. Note that specific implementations may use other names for these objects, such as vector in C++ and flex in ALGOL 68 (both lists; flex is technically just a re-sizable array).
If there is any confusion left in your case due to the specifics of how the +
sign works here, just know that order is important for lists and unless there is very good reason to believe otherwise you can pretty much always safely assume that list operations preserve order. In this case, the +
sign behaves much like it does for strings (which are really just lists of characters anyway): it takes the content of a list and places it behind the content of another.
If we have
list1 = [0, 1, 2, 3, 4]
list2 = [5, 6, 7, 8, 9]
Then
list1 + list2
Is the same as
[0, 1, 2, 3, 4] + [5, 6, 7, 8, 9]
Which evaluates to
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Much like
"abdcde" + "fghijk"
Produces
"abdcdefghijk"
When the page first loads, have Search appear in the text box, colored gray if you want it to be.
When the input box receives focus, select all of the text in the search box so that the user can just start typing, which will delete the selected text in the process. This will also work nicely if the user wants to use the search box a second time since they won't have to manually highlight the previous text to delete it.
<input type="text" value="Search" onfocus="this.select();" />
This site always have helped me out a lot, and now it's my turn to help the others with what I know.
I hope that my code below be useful for someone.
string source_dir = @"E:\";
string destination_dir = @"C:\";
// substring is to remove destination_dir absolute path (E:\).
// Create subdirectory structure in destination
foreach (string dir in System.IO.Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories))
{
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(destination_dir, dir.Substring(source_dir.Length + 1)));
// Example:
// > C:\sources (and not C:\E:\sources)
}
foreach (string file_name in System.IO.Directory.GetFiles(source_dir, "*", System.IO.SearchOption.AllDirectories))
{
System.IO.File.Copy(file_name, System.IO.Path.Combine(destination_dir, file_name.Substring(source_dir.Length + 1)));
}
Complete example here:-
<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="./bootstrap.min.css">
<script src="./bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
</head>
<body ng-controller="myController">
<table border='1'>
<tr ng-repeat="(key,val) in collValues">
<td ng-if="!hasChildren(val)">{{key}}</td>
<td ng-if="val === 'string'">
<input type="text" name="{{key}}"></input>
</td>
<td ng-if="val === 'number'">
<input type="number" name="{{key}}"></input>
</td>
<td ng-if="hasChildren(val)" td colspan='2'>
<table border='1' ng-repeat="arrVal in val">
<tr ng-repeat="(key,val) in arrVal">
<td>{{key}}</td>
<td ng-if="val === 'string'">
<input type="text" name="{{key}}"></input>
</td>
<td ng-if="val === 'number'">
<input type="number" name="{{key}}"></input>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
<script type="text/javascript">
var app = angular.module("dashboard",[]);
app.controller("myController",function($scope){
$scope.collValues = {
'name':'string',
'id':'string',
'phone':'number',
'depart':[
{
'depart':'string',
'name':'string'
}
]
};
$scope.hasChildren = function(bigL1) {
return angular.isArray(bigL1);
}
});
</script>
</html>
The easiest way to pass additional data is to add the data to the existing ViewData for the view as @Joel Martinez notes. However, if you don't want to pollute your ViewData, RenderPartial has a method that takes three arguments as well as the two-argument version you show. The third argument is a ViewDataDictionary. You can construct a separate ViewDataDictionary just for your partial containing just the extra data that you want to pass in.
The error No provider for NameService
is a common issue that many Angular2 beginners face.
Reason: Before using any custom service you first have to register it with NgModule by adding it to the providers list:
Solution:
@NgModule({
imports: [...],
providers: [CustomServiceName]
})
Here is the sample program.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadFromConsole {
public static void main(String[] args) {
System.out.println("Enter here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String value = bufferRead.readLine();
System.out.println(value);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You can get it easily when you search in Internet. StackExchange recommends to do some research and put some effort before reaching it.
Another solution is add @JsonIgnore :
@OneToMany(mappedBy="catalog", fetch = FetchType.LAZY)
@JsonIgnore
private Set<Product> products = new HashSet<Product>(0);
Note that git checkout --ours|--theirs
will overwrite the files entirely, by choosing either theirs
or ours
version, which might be or might not be what you want to do (if you have any non-conflicted changes coming from the other side, they will be lost).
If instead you want to perform a three-way merge on the file, and only resolve the conflicted hunks using --ours|--theirs
, while keeping non-conflicted hunks from both sides in place, you may want to resort to git merge-file
; see details in this answer.
for(int i = 0; i < n; i++) {
existing_string += 'c';
}
but you should use StringBuilder instead, and save memory
int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
builder.append(" append ");
}
System.out.println(builder.toString());
CREATE TABLE `voting` (
`QuestionID` int(10) unsigned NOT NULL,
`MemberId` int(10) unsigned NOT NULL,
`vote` int(10) unsigned NOT NULL,
PRIMARY KEY (`QuestionID`,`MemberId`)
);
array_slice
returns a slice of an array
$sliced_array = array_slice($array, 0, 5)
is the code you want in your case to return the first five elements
Solution with border-collapse:separate for table and display:inline-table for tbody and thead.
table {
width: 100%;
border-collapse: separate;
border-spacing: 0px;
background: transparent;
}
table thead {
display: inline-table;
width: 100%;
background: #fc0 url(../images/bg-heading.png) repeat-x 0% 0;
-webkit-border-top-left-radius: 7px;
-moz-border-radius-topleft: 7px;
-webkit-border-top-right-radius: 7px;
-moz-border-radius-topright: 7px;
border-radius: 7px 7px 0px 0px;
padding: 1px;
padding-bottom: 0;
}
table tbody {
border: 1px solid #ddd;
display: inline-table;
width: 100%;
border-top: none;
}
so if you have a table with a row like:
firstname lastname
Bill smith
you can do something like
select firstname + ' ' + lastname from thetable
and you will get "Bill Smith"
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
This can also be done using a wrapper. Very general way of keeping time.
The wrapper in this example code wraps any function and prints the amount of time needed to execute the function:
def timethis(f):
import time
def wrapped(*args, **kwargs):
start = time.time()
r = f(*args, **kwargs)
print "Executing {0} took {1} seconds".format(f.func_name, time.time()-start)
return r
return wrapped
@timethis
def thistakestime():
for x in range(10000000):
pass
thistakestime()
Quite a while later, and thanks to @arne, I created this similar small function to handle where the input should be disabled AND hidden, or enabled AND shown:
function toggleInputState(el, on) {
// 'on' = true(visible) or false(hidden)
// If a field is to be shown, enable it; if hidden, disable it.
// Disabling will prevent the field's value from being submitted
$(el).prop('disabled', !on).toggle(on);
}
Then a jQuery object (such as $('input[name="something"]') ) is simply switched using:
toggleInputState(myElement, myBoolean)
Just simply comment out the line: ALLOWED_HOSTS = [...]
I am using fullcalendar on my project recently, I don't know what exact view effect you want to achieve, in my project I want to change the event time view from 12h format from
to 24h format.
If this is the effect you want to achieve, the solution below might help:
set timeFormat: 'H:mm'
The question won't be complete if we don't mention about alternative methods for looping through objects.
Nowadays many well known JavaScript libraries provide their own methods for iterating over collections, i.e. over arrays, objects, and array-like objects. These methods are convenient to use and are entirely compatible with any browser.
If you work with jQuery, you may use jQuery.each()
method. It can be used to seamlessly iterate over both objects and arrays:
$.each(obj, function(key, value) {
console.log(key, value);
});
In Underscore.js you can find method _.each()
, which iterates over a list of elements, yielding each in turn to a supplied function (pay attention to the order of arguments in iteratee function!):
_.each(obj, function(value, key) {
console.log(key, value);
});
Lo-Dash provides several methods for iterating over object properties. Basic _.forEach()
(or it's alias _.each()
) is useful for looping through both objects and arrays, however (!) objects with length
property are treated like arrays, and to avoid this behavior it is suggested to use _.forIn()
and _.forOwn()
methods (these also have value
argument coming first):
_.forIn(obj, function(value, key) {
console.log(key, value);
});
_.forIn()
iterates over own and inherited enumerable properties of an object, while _.forOwn()
iterates only over own properties of an object (basically checking against hasOwnProperty
function). For simple objects and object literals any of these methods will work fine.
Generally all described methods have the same behaviour with any supplied objects. Besides using native for..in
loop will usually be faster than any abstraction, such as jQuery.each()
, these methods are considerably easier to use, require less coding and provide better error handling.
Get cursor on top, where white header with file name, then press Alt. To set top menu by default always visible. You needed in top menu selected: FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false) Save it.
For a non-programmatic solution, look in the Activity Monitor. It lists the architecture of 64-bit processes as “Intel (64-bit)”.
The live
function is registering a click event handler. It'll do so every time you click the object. So if you click it twice, you're assigning two click handlers to the object. You're also assigning a click handler here:
onclick="feedback('the message html')";
And then that click handler is assigning another click handler via live()
.
Really what I think you want to do is this:
function feedback(message)
{
$('#feedback').remove();
$('.answers').append('<div id="feedback">'+message+'</div>');
}
Ok, per your comment, try taking out the onclick
part of the <a>
element and instead, putting this in a document.ready()
handler.
$('#answer').live('click',function(){
$('#feedback').remove();
$('.answers').append('<div id="feedback">'+message+'</div>');
});
You can use ng-class
to add conditional classes.
HTML
<button id="button1" ng-click="alpha = true" ng-class="{alpha: alpha}">Button</button>
In your controller (to make sure the class is not shown by default)
$scope.alpha = false;
Now, when you click the button, the $scope.alpha variable is updated and ng-class will add the 'alpha' class to your button.
Use the gca
("get current axes") helper function:
ax = plt.gca()
Example:
import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()
Typically you see this error after you have already done a redirect and then try to output some more data to the output stream. In the cases where I have seen this in the past, it is often one of the filters that is trying to redirect the page, and then still forwards through to the servlet. I cannot see anything immediately wrong with the servlet, so you might want to try having a look at any filters that you have in place as well.
Edit: Some more help in diagnosing the problem…
The first step to diagnosing this problem is to ascertain exactly where the exception is being thrown. We are assuming that it is being thrown by the line
getServletConfig().getServletContext()
.getRequestDispatcher("/GroupCopiedUpdt.jsp")
.forward(request, response);
But you might find that it is being thrown later in the code, where you are trying to output to the output stream after you have tried to do the forward. If it is coming from the above line, then it means that somewhere before this line you have either:
Good luck!
To assign value of a text box whose id is ?textbox? in jQuery please do the following
$("#textbox").val('Blah');
I converted a simple NetBeans 8 Java FXML application to the Maven-driven one. Then I got problems, because the getResource()
methods weren't able to find the .fxml files. In mine original application the fxmls were scattered through the package tree - each beside its controller class file.
After I made Clean and build in NetBeans, I checked the result .jar in the target folder - the .jar didn't contain any fxml at all. All the fxmls were strangely disappeared.
Then I put all fxmls into the resources/fxml folder and set the getResource method parameters accordingly, for example: FXMLLoader(App.class.getClassLoader().getResource("fxml/ObjOverview.fxml"));
In this case everything went OK. The fxml folder appeared int the .jar's root and it contained all my fxmls. The program was working as expected.
IUS offers an installation script for subscribing to their repository and importing associated GPG keys. Make sure you’re in your home directory, and retrieve the script using curl:
curl 'https://setup.ius.io/' -o setup-ius.sh
sudo bash setup-ius.sh
Install Required Packages-:
sudo yum install -y mod_php70u php70u-cli php70u-mysqlnd php70u-json php70u-gd php70u-dom php70u-simplexml php70u-mcrypt php70u-intl
Select Help->About
for 64 bit.. it would say version as 64 bit Edition.
I see this in IE 9.. may be true with lesser versions too..
This is how you would drop the constraint
ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO
With a script
-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)
set @database = 'dotnetnuke'
set @table = 'tabs'
DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
select @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = @database and
table_name = @table
exec sp_executesql @sql
END
Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
In case you have to replace multiple values and if you don't mind "refactoring" your variable with as.factor(as.character(...)) you could try the following:
replace.values <- function(search, replace, x){
stopifnot(length(search) == length(replace))
xnew <- replace[ match(x, search) ]
takeOld <- is.na(xnew) & !is.na(x)
xnew[takeOld] <- x[takeOld]
return(xnew)
}
iris$Species <- as.factor(search=c("oldValue1","oldValue2"),
replace=c("newValue1","newValue2"),
x=as.character(iris$Species))
As the error says Failed to find build Tools revision 23.0.1 This means that in your project you have used buildToolsVersion "23.0.3" So,You need to download the exact same version this makes the error disappear
**Step 1:** GO to Tools and click SDK Manager **Step 2:** you can see SDK Platforms ,SDK Tools and SDK update Sites **Step3:** Click SDK Tools and click show package details **Step 4:** Select the version that you have mentioned in your Project These Steps has solved my issue.
You can create an array that includes the filetype that is needed and use $.inArray() in jQuery to check if filetype exist in array.
var imageType = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
// Given that file is a file object and file.type is string
// like "image/jpeg", "image/png", or "image/gif" and so on...
if (-1 == $.inArray(file.type.split('/')[1], imageType)) {
console.log('Not an image type');
}
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
Something like this worked for me. I am guessing this should work for you.
Run webpack-dev using this
webpack-dev-server --host 0.0.0.0 --port 80
And set this in webpack.config.js
entry: [
'webpack-dev-server/client?http://0.0.0.0:80',
config.paths.demo
]
Note If you are using hot loading, you will have to do this.
Run webpack-dev using this
webpack-dev-server --host 0.0.0.0 --port 80
And set this in webpack.config.js
entry: [
'webpack-dev-server/client?http://0.0.0.0:80',
'webpack/hot/only-dev-server',
config.paths.demo
],
....
plugins:[new webpack.HotModuleReplacementPlugin()]
You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.
My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries.
Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID
WHERE p.isactive = 1
The better version of this query is :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1
(Assuming isactive is a field in product table which represents the active/inactive products).
This code worked for me. I use ojdbc6-11.2.0.2.jar.
java.sql.Connection con;
javax.xml.bind.Marshaller marshaller;
Clob xmlClob = con.createClob();
try {
try (Writer xmlClobWriter = xmlClob.setCharacterStream(1)) {
m.marshal(jaxbObject, xmlClobWriter);
} // xmlClobWriter.close();
try (PreparedStatement stmt = con.prepareStatement("INSERT INTO table (xml) values(?)")) {
stmt.setClob(1, xmlClob);
stmt.executeUpdate();
}
} finally {
xmlClob.free();
}
If the list is sorted (as happens to be in the example) a binary search on index certainly works.
public static Dog Find(List<Dog> AllDogs, string Id)
{
int p = 0;
int n = AllDogs.Count;
while (true)
{
int m = (n + p) / 2;
Dog d = AllDogs[m];
int r = string.Compare(Id, d.Id);
if (r == 0)
return d;
if (m == p)
return null;
if (r < 0)
n = m;
if (r > 0)
p = m;
}
}
Not sure what the LINQ version of this would be.
db.adminCommand( { getLog: "*" } )
Then
db.adminCommand( { getLog : "global" } )
In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.
Here's something you might want to do:
public class Foo
{
public void fee()
{
//do stuff
}
public static void main (String[]arg)
{
Foo foo = new Foo();
foo.fee();
}
}
Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.
You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.
os.rename(old, new)
This is found in the Python docs: http://docs.python.org/library/os.html
I had similar issue, but in the end I found out that ~/.bashrc was all I needed.
However, in Ubuntu, I had to comment the line that stops processing ~/.bashrc :
#If not running interactively, don't do anything
[ -z "$PS1" ] && return
In short: SID = the unique name of your DB, ServiceName = the alias used when connecting
Not strictly true. SID = unique name of the INSTANCE (eg the oracle process running on the machine). Oracle considers the "Database" to be the files.
Service Name = alias to an INSTANCE (or many instances). The main purpose of this is if you are running a cluster, the client can say "connect me to SALES.acme.com
", the DBA can on the fly change the number of instances which are available to SALES.acme.com
requests, or even move SALES.acme.com
to a completely different database without the client needing to change any settings.
foo="Hello"
foo="${foo} World"
echo "${foo}"
> Hello World
In general to concatenate two variables you can just write them one after another:
a='Hello'
b='World'
c="${a} ${b}"
echo "${c}"
> Hello World
I was able to generate
static {
WSDL_LOCATION = null;
}
by configuring pom file to have a null for wsdlurl:
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${basedir}/target/generated/src/main/java</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/service.wsdl</wsdl>
<extraargs>
<extraarg>-client</extraarg>
<extraarg>-wsdlLocation</extraarg>
<wsdlurl />
</extraargs>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
I just stumbled onto this while searching for this answer. If you are using intellij, you can navigate to the file location, but opening the external lib folder in the project explorer, right clicking on the jar, and select Open Library Settings.
Update : In angular 7, they are the same as 6
In angular 6
the complete answer found in live example
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);
}
it's because of pipeable/lettable operators
which now angular is able to use tree-shakable
and remove unused imports and optimize the app
some rxjs functions are changed
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
more in MIGRATION
and Import paths
For JavaScript developers, the general rule is as follows:
rxjs: Creation methods, types, schedulers and utilities
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';
rxjs/operators: All pipeable operators:
import { map, filter, scan } from 'rxjs/operators';
rxjs/webSocket: The web socket subject implementation
import { webSocket } from 'rxjs/webSocket';
rxjs/ajax: The Rx ajax implementation
import { ajax } from 'rxjs/ajax';
rxjs/testing: The testing utilities
import { TestScheduler } from 'rxjs/testing';
and for backward compatability you can use rxjs-compat
The following CSS code works almost modern browser:
.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
}
For IE, you must use JS or insert attribute in html tag.
<div id="foo" unselectable="on" class="unselectable">...</div>
You can always wrap Double.parseDouble() in a try catch block.
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}
dependencies: compile 'com.android.support:cardview-v7:23.1.1'
<android.support.v7.widget.CardView
android:layout_width="80dp"
android:layout_height="80dp"
android:elevation="12dp"
android:id="@+id/view2"
app:cardCornerRadius="40dp"
android:layout_centerHorizontal="true"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="1.9">
<ImageView
android:layout_height="80dp"
android:layout_width="match_parent"
android:id="@+id/imageView1"
android:src="@drawable/Your_image"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
</android.support.v7.widget.CardView>
So it would become:
List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
Iterator<Integer> myListIterator = myCoords.iterator();
while (myListIterator.hasNext()) {
Integer coord = myListIterator.next();
System.out.print("\r" + coord);
try{
Thread.sleep(2000);
}catch(Exception e){
// handle the exception...
}
}
}
Array['key'] = value;
$data['cat'] = 'wagon';
This is what you need. No need to use array_push() function for this. Some time the problem is very simple and we think in complex way :) .
Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz"
but only sees "abcd...wxy
.
This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.
One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage
:
chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
console.log(data);
});
Now before your callback is called, the browser would attempt to parse the message using JSON.parse
which can give you "unexpected end of input" errors if the supplied byte length does not match the data.
I have used this code to compare two list which has million of records.
This method will not take much time
//Method to compare two list of string
private List<string> Contains(List<string> list1, List<string> list2)
{
List<string> result = new List<string>();
result.AddRange(list1.Except(list2, StringComparer.OrdinalIgnoreCase));
result.AddRange(list2.Except(list1, StringComparer.OrdinalIgnoreCase));
return result;
}
I guess the dirtiest solution is this:
list(eval('0, 0, 0, 11, 0, 0, 0, 11'))
Just simply try the following if you don't need to care about efficiency.
zip -r foo.zip foo/*
unzip -LL foo.zip
What's the difference between VARCHAR and CHAR in MySQL?
To already given answers I would like to add that in OLTP systems or in systems with frequent updates consider using CHAR
even for variable size columns because of possible VARCHAR
column fragmentation during updates.
I am trying to store MD5 hashes.
MD5 hash is not the best choice if security really matters. However, if you will use any hash function, consider BINARY
type for it instead (e.g. MD5 will produce 16-byte hash, so BINARY(16)
would be enough instead of CHAR(32)
for 32 characters representing hex digits. This would save more space and be performance effective.
removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.
I can't think of anything that would be able to handle this out of the box. But it's fairly well handled for floating point numbers.
>>> round(1.2322, 2)
1.23
Integers are trickier. They're not stored as base 10 in memory, so significant places isn't a natural thing to do. It's fairly trivial to implement once they're a string though.
Or for integers:
>>> def intround(n, sigfigs):
... n = str(n)
... return n[:sigfigs] + ('0' * (len(n)-(sigfigs)))
>>> intround(1234, 1)
'1000'
>>> intround(1234, 2)
If you would like to create a function that handles any number, my preference would be to convert them both to strings and look for a decimal place to decide what to do:
>>> def roundall1(n, sigfigs):
... n = str(n)
... try:
... sigfigs = n.index('.')
... except ValueError:
... pass
... return intround(n, sigfigs)
Another option is to check for type. This will be far less flexible, and will probably not play nicely with other numbers such as Decimal
objects:
>>> def roundall2(n, sigfigs):
... if type(n) is int: return intround(n, sigfigs)
... else: return round(n, sigfigs)
My solution was use readAsBinaryString()
and btoa()
on its result.
uploadFileToServer(event) {
var file = event.srcElement.files[0];
console.log(file);
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
console.log(btoa(reader.result));
};
reader.onerror = function() {
console.log('there are some problems');
};
}
application/xml
is seen by svn
as binary type whereas text/xml
as text file for which a diff can be displayed.
In react, state will not change until you do it by using this.setState({});
.
That is why your console message showing old values.
It's pandas
label-based selection, as explained here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label
The boolean array is basically a selection method using a mask.
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.
If you want a more "JSONish" response page you can try something like that:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RestController
@RequestMapping("/error")
public class SimpleErrorController implements ErrorController {
private final ErrorAttributes errorAttributes;
@Autowired
public SimpleErrorController(ErrorAttributes errorAttributes) {
Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
this.errorAttributes = errorAttributes;
}
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping
public Map<String, Object> error(HttpServletRequest aRequest){
Map<String, Object> body = getErrorAttributes(aRequest,getTraceParameter(aRequest));
String trace = (String) body.get("trace");
if(trace != null){
String[] lines = trace.split("\n\t");
body.put("trace", lines);
}
return body;
}
private boolean getTraceParameter(HttpServletRequest request) {
String parameter = request.getParameter("trace");
if (parameter == null) {
return false;
}
return !"false".equals(parameter.toLowerCase());
}
private Map<String, Object> getErrorAttributes(HttpServletRequest aRequest, boolean includeStackTrace) {
RequestAttributes requestAttributes = new ServletRequestAttributes(aRequest);
return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
}
}
I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )
Anyway, coming to the solution, this is what I was required to do:
su -
gedit /etc/phpMyAdmin/config.inc.php
if not found... try phpmyadmin - all small caps.
gedit /etc/phpmyadmin/config.inc.php
Locate
$cfg['Servers'][$i]['AllowNoPassword']
and set it to:
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
Save it.
I believe you want to use confirm()
<script type="text/javascript">
function clicked() {
if (confirm('Do you want to submit?')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
Here below my code which works fine.
const fs = require('fs');
fs.unlink(__dirname+ '/test.txt', function (err) {
if (err) {
console.error(err);
}
console.log('File has been Deleted');
});
This worked for me.
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// disable swipe
if(!swipeEnabled) {
if (viewPager.getAdapter().getCount()>1) {
viewPager.setCurrentItem(1);
viewPager.setCurrentItem(0);
}
}
}
public void onPageScrollStateChanged(int state) {}
public void onPageSelected(int position) {}
};
viewPager.addOnPageChangeListener(onPageChangeListener);
I see a lot of responses that recommend just using a ForegroundService. In order to use a ForegroundService there has to be a notification associated with it. Users will see this notification. Depending on the situation, they may become annoyed with your app and uninstall it.
The easiest solution is to use the new Architecture Component called WorkManager. You can check out the documentation here: https://developer.android.com/topic/libraries/architecture/workmanager/
You just define your worker class that extends Worker.
public class CompressWorker extends Worker {
public CompressWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}
@Override
public Worker.Result doWork() {
// Do the work here--in this case, compress the stored images.
// In this example no parameters are passed; the task is
// assumed to be "compress the whole library."
myCompress();
// Indicate success or failure with your return value:
return Result.SUCCESS;
// (Returning RETRY tells WorkManager to try this task again
// later; FAILURE says not to try again.)
}
}
Then you schedule when you want to run it.
OneTimeWorkRequest compressionWork =
new OneTimeWorkRequest.Builder(CompressWorker.class)
.build();
WorkManager.getInstance().enqueue(compressionWork);
Easy! There are a lot of ways you can configure workers. It supports recurring jobs and you can even do complex stuff like chaining if you need it. Hope this helps.
You haven't specify version in your maven dependency file may be thats why it is not picking the latest jar
As well as you need another deppendency with slf4j-log4j12
artifact id.
Include this in your pom file
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
Let me know if error is still not resolved
I also recomend you to see this link
Click File >> Recent Projects > and you should be able to use edit it again. Hope it helps :)
def deleteDir(dirPath):
deleteFiles = []
deleteDirs = []
for root, dirs, files in os.walk(dirPath):
for f in files:
deleteFiles.append(os.path.join(root, f))
for d in dirs:
deleteDirs.append(os.path.join(root, d))
for f in deleteFiles:
os.remove(f)
for d in deleteDirs:
os.rmdir(d)
os.rmdir(dirPath)
You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:
JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);
Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});
if you are a sudo user i mean if you got sudo access:
sudo sh startup.sh
otherwise: sh startup.sh
But things is that you have to be on the bin directory of your server like
cd /home/nanofaroque/servers/apache-tomcat-7.0.47/bin
Since Angular version 6 .angular-cli.json
is deprecated. That file was replaced by angular.json
file which supports workspaces.
How about this way?
package main
import (
"fmt"
"errors"
)
type Item struct {
Value int
Name string
}
var items []Item = []Item{{Value:0, Name:"zero"},
{Value:1, Name:"one"},
{Value:2, Name:"two"}}
func main() {
var err error
v := Get(3, &err).Value
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v)
}
func Get(value int, err *error) Item {
if value > (len(items) - 1) {
*err = errors.New("error")
return Item{}
} else {
return items[value]
}
}
You need to declare the array in the HTML via
<input type="checkbox" name="Days[]" value="Daily">
Also you can insert multiple items with one query like this
$query = "INSERT INTO example (orange) VALUES ";
for ($i=0; $i<count($checkBox); $i++)
$query .= "('" . $checkBox[$i] . "'),";
$query = rtrim($query,',');
mysql_query($query) or die (mysql_error() );
Also keep in mind that mysql_*
functions are officially deprecated and hence should not be used in new code. You can use PDO or MySQLi instead. See this answer on SO for more information.
maybe there are some unmerged paths in your git repository that you have to resolve before stashing.
If ayman's solution doesn't work, try naming your file .profile
instead of .bash_profile
. That worked for me.
You can use set -e
as a prefix for the for-loop. Example:
all:
set -e; for a in 1 2 3; do /bin/false; echo $$a; done
make
will exit immediately with an exit code <> 0
.
You go into ~/.janus
and run:
git submodule add <git@github ...> snipmate-snippets/snippets/
If you need more information about submodules (or git in general) ProGit is pretty useful.
Another option is an interesting open source project called ScriptCS. It uses some crafty techniques to allow you a development experience outside of Visual Studio while still being able to leverage NuGet to manage your dependencies. It's free, very easy to install using Chocolatey. You can check it out here http://scriptcs.net.
Another cool feature it has is the REPL from the command line. Which allows you to do stuff like this:
C:\> scriptcs
scriptcs (ctrl-c or blank to exit)
> var message = "Hello, world!";
> Console.WriteLine(message);
Hello, world!
>
C:\>
You can create C# utility "scripts" which can be anything from small system tasks, to unit tests, to full on Web APIs. In the latest release I believe they're also allowing for hosting the runtime in your own apps.
Check out it development on the GitHub page too https://github.com/scriptcs/scriptcs
As the other answers said, the function you need is cv2.rectangle()
, but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top)
and (right, bottom)
. Or, equivalently, (xmin, ymin)
and (xmax, ymax)
.
If you want your form's field clear, you must only add a delay in the onClick event like:
<input name="submit" id="MyButton" type="submit" class="btn-lg" value="ClickMe" onClick="setTimeout('clearform()', 2000 );"
onClick="setTimeout('clearform()', 1500 );" . in 1,5 seconds its clear
document.getElementById("name").value = ""; <<<<<<just correct this
document.getElementById("telephone").value = ""; <<<<<correct this
By clearform()
, I mean your clearing-fields function.
if you need to find square root without using sqrt()
,use root=pow(x,0.5)
.
Where x is value whose square root you need to find.
For debugging purposes, you can use the DLL file. You can run it using dotnet ConsoleApp2.dll
. If you want to generate an EXE file, you have to generate a self-contained application.
To generate a self-contained application (EXE in Windows), you must specify the target runtime (which is specific to the operating system you target).
Pre-.NET Core 2.0 only: First, add the runtime identifier of the target runtimes in the .csproj file (list of supported RIDs):
<PropertyGroup>
<RuntimeIdentifiers>win10-x64;ubuntu.16.10-x64</RuntimeIdentifiers>
</PropertyGroup>
The above step is no longer required starting with .NET Core 2.0.
Then, set the desired runtime when you publish your application:
dotnet publish -c Release -r win10-x64
dotnet publish -c Release -r ubuntu.16.10-x64
var res = exitDictionary
.Select(p => p.Value).Cast<Dictionary<string, object>>()
.SelectMany(d => d)
.Where(p => p.Key == "fieldname1")
.Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
.SelectMany(l => l)
.SelectMany(d=> d)
.Where(p => p.Key == "valueTitle")
.Select(p => p.Value)
.ToList();
This also works, and easy to understand.
If someone is using column names like "key"
or "value"
, then you still see the same error that your mysql query syntax is bad. This should fix:
.where("`key` LIKE ?", "%#{key}%")
Copy of one list into second is quite simple , you can do that as below:-
ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);
For anyone looking for a web-enabled client for Postgres, I'll just put the link out here to TeamPostgreSQL, a very polished AJAX web client for pg:
You have the wrong table set on the command. You should use the following on your setup:
ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;
constexpr indicates a value that's constant and known during compilation.
const indicates a value that's only constant; it's not compulsory to know during compilation.
int sz;
constexpr auto arraySize1 = sz; // error! sz's value unknown at compilation
std::array<int, sz> data1; // error! same problem
constexpr auto arraySize2 = 10; // fine, 10 is a compile-time constant
std::array<int, arraySize2> data2; // fine, arraySize2 is constexpr
Note that const doesn’t offer the same guarantee as constexpr, because const objects need not be initialized with values known during compilation.
int sz;
const auto arraySize = sz; // fine, arraySize is const copy of sz
std::array<int, arraySize> data; // error! arraySize's value unknown at compilation
All constexpr objects are const, but not all const objects are constexpr.
If you want compilers to guarantee that a variable has a value that can be used in contexts requiring compile-time constants, the tool to reach for is constexpr, not const.
date('Y-m-d H:i:s')
. See the manual for more.
+=
in JavaScript (as well as in many other languages) adds the right hand side to the variable on the left hand side, storing the result in that variable. Your example of 1 +=2
therefore does not make sense. Here is an example:
var x = 5;
x += 4; // x now equals 9, same as writing x = x + 4;
x -= 3; // x now equals 6, same as writing x = x - 3;
x *= 2; // x now equals 12, same as writing x = x * 2;
x /= 3; // x now equals 4, same as writing x = x / 3;
In your specific example the loop is summing the numbers in the array data
.
Dim myStringArray() As String
*code*
redim myStringArray(size_of_your_array)
Then you can do something static like this:
myStringArray = { item_1, item_2, ... }
Or something iterative like this:
Dim x
For x = 0 To size_of_your_array
myStringArray(x) = data_source(x).Name
Next x
" Hello " , " This " , "is ", "Sorting ", "Example"
First of all you provided spaces in " Hello "
and " This "
, spaces have a lower value than alphabetic characters in Unicode, so it gets printed first. (The rest of the characters were sorted alphabetically).
Now upper case letters have a lower value than lower case letter in Unicode, so "Example" and "Sorting" gets printed, then at last "is "
which has the highest value.
In addition to the answer already accepted, for the scenario when you want to define a default property as a function of other properties you can use expression body notation on C#6.0 (and higher) for even more elegant and concise constructs like:
public class Person{
public string FullName => $"{First} {Last}"; // expression body notation
public string First { get; set; } = "First";
public string Last { get; set; } = "Last";
}
You can use the above in the following fashion
var p = new Person();
p.FullName; // First Last
p.First = "Jon";
p.Last = "Snow";
p.FullName; // Jon Snow
In order to be able to use the above "=>" notation, the property must be read only, and you do not use the get accessor keyword.
Details on MSDN
In Java its Webelement.getText() . Not sure about python.
The string
class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
// or
str = arr;
In the MongoDB shell:
db.getCollection('sensorevents').find({from:{$gt: new ISODate('2015-08-30 16:50:24.481Z')}})
In my nodeJS code ( using Mongoose )
SensorEvent.Model.find( {
from: { $gt: new Date( SensorEventListener.lastSeenSensorFrom ) }
} )
I am querying my sensor events collection to return values where the 'from' field is greater than the given date
Visual Paradigm SDE for IntellIJ (Community edition) Modelling Case Tool
You need to install proper software. Now it should works well.
I guess that UML Class Diagram is only available on Ultimate Edition.
To show UML diagram click right mouse button on specific class -> Diagrams -> Show diagram... Or you can in editor click Ctrl+Alt+Shift+U. You could append new classes to diagram by drag and drop. On the top of window you could choose more options. To save UML you should just click on save icon.
The ~/Library/Developer/Xcode/iOS DeviceSupport
folder is basically only needed to symbolicate crash logs.
You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.
I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.
Try to put this in your CSS file.
td {
text-align: center;
vertical-align: middle;
}
You have an error in your syntax here:
this._possessions = new Thing[100]();
This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:
this._possessions = [];
Of the array constructor if you want to set the length:
this._possessions = new Array(100);
I have created a brief working example you can try in the playground.
module Entities {
class Thing {
}
export class Person {
private _name: string;
private _possessions: Thing[];
private _mostPrecious: Thing;
constructor (name: string) {
this._name = name;
this._possessions = [];
this._possessions.push(new Thing())
this._possessions[100] = new Thing();
}
}
}
Use window.open()
:
var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
Depending on the browsers implementation this will work
There is nothing you can do to make it open in a window rather than a tab.
Unfortunately DEBUG
is overloaded heavily. For instance, it's recommended to always generate and save a pdb file for RELEASE builds. Which means one of the -Zx
flags, and -DEBUG
linker option. While _DEBUG
relates to special debug versions of runtime library such as calls to malloc
and free
. Then NDEBUG
will disable assertions.
we can use javascript code
function validateAlphaNumericCode(event) {
keyEntry = (event.which) ? event.which : event.keyCode
if (((keyEntry >= '65') && (keyEntry <= '90')) || ((keyEntry >= '97') && (keyEntry <= '122')) || (keyEntry == '37') || (keyEntry == '39') || (keyEntry == '46') || (keyEntry == '8') || (keyEntry == '9') || (keyEntry == '95') || ((keyEntry >= '48') && (keyEntry <= '57')))
return true;
else
return false;
}
validate this code with your textbox.
You mean InputBox? Just look in the Microsoft.VisualBasic namespace.
C# and VB.Net share a common library. If one language can use it, so can the other.
I think you need quotes around your {$row['null_field']}
, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',)
which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
When I had this, problem, the cause was the ordering of the libraries. To fix it, I put libboost_system
last:
g++ mingw/timer1.o -o mingw/timer1.exe -L/usr/local/boost_1_61_0/stage/lib \
-lboost_timer-mgw53-mt-1_61 \
-lboost_chrono-mgw53-mt-1_61 \
-lboost_system-mgw53-mt-1_61
This was on mingw with gcc 5.3 and boost 1.61.0 with a simple timer example.
The simplest non recursive way is:
for d in */; do
echo "$d"
done
The /
at the end tells, use directories only.
There is no need for
DECLARE @i AS FLOAT = 2 SELECT @i / 3 SELECT cast(@i / cast(3 AS DECIMAL(18,2))as decimal (18,2))
Both factor and result requires casting to be considered as decimals.
Use This Within button on Click option or your needs:
final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setTitle("ProgressDialog"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
This is a bit of a cheat but I just set a default style and then overrode it using a DataTrigger if the value is null...
<Style>
<!-- Highlight for Reviewed (Default) -->
<Setter Property="Control.Background" Value="PaleGreen" />
<Style.Triggers>
<!-- Highlight for Not Reviewed -->
<DataTrigger Binding="{Binding Path=REVIEWEDBY}" Value="{x:Null}">
<Setter Property="Control.Background" Value="LightIndianRed" />
</DataTrigger>
</Style.Triggers>
</Style>
Have you checked strncpy?
char * strncpy ( char * destination, const char * source, size_t num );
You must realize that begin and end actually defines a num of bytes to be copied from one place to another.
Building on Preet Sangha's solution, the following should safely cover the scenario where you're working with a large solution with the potential for several Inner Exceptions.
try
{
object result = processClass.InvokeMethod("Create", methodArgs);
}
catch (Exception e)
{
// Here I was hoping to get an error code.
if (ExceptionContainsErrorCode(e, 10004))
{
// Execute desired actions
}
}
...
private bool ExceptionContainsErrorCode(Exception e, int ErrorCode)
{
Win32Exception winEx = e as Win32Exception;
if (winEx != null && ErrorCode == winEx.ErrorCode)
return true;
if (e.InnerException != null)
return ExceptionContainsErrorCode(e.InnerException, ErrorCode);
return false;
}
This code has been unit tested.
I won't harp too much on the need for coming to appreciate and implement good practice when it comes to Exception Handling by managing each expected Exception Type within their own blocks.
This is a simple loop that keeps prompting unless the user selects 'y' or 'n'
$confirmation = Read-Host "Ready? [y/n]"
while($confirmation -ne "y")
{
if ($confirmation -eq 'n') {exit}
$confirmation = Read-Host "Ready? [y/n]"
}
I had the same problem with Microsoft Visual Studio 2010 Ultimate and it was solved by the method described in this youtube video
The video suggests to rename the file cvtres.exe in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin (in my Win7X64 matchine)
to cvtres-old.exe
The options for managing tablespaces have got a lot better over the versions starting with 8i. This is especially true if you are using the appropriate types of file for a temporary tablespace (i.e. locally managed tempfiles).
So, it could be as simple as this command, which will shrink your tablespace to 128 meg...
alter tablespace <your_temp_ts> shrink space keep 128M;
The Oracle online documentation is pretty good. Find out more.
edit
It would appear the OP has an earlier version of the database. With earlier versions we have to resize individual datafiles. So, first of all, find the file names. One or other of these queries should do it...
select file_name from dba_data_files where tablespace_name = '<your_temp_ts>'
/
select file_name from dba_temp_files where tablespace_name = '<your_temp_ts>'
/
Then use that path in this command:
alter database datafile '/full/file/path/temp01.dbf' resize 128m
/
An example using built in TimeUnit
.
long uptime = System.currentTimeMillis();
long days = TimeUnit.MILLISECONDS
.toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS
.toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS
.toMinutes(uptime);
uptime -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS
.toSeconds(uptime);
Thanks for that info on the ControlToValidate LukeH!
What I was trying to do in my code was to only ensure that some text field A has some text in the field when text field B has a particular value. Otherwise, A can be blank or whatever else. Getting rid of the ControlToValidate="A" in my mark up fixed the issue for me.
Cheers!
You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
}
}
}
Try to modify the eclipse.ini
so that both Xms
and Xmx
are of the same value:
-Xms6000m
-Xmx6000m
This should force the Eclipse's VM to allocate 6GB
of heap right from the beginning.
But be careful about either using the eclipse.ini
or the command-line ./eclipse/eclipse -vmargs ...
. It should work in both cases but pick one and try to stick with it.
Had the same problem....managed to get it to work after a little while.
Thing to do is follow instructions on installing FFmpeg - which is (at least on windows) a bundle of executables you need to set a path to in your environment variables
http://www.wikihow.com/Install-FFmpeg-on-Windows
Hope this helps someone - even after a while after the question - good luck
Add the function ob_end_clean() before call the Output function.
In order to do the database style ComboBoxes manually trying to setup a relationship between a number (internal) and some text (visible), I've found you have to:
First things first. Change your KeyValuePair to so it looks like:
(0,"Select") (1,"Option 1")
Now, when you run your sql "Select empstatus from employees where blah" and get back an integer, you need to set the combobox without wasting a bunch of time.
Simply: *** SelectedVALUE - not Item ****
cmbEmployeeStatus.SelectedValue = 3; //or
cmbEmployeeStatus.SelectedValue = intResultFromQuery;
This will work whether you have manually loaded the combobox with code values, as you did, or if you load the comboBox from a query.
If your foreign keys are integers, (which for what I do, they all are), life is easy. After the user makes the change to the comboBox, the value you will store in the database is SelectedValue. (Cast to int as needed.)
Here is my code to set the ComboBox to the value from the database:
if (t is DBInt) //Typical for ComboBox stuff
{
cb.SelectedValue = ((DBInt)t).value;
}
And to retrieve:
((DBInt)t).value = (int) cb.SelectedValue;
DBInt is a wrapper for an Integer, but this is part of my ORM that gives me manual control over databinding, and reduces code errors.
Why did I answer this so late? I was struggling with this also, as there seems to be no good info on the web about how to do this. I figured it out, and thought I'd be nice and post it for someone else to see.
Are you targeting the android.R or the one in your own project?
Are you sure your own R.java file is generated? Mistakes in your xml views could cause the R.java not to be generated. Go through your view files and make sure all the xml is right!
Take a look at LinkedHashSet class
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.).
This can be achieved using awk
Below Line will display unique Values
awk file_name | uniq
You can output these unique values to a new file
awk file_name | uniq > uniq_file_name
new file uniq_file_name will contain only Unique values, no duplicates
bin
folder to your PATH environment variablecd
to the place where you want to download (i.e checkout) the projects' code.The European Central Bank (ECB) also has the most reliable free feed that I know of. It contains approx 28 currencies and is updated at least daily.
http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
For more formats and tools see the ECB reference page: http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
var arr = [1, 2, 3]_x000D_
_x000D_
// ES5 syntax_x000D_
arr = arr.filter(function(item){ return item != 3 })_x000D_
_x000D_
// ES2015 syntax_x000D_
arr = arr.filter(item => item != 3)_x000D_
_x000D_
console.log( arr )
_x000D_
You need to use a regular expression, so that you can specify the global (g) flag:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
(I removed the $()
around the string, as replace
is not a jQuery method, so that won't work at all.)
One use where I found CTE's excelled performance wise was where I needed to join a relatively complex Query on to a few tables which had a few million rows each.
I used the CTE to first select the subset based of the indexed columns to first cut these tables down to a few thousand relevant rows each and then joined the CTE to my main query. This exponentially reduced the runtime of my query.
Whilst results for the CTE are not cached and table variables might have been a better choice I really just wanted to try them out and found the fit the above scenario.
with underscore i had to use String() in the iteratee function
function isUniq(item) {
return String(item.user);
}
var myUniqArray = _.uniq(myArray, isUniq);
I think the most elegant solution is to pass a lambda function to "type", as mentioned by Chepner. In addition to this, if you do not know beforehand what the delimiter of your list will be, you can also pass multiple delimiters to re.split:
# python3 test.py -l "abc xyz, 123"
import re
import argparse
parser = argparse.ArgumentParser(description='Process a list.')
parser.add_argument('-l', '--list',
type=lambda s: re.split(' |, ', s),
required=True,
help='comma or space delimited list of characters')
args = parser.parse_args()
print(args.list)
# Output: ['abc', 'xyz', '123']
{ }
-->
defines scope, so if(a==1) { int b = 10; }
says, you are defining int b, for {}- this scope. For
if(a==1)
int b =10;
there is no scope. And you will not be able to use b
anywhere.
You are correct in thinking that display
is not animatable. It won't work, and you shouldn't bother including it in keyframe animations.
visibility
is technically animatable, but in a round about way. You need to hold the property for as long as needed, then snap to the new value. visibility
doesn't tween between keyframes, it just steps harshly.
.ele {_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
_x000D_
background-color: #ff6699;_x000D_
animation: 1s fadeIn;_x000D_
animation-fill-mode: forwards;_x000D_
_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
99% {_x000D_
visibility: hidden;_x000D_
}_x000D_
100% {_x000D_
visibility: visible;_x000D_
}_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
If you want to fade, you use opacity
. If you include a delay, you'll need visibility
as well, to stop the user from interacting with the element while it's not visible.
.ele {_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
_x000D_
background-color: #ff6699;_x000D_
animation: 1s fadeIn;_x000D_
animation-fill-mode: forwards;_x000D_
_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
100% {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
Both examples use animation-fill-mode
, which can hold an element's visual state after an animation ends.
SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;
This would return all rows with highest id
, in case id
column is not constrained to be unique.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.standingsButton) {
startActivity(new Intent(MainActivity.this,StandingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
You can use:
overflow:hidden;
to hide the text outside the zone.
Note that it may cut the last letter (so a part of the last letter will still be displayed). A nicer way is to display an ellipsis at the end. You can do it by using text-overflow
:
overflow: hidden;
white-space: nowrap; /* Don't forget this one */
text-overflow: ellipsis;
All the setting are stored in .metadata file in your workspace delete this and you are good to go
At last i did it Thanks alot friends, and a special thanks to Mr https://stackoverflow.com/users/87015/salman-a because of his code i was able to solve it properly. finally my code is looking like this as i am using groovy grails i hope this will help somebody there.. Thanks alot
html code looks like this in my gsp page
<input id="populate-dropdown" name="nameofClient" type="text">
<input id="wilhaveid" name="idofclient" type="text">
script Function is like this in my gsp page
<script>
$( "#populate-dropdown").on('input', function() {
$.ajax({
url:'autoCOmp',
data: {inputField: $("#populate-dropdown").val()},
success: function(resp){
$('#populate-dropdown').autocomplete({
source:resp,
select: function (event, ui) {
$("#populate-dropdown").val(ui.item.label);
$("#wilhaveid").val(ui.item.value);
return false;
}
})
}
});
});
</script>
And my controller code is like this
def autoCOmp(){
println(params)
def c = Client.createCriteria()
def results = c.list {
like("nameOfClient", params.inputField+"%")
}
def itemList = []
results.each{
itemList << [value:it.id,label:it.nameOfClient]
}
println(itemList)
render itemList as JSON
}
One more thing i have not set id field hidden because at first i was checking that i am getting the exact id , you can keep it hidden just put type=hidden instead of text for second input item in html
Thanks !
Since my other answer was obviously not well understood, here's a second attempt:
There's two approaches to answer the question.
Forget about the :after
pseudo-selector, and go for something like
.pdflink {
min-height: 20px;
padding-right: 10px;
background-position: right bottom;
background-size: 10px 20px;
background-repeat: no-repeat;
}
The question is: Can you style generated content? The answer is: No, you can't. There's been a lengthy discussion on the W3C mailing list on this issue, but no solution so far.
Generated content is rendered into a generated box, and you can style that box, but not the content as such. Different browsers show very different behaviour
#foo {content: url("bar.jpg"); width: 42px; height:42px;} #foo::before {content: url("bar.jpg"); width: 42px; height:42px;}
Chrome resizes the first one, but uses the intrinsic dimensions of the image for the second
firefox and ie don't support the first, and use intrinsic dimensions for the second
opera uses intrinsic dimensions for both cases
(from http://lists.w3.org/Archives/Public/www-style/2011Nov/0451.html )
Similarly, browsers show very different results on things like http://jsfiddle.net/Nwupm/1/ , where more than one element is generated. Keep in mind that CSS3 is still in early development stage, and this issue has yet to be solved.
I would do something like:
select
A.id, A.age, B.count
from
students A,
(select age, count(*) as count from students group by age) B
where A.age=B.age;
As @Musa comments it, it seems that the reason is that:
Postman doesn't care about SOP, it's a dev tool not a browser
By the way here's a chrome extension in order to make it work on your browser (this one is for chrome, but you can find either for FF or Safari).
Check here if you want to learn more about Cross-Origin and why it's working for extensions.
another option (in place, any combination of indices):
_marker = object()
for i in indices:
my_list[i] = _marker # marked for deletion
obj[:] = [v for v in my_list if v is not _marker]
<div runat="server">
is mapped to a HtmlGenericControl
.
Try using BtnventCss.Attributes.Add("class", "hom_but_a");
If you want to avoid the mem cost of using the exec command, I believe you can do better with xargs. I think the following is a more efficient alternative to
find foo -type f ! -name '*Music*' -exec cp {} bar \; # new proc for each exec
find . -maxdepth 1 -name '*Music*' -prune -o -print0 | xargs -0 -i cp {} dest/
how to club the 4 query's as a single query
show below query
nsc = nature of case
report is taken on 06th of every month
( monthly report will be counted from 05th previous month to 05th present of present month)
public static Stream ToStream(this Image image)
{
var stream = new MemoryStream();
image.Save(stream, image.RawFormat);
stream.Position = 0;
return stream;
}
The simplest way to delete rows and columns from arrays is the numpy.delete
method.
Suppose I have the following array x
:
x = array([[1,2,3],
[4,5,6],
[7,8,9]])
To delete the first row, do this:
x = numpy.delete(x, (0), axis=0)
To delete the third column, do this:
x = numpy.delete(x,(2), axis=1)
So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.
Try this using uniqid and hexdec,
echo hexdec(uniqid());
Checkout the -maxdepth
flag of find
find . -maxdepth 1 -type d -exec ls -ld "{}" \;
Here I used 1 as max level depth, -type d
means find only directories, which then ls -ld
lists contents of, in long format.
You can use the following command line to start the service:
net start *servicename*
The top answer by hughdbrown suggests using set difference, which is definitely the best approach:
diff = set(dictb.keys()) - set(dicta.keys())
The problem with this code is that it builds two lists just to create two sets, so it's wasting 4N time and 2N space. It's also a bit more complicated than it needs to be.
Usually, this is not a big deal, but if it is:
diff = dictb.keys() - dicta
collections.abc.Mapping
has a KeysView
that acts like a Set
.In Python 2, keys()
returns a list of the keys, not a KeysView
. So you have to ask for viewkeys()
directly.
diff = dictb.viewkeys() - dicta
For dual-version 2.7/3.x code, you're hopefully using six
or something similar, so you can use six.viewkeys(dictb)
:
diff = six.viewkeys(dictb) - dicta
In 2.4-2.6, there is no KeysView
. But you can at least cut the cost from 4N to N by building your left set directly out of an iterator, instead of building a list first:
diff = set(dictb) - dicta
I have a dictA which can be the same as dictB or may have some keys missing as compared to dictB or else the value of some keys might be different
So you really don't need to compare the keys, but the items. An ItemsView
is only a Set
if the values are hashable, like strings. If they are, it's easy:
diff = dictb.items() - dicta.items()
Although the question isn't directly asking for a recursive diff, some of the example values are dicts, and it appears the expected output does recursively diff them. There are already multiple answers here showing how to do that.
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
This works:
var event = jQuery.Event('keypress');
event.which = 13;
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event);
CREATE TABLE someTable (
id serial PRIMARY KEY,
col1 int NOT NULL,
col2 int NOT NULL,
UNIQUE (col1, col2)
)
autoincrement
is not postgresql. You want a serial
.
If col1
and col2
make a unique and can't be null then they make a good primary key:
CREATE TABLE someTable (
col1 int NOT NULL,
col2 int NOT NULL,
PRIMARY KEY (col1, col2)
)
You can use the cd
builtin, or the pushd
and popd
builtins for this purpose. For example:
# do something with /etc as the working directory
cd /etc
:
# do something with /tmp as the working directory
cd /tmp
:
You use the builtins just like any other command, and can change directory context as many times as you like in a script.
A VirtualHost would also work for this and may work better for you as you can host several projects without the need for subdirectories. Here's how you do it:
httpd.conf (or extra\httpd-vhosts.conf relative to httpd.conf. Trailing slashes "\" might cause it not to work):
NameVirtualHost *:80
# ...
<VirtualHost *:80>
DocumentRoot C:\projects\transitCalculator\trunk\
ServerName transitcalculator.localhost
<Directory C:\projects\transitCalculator\trunk\>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
HOSTS file (c:\windows\system32\drivers\etc\hosts usually):
# localhost entries
127.0.0.1 localhost transitcalculator.localhost
Now restart XAMPP and you should be able to access http://transitcalculator.localhost/ and it will map straight to that directory.
This can be helpful if you're trying to replicate a production environment where you're developing a site that will sit on the root of a domain name. You can, for example, point to files with absolute paths that will carry over to the server:
<img src="/images/logo.png" alt="My Logo" />
whereas in an environment using aliases or subdirectories, you'd need keep track of exactly where the "images" directory was relative to the current file.
Probably the new PyCharm from the makers of IntelliJ and ReSharper.
In my case, I wanted to center in a parent container with position: absolute.
<div class="absolute-container">
<div class="parent-container">
<div class="centered-content">
My content
</div>
</div>
</div>
I had to add some positioning for top, bottom, left & right.
.absolute-container {
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
}
.parent-container {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table
}
.centered-content {
display: table-cell;
text-align: center;
vertical-align: middle
}
The +
operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d
is a non-zero number.
File names are case sensitive - please check your file name. it should be in same case in view folder
You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.
Try this:
$ git reset foo/bar.txt
$ git checkout foo/bar.txt
In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.
SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber
Query Result is below:
Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015
As of Node.js 14.3.0 the top-level await is supported.
Required flag: --experimental-top-level-await
.
Further details: https://v8.dev/features/top-level-await
Doing an ordering and then selecting the first item is wasting a lot of time ordering the items after the first one. You don't care about the order of those.
Instead you can use the aggregate function to select the best item based on what you're looking for.
var maxHeight = dimensions
.Aggregate((agg, next) =>
next.Height > agg.Height ? next : agg);
var maxHeightAndWidth = dimensions
.Aggregate((agg, next) =>
next.Height >= agg.Height && next.Width >= agg.Width ? next: agg);
matplotlib.pyplot.vlines
vs. matplotlib.pyplot.axvline
vlines
accepts 1 or more locations for x
, while axvline
permits one location.
x=37
x=[37, 38, 39]
vlines
takes ymin
and ymax
as a position on the y-axis, while axvline
takes ymin
and ymax
as a percentage of the y-axis range.
vlines
, pass a list
to ymin
and ymax
.fig, ax = plt.subplots()
, then replace plt.vlines
or plt.axvline
with ax.vlines
or ax.axvline
, respectively.import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.figure(figsize=(10, 7))
# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')
# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')
# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')
# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')
# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')
# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')
# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')
plt.show()
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
user1594322 gave a correct answer but when I tried it I ran into admin/permission problems. I was able to copy 'mingw32-make.exe' and paste it, over-ruling/by-passing admin issues and then editing the copy to 'make.exe'. On VirtualBox in a Win7 guest.
Use:
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
String version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
And you can get the version code by using this
int verCode = pInfo.versionCode;
If you want to redo the last operation, do the following.
ESC
C + /
)sort
has been replaced in v0.20 by DataFrame.sort_values
and DataFrame.sort_index
. Aside from this, we also have argsort
.
Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.
# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})
df
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
For example, to sort df
by column "A", use sort_values
with a single column name:
df.sort_values(by='A')
A B
0 a 7
3 a 5
4 b 2
1 c 9
2 c 3
If you need a fresh RangeIndex, use DataFrame.reset_index
.
For example, to sort by both col "A" and "B" in df
, you can pass a list to sort_values
:
df.sort_values(by=['A', 'B'])
A B
3 a 5
0 a 7
4 b 2
2 c 3
1 c 9
df2 = df.sample(frac=1)
df2
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
You can do this using sort_index
:
df2.sort_index()
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
df.equals(df2)
# False
df.equals(df2.sort_index())
# True
Here are some comparable methods with their performance:
%timeit df2.sort_index()
%timeit df2.iloc[df2.index.argsort()]
%timeit df2.reindex(np.sort(df2.index))
605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
For example,
idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])
This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc
will do.
df.iloc[idx]
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
While it's not currently possible with the script
tag, it is possible with an iframe
if it's from the same domain.
<iframe
id="mySpecialId"
src="/my/link/to/some.json"
onload="(()=>{if(!window.jsonData){window.jsonData={}}try{window.jsonData[this.id]=JSON.parse(this.contentWindow.document.body.textContent.trim())}catch(e){console.warn(e)}this.remove();})();"
onerror="((err)=>console.warn(err))();"
style="display: none;"
></iframe>
To use the above, simply replace the id
and src
attribute with what you need. The id
(which we'll assume in this situation is equal to mySpecialId
) will be used to store the data in window.jsonData["mySpecialId"]
.
In other words, for every iframe that has an id
and uses the onload
script will have that data synchronously loaded into the window.jsonData
object under the id
specified.
I did this for fun and to show that it's "possible' but I do not recommend that it be used.
Here is an alternative that uses a callback instead.
<script>
function someCallback(data){
/** do something with data */
console.log(data);
}
function jsonOnLoad(callback){
const raw = this.contentWindow.document.body.textContent.trim();
try {
const data = JSON.parse(raw);
/** do something with data */
callback(data);
}catch(e){
console.warn(e.message);
}
this.remove();
}
</script>
<!-- I frame with src pointing to json file on server, onload we apply "this" to have the iframe context, display none as we don't want to show the iframe -->
<iframe src="your/link/to/some.json" onload="jsonOnLoad.apply(this, someCallback)" style="display: none;"></iframe>
Tested in chrome and should work in firefox. Unsure about IE or Safari.
Notice the repetition of Book
in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)
- it screams for a class type.
class Book {
int number;
String title;
String language;
int price;
}
Now you can simply have:
Book[] books = new Books[3];
If you want arrays, you can declare it as object array an insert Integer
and String
into it:
Object books[3][4]
There are two ways to approach this problem. Either use a simple array or an array of objects. Each solution has it pros and cons. Below you'll find one for each case.
The HTML could look like:
<label ng-repeat="fruitName in fruits">
<input
type="checkbox"
name="selectedFruits[]"
value="{{fruitName}}"
ng-checked="selection.indexOf(fruitName) > -1"
ng-click="toggleSelection(fruitName)"
> {{fruitName}}
</label>
And the appropriate controller code would be:
app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
// Fruits
$scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
// Selected fruits
$scope.selection = ['apple', 'pear'];
// Toggle selection for a given fruit by name
$scope.toggleSelection = function toggleSelection(fruitName) {
var idx = $scope.selection.indexOf(fruitName);
// Is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// Is newly selected
else {
$scope.selection.push(fruitName);
}
};
}]);
Pros: Simple data structure and toggling by name is easy to handle
Cons: Add/remove is cumbersome as two lists (the input and selection) have to be managed
The HTML could look like:
<label ng-repeat="fruit in fruits">
<!--
- Use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted
traditionally
- Use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression
(no two-way-data-binding)
- Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected`
is arbitrary. The property name could be anything and will be created on the object if not present.
-->
<input
type="checkbox"
name="selectedFruits[]"
value="{{fruit.name}}"
ng-model="fruit.selected"
> {{fruit.name}}
</label>
And the appropriate controller code would be:
app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {
// Fruits
$scope.fruits = [
{ name: 'apple', selected: true },
{ name: 'orange', selected: false },
{ name: 'pear', selected: true },
{ name: 'naartjie', selected: false }
];
// Selected fruits
$scope.selection = [];
// Helper method to get selected fruits
$scope.selectedFruits = function selectedFruits() {
return filterFilter($scope.fruits, { selected: true });
};
// Watch fruits for changes
$scope.$watch('fruits|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (fruit) {
return fruit.name;
});
}, true);
}]);
Pros: Add/remove is very easy
Cons: Somewhat more complex data structure and toggling by name is cumbersome or requires a helper method
I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:
public static MyEnum asMyEnum(String str) {
for (MyEnum me : MyEnum.values()) {
if (me.name().equalsIgnoreCase(str))
return me;
}
return null;
}
Edit: As Jon Skeet notes, values()
works by cloning a private backing array every time it is called. If performance is critical, you may want to call values()
only once, cache the array, and iterate through that.
Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.
A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:
arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)
You should remove "style" attribute instead of "display" property :
$("span").removeAttr("style");
Make Sure that in Project Navigator > Signing > Team , A team name must need be selected.
If that number represents milliseconds, use the Date's constructor :
var myDate = new Date(1238540400000);
I had the same problem, just forgot to activate my virtual environment. For anyone out there who also had a mental blank.
I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.
Vendor bundle.
You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor
), and file name that will be generated (vendor.js
).
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),
Now important part, you have to now specify what does it mean vendor
library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor
bundle.
in your case it should look something like:
entry: {
app: 'entry.js',
vendor: ['jquery', 'jquery.plugin1']
}
JQuery as global
Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:
new webpack.ProvidePlugin({
$: "jquery"
})
And now you can just use $
anywhere in your code - webpack will automatically convert that to
require('jquery')
I hope it helped. you can also look at my webpack configuration file that is here
I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)
Edit:
To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:
new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),
and then declare different extenral libraries for different files:
entry: {
page1: ['entry.js'],
page2: ['entry2.js'],
"vendor-page1": [
'lodash'
],
"vendor-page2": [
'jquery'
]
},
If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.
An alternative approach would be:
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))
df = df1.join(df2, ['x1','x2'])
df.show()
which outputs:
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
| 2| b|3.0|0.0|
+---+---+---+---+
With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.
Whenever the columns in the two tables have different names, (let's say in the example above, df2
has the columns y1
, y2
and y4
), you could use the following syntax:
df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])