Shift-tab doesn't seem to work on multi-lines in Aptana. It also doesn't work on single lines with a single preceding space. Any workarounds? I use shift-tab (outdent) to fix badly formatted code all the time.
I miss NetBeans ...
UPDATE: it works on multi-newlines, if the multi-lines have the same level of indentation. It should just continue outdenting the other lines that haven't reached the beginning of the new line yet. Is there an option to change this I wonder?
From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.
That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.
You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.
It seems having msysgit (Git for Windows) installed is causing the problem.
In most cases you'll have a pretty recent version of Git for Windows installed. Cited from https://code.google.com/p/tortoisegit/:
There was a security issue in Git, see here. Git for Windows < 1.9.5 is affected - so you should update, TortoiseGit itself is not affected (using the default configuration; only if libgit2 is manually enabled for checkout/fetching). TortoiseGit 1.8.13.0 includes all fixes.
But it seems Aptana Studio Installer won't accept any pre-installed version of Git for Windows!
What you need to do:
That's it !!!
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
Maybe someone prefers
<TextBlock Text="{Binding StringFormat='Stuff on line1{0}Stuff on line2{0}Stuff on line3',
Source={x:Static s:Environment.NewLine}}" />
with xmlns:s="clr-namespace:System;assembly=mscorlib"
.
Yet another node based simple command line server
https://github.com/greggman/servez-cli
Written partly in response to http-server having issues, particularly on windows.
Install node.js then
npm install -g servez
servez [options] [path]
With no path it serves the current folder.
By default it serves index.html
for folder paths if it exists. It serves a directory listing for folders otherwise. It also serves CORS headers. You can optionally turn on basic authentication with --username=somename --password=somepass
and you can serve https.
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
If you want to make sure the border is on the inside of your element, you can use
box-sizing:border-box;
this will place the following border on the inside of the element:
border: 10px solid black;
(similar result you'd get using the additonal parameter inset
on box-shadow, but instead this one is for the real border and you can still use your shadow for something else.)
Note to another answer above: as soon as you use any inset
on box-shadow
of a certain element, you are limited to a maximum of 2 box-shadows on that element and would require a wrapper div for further shadowing.
Both solutions should as well get you rid of the undesired 3D effects. Also note both solutions are stackable (see the example I've added in 2018)
.example-border {_x000D_
width:100px;_x000D_
height:100px;_x000D_
border:40px solid blue;_x000D_
box-sizing:border-box;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
.example-shadow {_x000D_
width:100px;_x000D_
height:100px;_x000D_
float:left;_x000D_
margin-left:20px;_x000D_
box-shadow:0 0 0 40px green inset;_x000D_
}_x000D_
_x000D_
.example-combined {_x000D_
width:100px;_x000D_
height:100px;_x000D_
float:left;_x000D_
margin-left:20px;_x000D_
border:20px solid orange;_x000D_
box-sizing:border-box;_x000D_
box-shadow:0 0 0 20px red inset;_x000D_
}
_x000D_
<div class="example-border"></div>_x000D_
<div class="example-shadow"></div>_x000D_
<div class="example-combined"></div>
_x000D_
The only way that worked for me, is by copying the dll into your desktop or something, add reference to it, then delete the dll from your desktop. Visual Studio will refresh itself, and will finally reference the dll from the GAC on itself.
For anyone doing this on iOS8, this is what I had to do:
I have a swift class file titled SettingsView.swift
and a .xib file named SettingsView.xib
. I run this in MasterViewController.swift
(or any view controller really to open a second view controller)
@IBAction func openSettings(sender: AnyObject) {
var mySettings: SettingsView = SettingsView(nibName: "SettingsView", bundle: nil) /<--- Notice this "nibName"
var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical
mySettings.modalTransitionStyle = modalStyle
self.presentViewController(mySettings, animated: true, completion: nil)
}
var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
_x000D_
String url = "https://www.murait.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}else{
Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}
You have to check that the URL is valid or not. If URL is invalid application may crash so that you have to check URL is valid or not by this method.
If you know the name of the alias, you can use the --help
option to describe it. For example:
$ git sa --help
`git sa' is aliased to `stash'
$ git a --help
`git a' is aliased to `add'
You can't do it with client side script only... you could make an AJAX call to some server side code that will send an email...
If you know the the name of the file and if you always want to download that specific file, then you can easily get the ID and other attributes for your desired file from: https://developers.google.com/drive/v2/reference/files/list (towards the bottom you will find a way to run queries). In the q field enter title = 'your_file_name' and run it. You should see some result show up right below and within it should be an "id" field. That is the id you are looking for.
You can also play around with additional parameters from: https://developers.google.com/drive/search-parameters
You could add your JSON file as an external using webpack config. Then you can load up that json in any of your react modules.
Take a look at this answer
You can create a stored procedure passing 2 dates
CREATE PROCEDURE SELECTALLDATES
(
@StartDate as date,
@EndDate as date
)
AS
Declare @Current as date = DATEADD(DD, 1, @BeginDate);
Create table #tmpDates
(displayDate date)
WHILE @Current < @EndDate
BEGIN
insert into #tmpDates
VALUES(@Current);
set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day
END
Select *
from #tmpDates
drop table #tmpDates
I don't know if this is new functionality, but this will plot on separate figures:
df.plot(y='korisnika')
df.plot(y='osiguranika')
while this will plot on the same figure: (just like the code in the op)
df.plot(y=['korisnika','osiguranika'])
I found this question because I was using the former method and wanted them to plot on the same figure, so your question was actually my answer.
The CosisEntities
class is your DbContext
. When you create a context in a using
block, you're defining the boundaries for your data-oriented operation.
In your code, you're trying to emit the result of a query from a method and then end the context within the method. The operation you pass the result to then tries to access the entities in order to populate the grid view. Somewhere in the process of binding to the grid, a lazy-loaded property is being accessed and Entity Framework is trying to perform a lookup to obtain the values. It fails, because the associated context has already ended.
You have two problems:
You're lazy-loading entities when you bind to the grid. This means that you're doing lots of separate query operations to SQL Server, which are going to slow everything down. You can fix this issue by either making the related properties eager-loaded by default, or asking Entity Framework to include them in the results of this query by using the Include
extension method.
You're ending your context prematurely: a DbContext
should be available throughout the unit of work being performed, only disposing it when you're done with the work at hand. In the case of ASP.NET, a unit of work is typically the HTTP request being handled.
To answer a modulo x % y
, you ask two questions:
A- How many times y
goes in x
without remainder ? For 2%4 that's 0.
B- How much do you need to add to get from that back to x
? To get from 0 back to 2 you'll need 2-0, i.e. 2.
These can be summed up in one question like so:
How much will you need to add to the integer-ish result of the division of x
by y
, to get back at x
?
By integer-ish it is meant only whole numbers and not fractions whatsoever are of interest.
A fractional division remainder (e.g. .283849) is not of interest in modulo because modulo only deals with integer numbers.
You can use this module which is easy to use: https://github.com/halilb/react-native-textinput-effects
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
You can use angular's function called angular.isUndefined(value)
returns boolean.
You may read more about angular's functions here: AngularJS Functions (isUndefined)
It should be
if (*message == '\0')
In C, simple quotes delimit a single character whereas double quotes are for strings.
Using this code you can copy any class object to another class object for same name and same type of properties.
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string serializeString = JsonConvert.Serialize(objectEntity);
objectViewModel objVM = JsonConvert.Deserialize<objectViewModel>(serializeString);
Try to set response dataType property directly:
dataType: 'text'
and put
die('');
in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.
Try this:
<video width="320" height="240" autoplay muted>
<source src="video.mp4" type="video/mp4">
</video>
Another possibility with Guava:
dependency: compile 'com.google.guava:guava:11.0.2'
import com.google.common.io.ByteStreams;
...
String total = new String(ByteStreams.toByteArray(inputStream ));
all: program1 program2
program1:
gcc -Wall -o prog1 program1.c
program2:
gcc -Wall -o prog2 program2.c
Increasing number of max-connections will not solve the problem.
We were experiencing the same situation on our servers. This is what happens
User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.
You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour
SET interactive_timeout=3600
For whoever is using Kotlin, honestly the by far easiest way to iterate over a SparseArray is: Use the Kotlin extension from Anko or Android KTX! (credit to Yazazzello for pointing out Android KTX)
Simply call forEach { i, item -> }
body{
height: 100%;
overflow: hidden !important;
width: 100%;
position: fixed;
works on iOS9
Use this code to setup your mongodb connection:
var mongoose = require('mongoose');
var mongoURI = "mongodb://localhost:27017/test";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
Make sure mongod is running while you start the server. Are you using Express or just a simple node.js server? What is the error message you get with the above code?
Try this:
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public' AND table_type='BASE TABLE'
this one works!
You could simply use Runtime.exec()
I don't think WPF supports what you are trying to achieve i.e. assigning method to a button using method's name or btn1.Click = "btn1_Click". You will have to use approach suggested in above answers i.e. register button click event with appropriate method btn1.Click += btn1_Click;
UPDATE
only changes the values you specify:
UPDATE table SET cell='new_value' WHERE whatever='somevalue'
For just elements this can be used to find the index of an element amongst it's sibling elements:
function getElIndex(el) {
for (var i = 0; el = el.previousElementSibling; i++);
return i;
}
Note that previousElementSibling
isn't supported in IE<9.
Use following hexadecimal code for transparent text colour: #00FFFF00
Random random = new Random();
int n = random.nextInt(69) + 32;
if (n > 96) {
n += 26;
}
char c = (char) n;
I guess it depends which punctuation you want to include, but this should generate a random character including all of the punctuation on this ASCII table. Basically, I've generated a random int from 32 - 96 or 123 - 126, which I have then casted to a char, which gives the ASCII equivalent of that number. Also, make sure youimport java.util.Random
Following is the simple function to encode xml escape chars in JS
Encoder.htmlEncode(unsafeText);
I use the following method in my JavaFX applications.
newWindowButton.setOnMouseClicked((event) -> {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
});
Data structures (DS) are important because they are used to perform operations on data which basically implies: take some input, process it, and give back the output.
Some data structures are more useful than others in some particular cases. Therefore, it is quite unfair to ask which (DS) is more efficient/speedy. It is like asking which tool is more efficient between a knife and fork. I mean all depends on the situation.
A list is mutable sequence, typically used to store collections of homogeneous items.
A set object is an unordered collection of distinct hashable objects. It is commonly used to test membership, remove duplicates from a sequence, and compute mathematical operations such as intersection, union, difference, and symmetric difference.
From some of the answers, it is clear that a list is quite faster than a set when iterating over the values. On the other hand, a set is faster than a list when checking if an item is contained within it. Therefore, the only thing you can say is that a list is better than a set for some particular operations and vice-versa.
I took the liberty to expand the answer from nona-urbiz; just add this to your ~/.bashrc:
git-pullall () { for RMT in $(git remote); do git pull -v $RMT $1; done; }
alias git-pullall=git-pullall
git-pushall () { for RMT in $(git remote); do git push -v $RMT $1; done; }
alias git-pushall=git-pushall
Usage:
git-pullall master
git-pushall master ## or
git-pushall
If you do not provide any branch argument for git-pullall then the pull from non-default remotes will fail; left this behavior as it is, since it's analogous to git.
Making this case insensitive wasn't working in asp.net so I just specified each of the letters.
Here's what I had to do to get it working in an asp.net RegularExpressionValidator:
[Hh][Tt][Tt][Pp][Ss]?://(.*)
Notes:
(?i)
and using /whatever/i
didn't work probably because javascript hasn't brought in all case sensitive functionality^
at beginning but it didn't matter, but the (.*)
did (Expression didn't work without (.*)
but did work without ^
)//
though might be a good idea.Here's the full RegularExpressionValidator if you need it:
<asp:RegularExpressionValidator ID="revURLHeaderEdit" runat="server"
ControlToValidate="txtURLHeaderEdit"
ValidationExpression="[Hh][Tt][Tt][Pp][Ss]?://(.*)"
ErrorMessage="URL should begin with http:// or https://" >
</asp:RegularExpressionValidator>
If you want to do your part as developer, utilizing open source libraries, you should try including all those open source licenses within your apk
. To do this, you can use the merge method in your packagingOptions
.
Example:
packagingOptions {
// This will get include every license and notice regardless of what dir it’s in.
merge '**/LICENSE.txt'
merge '**/NOTICE.txt'
merge '**/notice.txt'
merge '**/license.txt'
merge '**/NOTICE'
merge '**/LICENSE'
merge '**/notice'
merge '**/license'
merge '**/LGPL2.1'
// This will exclude any README files, regardless of the dir or the file type.
exclude '**/README.*'
}
This answer is better than using pickFirst
because that method only picks the first license it finds and disregards all the rest, kinda rendering it useless in this case.
So in short, use the merge
method to include all those licenses from those kickass open source libraries you’ve been using.
More info on Gradle
PackagingOptions.
Make sure you evaluate the DataNucleus implementation of JDO. We started out with Hibernate because it appeared to be so popular but pretty soon realized that it's not a 100% transparent persistence solution. There are too many caveats and the documentation is full of 'if you have this situation then you must write your code like this' that took away the fun of freely modeling and coding however we want. JDO has never caused me to adjust my code or my model to get it to 'work properly'. I can just design and code simple POJOs as if I was going to use them 'in memory' only, yet I can persist them transparently.
The other advantage of JDO/DataNucleus over hibernate is that it doesn't have all the run time reflection overhead and is more memory efficient because it uses build time byte code enhancement (maybe add 1 sec to your build time for a large project) rather than hibernate's run time reflection powered proxy pattern.
Another thing you might find annoying with Hibernate is that a reference you have to what you think is the object... it's often a 'proxy' for the object. Without the benefit of byte code enhancement the proxy pattern is required to allow on demand loading (i.e. avoid pulling in your entire object graph when you pull in a top level object). Be prepared to override equals and hashcode because the object you think you're referencing is often just a proxy for that object.
Here's an example of frustrations you'll get with Hibernate that you won't get with JDO:
http://blog.andrewbeacock.com/2008/08/how-to-implement-hibernate-safe-equals.html
http://burtbeckwith.com/blog/?p=53
If you like coding to 'workarounds' then, sure, Hibernate is for you. If you appreciate clean, pure, object oriented, model driven development where you spend all your time on modeling, design and coding and none of it on ugly workarounds then spend a few hours evaluating JDO/DataNucleus. The hours invested will be repaid a thousand fold.
For quite some time now DataNucleus' implements the JPA persistence standard in addition to the JDO persistence standard so porting existing JPA projects from Hibernate to DataNucleus should be very straight forward and you can get all of the above mentioned benefits of DataNucleus with very little code change, if any. So in terms of the question, the choice of a particular standard, JPA (RDBMS only) vs JDO (RDBMS + No SQL + ODBMSes + others), DataNucleus supports both, Hibernate is restricted to JPA only.
Another issue to consider when choosing an ORM is the efficiency of its dirty checking mechanism - that becomes very important when it needs to construct the SQL to update the objects that have changed in the current transaction - especially when there are a lot of objects. There is a detailed technical description of Hibernate's dirty checking mechanism in this SO answer: JPA with HIBERNATE insert very slow
Give your two buttons the same name and different values:
<input type="submit" name="submit_button" value="Do Something">
<input type="submit" name="submit_button" value="Do Something Else">
Then in your Flask view function you can tell which button was used to submit the form:
def contact():
if request.method == 'POST':
if request.form['submit_button'] == 'Do Something':
pass # do something
elif request.form['submit_button'] == 'Do Something Else':
pass # do something else
else:
pass # unknown
elif request.method == 'GET':
return render_template('contact.html', form=form)
I do not know C#, but with a little guesswork I think I understand what
foo : int {
get { return getFoo(); }
set { setFoo(newValue); }
}
does. It looks very similar to what you have in Swift, but it's not the same: in Swift you do not have the getFoo
and setFoo
. That is not a little difference: it means you do not have any underlying storage for your value.
Swift has stored and computed properties.
A computed property has get
and may have set
(if it's writable). But the code in the getter and setter, if they need to actually store some data, must do it in other properties. There is no backing storage.
A stored property, on the other hand, does have backing storage. But it does not have get
and set
. Instead it has willSet
and didSet
which you can use to observe variable changes and, eventually, trigger side effects and/or modify the stored value. You do not have willSet
and didSet
for computed properties, and you do not need them because for computed properties you can use the code in set
to control changes.
Sorry, but all the answers are difficult to understand for me as a beginner in graphics...
After some fiddling, this is working for me and it is easy to reason about.
@Override
public void draw(Graphics2D g) {
AffineTransform tr = new AffineTransform();
// X and Y are the coordinates of the image
tr.translate((int)getX(), (int)getY());
tr.rotate(
Math.toRadians(this.rotationAngle),
img.getWidth() / 2,
img.getHeight() / 2
);
// img is a BufferedImage instance
g.drawImage(img, tr, null);
}
I suppose that if you want to rotate a rectangular image this method wont work and will cut the image, but I thing you should create square png images and rotate that.
i use Mac and i deleted ADT bundle source. faced the same error so i went to project > clean and adb ran normally.
I came across this issue as well and originally thought it was a CocoaPods issue, but it was an issue in the apps build settings where someone (probably me) had set ${PODS_ROOT}
in Header Search Paths and set it to be a recursive
search. This was allowing it to find headers that were not intended to be used when building the app. Once I set this to use non-recursive
everything was fine. using recursive
search is a terrible hack to try to find the proper headers. Lesson learned.
You could try either of these. They are not giving me errors.
It is also the suggested method from typescript for array declaration.
By using the Array<Thing>
it is making use of the generics in typescript. It is similar to asking for a List<T>
in c# code.
// Declare with default value
private _possessions: Array<Thing> = new Array<Thing>();
// or
private _possessions: Array<Thing> = [];
// or -> prefered by ts-lint
private _possessions: Thing[] = [];
or
// declare
private _possessions: Array<Thing>;
// or -> preferd by ts-lint
private _possessions: Thing[];
constructor(){
//assign
this._possessions = new Array<Thing>();
//or
this._possessions = [];
}
I also faced this issue and after debugging the culprit was found. In my case it was the "space" character right before the https
I've used the open source control at http://dropdowncheckboxes.codeplex.com/ and been very happy with it. My addition was to allow a list of checked files to use just file names instead of full paths if the 'selected' caption gets too long. My addition is called instead of UpdateSelection in your postback handler:
// Update the caption assuming that the items are files<br/>
// If the caption is too long, eliminate paths from file names<br/>
public void UpdateSelectionFiles(int maxChars) {
StringBuilder full = new StringBuilder();
StringBuilder shorter = new StringBuilder();
foreach (ListItem item in Items) {
if (item.Selected) {
full.AppendFormat("{0}; ", item.Text);
shorter.AppendFormat("{0}; ", new FileInfo(item.Text).Name);
}
}
if (full.Length == 0) Texts.SelectBoxCaption = "Select...";
else if (full.Length <= maxChars) Texts.SelectBoxCaption = full.ToString();
else Texts.SelectBoxCaption = shorter.ToString();
}
If you want to execute multiple commands in a for loop, you can save the result of find
with mapfile
(bash >= 4) as an variable and go through the array with ${dirlist[@]}
. It also works with directories containing spaces.
The find
command is based on the answer by Boldewyn. Further information about the find
command can be found there.
IFS=""
mapfile -t dirlist < <( find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n' )
for dir in ${dirlist[@]}; do
echo ">${dir}<"
# more commands can go here ...
done
I had the same problem. Files defined in .gitingore
where listed as untracked files when running git status
.
The reason was that the .gitignore
file was saved in UTF-16LE
encoding, and not in UTF8
encoding.
After changing the encoding of the .gitignore
file to UTF8
it worked for me.
It seemed that a lot of dependencies were incorrect.
A good place to look for the correct dependencies is the Maven Repository website.
Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
If anyone is using WordPress, you can use something like:
if (jQuery('.dropdown-menu li').hasClass('active')) {
jQuery('.current-menu-parent').addClass('current-menu-item');
}
The syntax is wrong in this clause (and similar ones)
CASE lkey WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
It's either
CASE WHEN [condition] THEN [expression] ELSE [expression] END
or
CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END
So in your case it would read:
CASE WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
Check out the documentation (The CASE expression):
You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.
add modify this line in
m2.conf
set maven.home C:\Users\me\.m2
Use the command as
java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>
The above command will set the mentioned paths to classpath only once for executing the class named TestClass.
If you want to execute more then one classes, then you can follow this
set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"
After this you can execute as many classes as you want just by simply typing
java <your-class-name>
The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)
If you want to set the classpth only once so that it could work for everytime, then do as follows
1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
a. Variable Name- classpath
b. Variable Value- .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.
Remember this will work every time. You don't need to explicitly set the classpath again and again.
NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.
Hope this will help you.
Try Date.now().
The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.
There are two methods by which you can round up your double value.
If you want your answer 4.90625 as 4 then you should use Math.floor and if you want your answer 4.90625 as 5 then you can use Math.ceil
You can refer following code for that.
public class TestClass {
public static void main(String[] args) {
int floorValue = (int) Math.floor((double)157 / 32);
int ceilValue = (int) Math.ceil((double)157 / 32);
System.out.println("Floor: "+floorValue);
System.out.println("Ceil: "+ceilValue);
}
}
You can use JsonBuilder for that.
Example Code:
import groovy.json.JsonBuilder
class Person {
String name
String address
}
def o = new Person( name: 'John Doe', address: 'Texas' )
println new JsonBuilder( o ).toPrettyString()
Use your jquery like this
$('.home').css({'background-image':'url(images/tabs3.png)'});
The TextBoxFor
is a newer MVC input extension introduced in MVC2.
The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.
See this page.
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx
Use the return
keyword to exit from a method.
public void someMethod() {
//... a bunch of code ...
if (someCondition()) {
return;
}
//... otherwise do the following...
}
From the Java Tutorial that I linked to above:
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
return;
I had issues like this especially when debugging actively through my phone; at times it took 27 minutes. I did the following things and take note of the explanation under each - one may work for you:
org.gradle.daemon=true
org.gradle.configureondemand=true
org.gradle.parallel=true
android.enableBuildCache=true
org.gradle.caching=true
org.gradle.jvmargs=-Xmx8000m -XX:MaxPermSize=5000m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
File -> Settings/Preferences -> Build, Execution, Deployment -> Gradle
Global Gradle Settings (at the bottom)
Mark the checkbox named: Offline Work.
File -> Settings/Preferences -> Build, Execution, Deployment -> Instant Run
Checked : Enable Instant Run to hot swap code...
Checked: restart activity on code changes ...
The move above was erratic also and therefore I sought to find out if the problem may be the processes/memory that ran directly on either my phone and computer. Here I freed up a little memory space in my phone and storage (which was at 98% utilized - down to 70%) and also on task manager (Windows), increased the priority of both Android Studio and Java.exe to High. Take this step cautiously; depends on your computer's memory.
After all this my build time while debugging actively on my phone at times went down to 1 ~ 2 minutes but at times spiked. I decided to do a hack which surprised me by taking it down to seconds best yet on the same project that gave me 22 - 27 minutes was 12 seconds!:
Connect phone for debugging then click RUN
After it starts, unplug the phone - the build should continue faster and raise an error at the end indicating this : Session 'app': Error Installing APKs
Reconnect back the phone and click on RUN again...
ALTERNATIVELY
If the script/function/method I'm debugging is purely JAVA, not JAVA-android e.g. testing an API with JSONArrays/JSONObjects, I test my java functions/methods on Netbeans which can compile a single file and show the output faster then make necessary changes on my Android Studio files. This also saves me a lot of time.
EDIT
I tried creating a new android project in local storage and copied all my files from the previous project into the new one - java, res, manifest, gradle app and gradle project (with latest gradle classpath dependency). And now I can build on my phone in less than 15 seconds.
You cannot access elements of an empty vector by subscript.
Always check that the vector is not empty & the index is valid while using the []
operator on std::vector
.
[]
does not add elements if none exists, but it causes an Undefined Behavior if the index is invalid.
You should create a temporary object of your structure, fill it up and then add it to the vector, using vector::push_back()
subject subObj;
subObj.name = s1;
sub.push_back(subObj);
There might be a reason that Typescript
is not installed globally, so install it
npm install -g typescript // installs typescript globally
If you want to convert .ts
files into .js
, do this as per your need
tsc file.ts // file.ts will be converted to file.js file
tsc // all .ts files will be converted to .js files in the directory
tsc --watch // converts all .ts files to .js, and watch changes in .ts files
This is what I did:
yourEditText.setCursorVisible(false); //This code is used when you do not want the cursor to be visible at startup
yourEditText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event); // handle the event first
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // hide the soft keyboard
yourEditText.setCursorVisible(true); //This is to display cursor when upon onTouch of Edittext
}
return true;
}
});
Here's an easy solution, from Wikibooks:
The placeins package provides the command \FloatBarrier, which can be used to prevent floats from being moved over it.
I just put \FloatBarrier
before and after every table.
If anyone else was ever to maintain your code, they would almost certainly do a double take on version 2 -- that's extremely non-standard.
I would stick with version 1. I'm of the school of though that case statements without a statement block of their own should have an explicit // fall through
comment next to them to indicate it is indeed your intent to fall through, thereby removing any ambiguity of whether you were going to handle the cases differently and forgot or something.
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
If a website's directory does NOT have an "index...." file, AND .htaccess has NOT been used to block access to the directory itself, then Apache will create an "index of" page for that directory. You can save that page, and its icons, using "Save page as..." along with the "Web page, complete" option (Firefox example). If you own the website, temporarily rename any "index...." file, and reference the directory locally. Then restore your "index...." file.
---
- hosts: all
tasks:
- name: Gather Version
debug:
msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
- name: Write Version
local_action: shell echo "This is {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output
With jQuery 1.6 version you can use the .promise()
method.
$(selector).fadeOut('slow');
$(selector).promise().done(function(){
// will be called when all the animations on the queue finish
});
This is my MovementMethod
for detecting link/text/image clicks. It is modified LinkMovementMethod
.
import android.text.Layout;
import android.text.NoCopySpan;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.text.style.URLSpan;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class ClickMovementMethod extends ScrollingMovementMethod {
private Object FROM_BELOW = new NoCopySpan.Concrete();
private static final int CLICK = 1;
private static final int UP = 2;
private static final int DOWN = 3;
private Listener listener;
public void setListener(Listener listener) {
this.listener = listener;
}
@Override
public boolean canSelectArbitrarily() {
return true;
}
@Override
protected boolean handleMovementKey(TextView widget, Spannable buffer, int keyCode,
int movementMetaState, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (KeyEvent.metaStateHasNoModifiers(movementMetaState)) {
if (event.getAction() == KeyEvent.ACTION_DOWN &&
event.getRepeatCount() == 0 && action(CLICK, widget, buffer)) {
return true;
}
}
break;
}
return super.handleMovementKey(widget, buffer, keyCode, movementMetaState, event);
}
@Override
protected boolean up(TextView widget, Spannable buffer) {
if (action(UP, widget, buffer)) {
return true;
}
return super.up(widget, buffer);
}
@Override
protected boolean down(TextView widget, Spannable buffer) {
if (action(DOWN, widget, buffer)) {
return true;
}
return super.down(widget, buffer);
}
@Override
protected boolean left(TextView widget, Spannable buffer) {
if (action(UP, widget, buffer)) {
return true;
}
return super.left(widget, buffer);
}
@Override
protected boolean right(TextView widget, Spannable buffer) {
if (action(DOWN, widget, buffer)) {
return true;
}
return super.right(widget, buffer);
}
private boolean action(int what, TextView widget, Spannable buffer) {
Layout layout = widget.getLayout();
int padding = widget.getTotalPaddingTop() +
widget.getTotalPaddingBottom();
int areatop = widget.getScrollY();
int areabot = areatop + widget.getHeight() - padding;
int linetop = layout.getLineForVertical(areatop);
int linebot = layout.getLineForVertical(areabot);
int first = layout.getLineStart(linetop);
int last = layout.getLineEnd(linebot);
ClickableSpan[] candidates = buffer.getSpans(first, last, URLSpan.class);
int a = Selection.getSelectionStart(buffer);
int b = Selection.getSelectionEnd(buffer);
int selStart = Math.min(a, b);
int selEnd = Math.max(a, b);
if (selStart < 0) {
if (buffer.getSpanStart(FROM_BELOW) >= 0) {
selStart = selEnd = buffer.length();
}
}
if (selStart > last)
selStart = selEnd = Integer.MAX_VALUE;
if (selEnd < first)
selStart = selEnd = -1;
switch (what) {
case CLICK:
if (selStart == selEnd) {
return false;
}
if (listener != null) {
URLSpan[] link = buffer.getSpans(selStart, selEnd, URLSpan.class);
if (link.length >= 1) {
listener.onClick(link[0].getURL());
} else {
ImageSpan[] image = buffer.getSpans(selStart, selEnd, ImageSpan.class);
if (image.length >= 1) {
listener.onImageClicked(image[0].getSource());
} else {
listener.onTextClicked();
}
}
}
break;
case UP:
int beststart, bestend;
beststart = -1;
bestend = -1;
for (int i = 0; i < candidates.length; i++) {
int end = buffer.getSpanEnd(candidates[i]);
if (end < selEnd || selStart == selEnd) {
if (end > bestend) {
beststart = buffer.getSpanStart(candidates[i]);
bestend = end;
}
}
}
if (beststart >= 0) {
Selection.setSelection(buffer, bestend, beststart);
return true;
}
break;
case DOWN:
beststart = Integer.MAX_VALUE;
bestend = Integer.MAX_VALUE;
for (int i = 0; i < candidates.length; i++) {
int start = buffer.getSpanStart(candidates[i]);
if (start > selStart || selStart == selEnd) {
if (start < beststart) {
beststart = start;
bestend = buffer.getSpanEnd(candidates[i]);
}
}
}
if (bestend < Integer.MAX_VALUE) {
Selection.setSelection(buffer, beststart, bestend);
return true;
}
break;
}
return false;
}
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (action == MotionEvent.ACTION_UP) {
if (listener != null) {
if (link.length >= 1) {
listener.onClick(link[0].getURL());
} else {
ImageSpan[] image = buffer.getSpans(off, off, ImageSpan.class);
if (image.length >= 1) {
listener.onImageClicked(image[0].getSource());
} else if (Selection.getSelectionStart(buffer) == Selection.getSelectionEnd(buffer)) {
listener.onTextClicked();
}
}
}
}
if (action == MotionEvent.ACTION_DOWN && link.length != 0) {
Selection.setSelection(buffer,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
return true;
}
if (link.length == 0) {
Selection.removeSelection(buffer);
}
}
return super.onTouchEvent(widget, buffer, event);
}
@Override
public void initialize(TextView widget, Spannable text) {
Selection.removeSelection(text);
text.removeSpan(FROM_BELOW);
}
@Override
public void onTakeFocus(TextView view, Spannable text, int dir) {
Selection.removeSelection(text);
if ((dir & View.FOCUS_BACKWARD) != 0) {
text.setSpan(FROM_BELOW, 0, 0, Spannable.SPAN_POINT_POINT);
} else {
text.removeSpan(FROM_BELOW);
}
}
public interface Listener {
void onClick(String clicked);
void onTextClicked();
void onImageClicked(String source);
}
}
As part of Spring 4.1.1
onwards you now have full support of Java 8 Optional
(original ticket) therefore in your example both requests will go via your single mapping endpoint as long as you replace required=false
with Optional for your 3 params logout, name, password:
@RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET,
produces="text/xml")
public String showLoginWindow(@PathVariable("id") String id,
@RequestParam(value = "logout") Optional<String> logout,
@RequestParam("name") Optional<String> username,
@RequestParam("password") Optional<String> password,
@ModelAttribute("submitModel") SubmitModel model,
BindingResult errors) throws LoginException {...}
DateTime date1 = new DateTime();
date1 = Convert.ToDateTime(TextBox1.Text);
Label1.Text = (date1.ToLongTimeString()); //11:00 AM
Label2.Text = date1.ToLongDateString(); //Friday, November 1, 2019;
Label3.Text = date1.ToString();
Label4.Text = date1.ToShortDateString();
Label5.Text = date1.ToShortTimeString();
If X inherits from Y, that has two somewhat orthogonal effects:
Although inheritance provides for both features, it is not hard to imagine circumstances where either could be of use without the other. No .net language I know of has a direct way of implementing the first without the second, though one could obtain such functionality by defining a base class which is never used directly, and having one or more classes that inherit directly from it without adding anything new (such classes could share all their code, but would not be substitutable for each other). Any CLR-compliant language, however, will allow the use of interfaces which provide the second feature of interfaces (substitutability) without the first (member reuse).
I got an error in Eclipse Mars version as "Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment.
To resolve this issue, please do the following steps, "Right click on Project Choose Build path Choose Configure Build path Choose Libraries tab Select JRE System Library and click on Edit button Choose workspace default JRE and Finish
Problem will be resolved.
Maybe --force-reinstall
would work, otherwise --ignore-installed
should do the trick.
Since web is evolving quickly, some things changes with time. For security issues, you might want to use the rel="noopener"
attribute in conjuncture with your target="_blank"
.
Like stated in Google Dev Documentation, the other page can access your window object with the window.opener property
. Your external link should looks like this now:
<a href="http://www.starfall.com/" target="_blank" rel="noopener">Starfall</a>
I think this is best link for your solution to update postgres to 9.6
https://sandymadaan.wordpress.com/2017/02/21/upgrade-postgresql9-3-9-6-in-ubuntu-retaining-the-databases/
If you want just to get the value, you can use simple shell oneliner like this:
S=10; F=/sys/class/net/eth0/statistics/rx_bytes; X=`cat $F`; sleep $S; Y=`cat $F`; BPS="$(((Y-X)/S))"; echo $BPS
It will show you the average "received bytes per second" for period of 10 seconds (you can change period by changing S=10
parameter, and you can measure transmitted BPS instead of received BPS by using tx_bytes
instead of rx_bytes
). Don't forget to change eth0
to network device you want to monitor.
Of course, you are not limited to displaying the average rate (as mentioned in other answers, there are other tools that will show you much nicer output), but this solution is easily scriptable to do other things.
For example, the following shell script (split into multiple lines for readability) will execute offlineimap process only when 5-minute average transmit speed drops below 10kBPS (presumably, when some other bandwidth-consuming process finishes):
#!/bin/sh
S=300; F=/sys/class/net/eth0/statistics/tx_bytes
BPS=999999
while [ $BPS -gt 10000 ]
do
X=`cat $F`; sleep $S; Y=`cat $F`; BPS="$(((Y-X)/S))";
echo BPS is currently $BPS
done
offlineimap
Note that /sys/class/...
is Linux specific (which is ok as submitter did choose linux
tag), and needs non-archaic kernel. Shell code itself is /bin/sh compatible (so not only bash, but dash and other /bin/sh implementations will work) and /bin/sh is something that is really always installed.
With xidel:
xidel -s input.xml -e 'serialize(.,{"indent":true()})'
<root>
<foo a="b">lorem</foo>
<bar value="ipsum"/>
</root>
Or file:write("output.xml",.,{"indent":true()})
to save to a file.
"singleton" in spring is using bean factory get instance, then cache it; which singleton design pattern is strictly, the instance can only be retrieved from static get method, and the object can never be publicly instantiated.
The '\r'
character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.
From the old telnet specification (RFC 854) (page 11):
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
However, from the latest specification (RFC5198) (page 13):
...
In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.
LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).
So newline in Telnet should always be '\r\n'
but most implementations have either not been updated, or keeps the old '\n\r'
for backwards compatibility.
For python 3 use this
inp = list(map(int,input().split()))
#input => java is a programming language
#return as => ("java","is","a","programming","language")
input() accepts a string from STDIN.
split()
splits the string about whitespace character and returns a list of strings.
map()
passes each element of the 2nd argument to the first argument and returns a map object
Finally list()
converts the map to a list
Using Java Web Start, you can install multiple JRE, then call what you need. On win, you can make a .bat file:
1- online version: <your_JRE_version\bin\javaws.exe> -localfile -J-Djnlp.application.href=<the url of .jnlp file.jnlp> -localfile -J "<path_temp_jnlp_file_.jnlp>"
2- launch from cache: <your_JRE_version\bin\javaws.exe> -localfile -J "<path_of_your_local_jnlp_file.jnlp>"
If you want to browse to a folder by default: For example "D:\Default_Folder" just initialise the "InitialFileName" attribute
Dim diaFolder As FileDialog
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.InitialFileName = "D:\Default_Folder"
diaFolder.Show
For Bootstrap 4 I find the following very handy because:
It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)
<div class="row">
<div class="col">Left</div>
<div class="col-auto">Right</div>
</div>
Ideal for aligning words, icons, buttons,... to the right.
An example to have this responsive on small devices:
<div class="row">
<div class="col">Left</div>
<div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>
Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/
Elasticsearch 1.1+ has the Cardinality Aggregation which will give you a unique count
Note that it is actually an approximation and accuracy may diminish with high-cardinality datasets, but it's generally pretty accurate in my testing.
You can also tune the accuracy with the precision_threshold
parameter. The trade-off, or course, is memory usage.
This graph from the docs shows how a higher precision_threshold
leads to much more accurate results.
though npm install lodash
would work, I think that it's a quick solution but there is a possibility that there are other modules not correctly installed in browser-sync
.
lodash is part of browser-sync
. The best solution is the one provided by Saebyeok. Re-install browser-sync
and that should fix the problem.
Imagine a counter with an initial value of 0
.
For every loop, increment the counter value by 1 using $counter = 0;
The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}
Try that.
Here is what worked for me. The heroku site is not being added to your known hosts. Go to window-other- show view-git-git repositories. From there clone the repository. Once you clone it, delete the repository that was just created and then import it from the file menu. Do this since when you clone the repository, it does not add it to the explorer view. Now you should have the git repository and the explorer view.
1. Remove Containers:
$ docker rm $(docker ps -aq)
2. Remove Images:
$ docker rmi $(docker images -q)
Instead of perform steps 1 and 2 you can do:
docker system prune
This command will remove:
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
The answer to "Given a class, see if instance has method (Ruby)" is better. Apparently Ruby has this built-in, and I somehow missed it. My answer is left for reference, regardless.
Ruby classes respond to the methods instance_methods
and public_instance_methods
. In Ruby 1.8, the first lists all instance method names in an array of strings, and the second restricts it to public methods. The second behavior is what you'd most likely want, since respond_to?
restricts itself to public methods by default, as well.
Foo.public_instance_methods.include?('bar')
In Ruby 1.9, though, those methods return arrays of symbols.
Foo.public_instance_methods.include?(:bar)
If you're planning on doing this often, you might want to extend Module
to include a shortcut method. (It may seem odd to assign this to Module
instead of Class
, but since that's where the instance_methods
methods live, it's best to keep in line with that pattern.)
class Module
def instance_respond_to?(method_name)
public_instance_methods.include?(method_name)
end
end
If you want to support both Ruby 1.8 and Ruby 1.9, that would be a convenient place to add the logic to search for both strings and symbols, as well.
I think the easiest way is
ng-selected="$first"
The problem is you either haven't closed your if
or you need an elseif
:
create procedure checando(
in nombrecillo varchar(30),
in contrilla varchar(30),
out resultado int)
begin
if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
set resultado = 0;
elseif exists (select * from compas where nombre = nombrecillo) then
set resultado = -1;
else
set resultado = -2;
end if;
end;
For a more simple and up to date answer:
backdrop-filter: blur(6px);
Note browser support is not perfect but in most cases a blur would be non essential.
("Jesse" or "jesse")
The above expression tests whether or not "Jesse"
evaluates to True
. If it does, then the expression will return it; otherwise, it will return "jesse"
. The expression is equivalent to writing:
"Jesse" if "Jesse" else "jesse"
Because "Jesse"
is a non-empty string though, it will always evaluate to True
and thus be returned:
>>> bool("Jesse") # Non-empty strings evaluate to True in Python
True
>>> bool("") # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>
This means that the expression:
name == ("Jesse" or "jesse")
is basically equivalent to writing this:
name == "Jesse"
In order to fix your problem, you can use the in
operator:
# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):
Or, you can lowercase the value of name
with str.lower
and then compare it to "jesse"
directly:
# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":
Additional attributes (in this case, the second onClick
) will be ignored. So, instead of onclick
calling both fbLikeDump();
and WriteCookie();
, it will only call fbLikeDump();
. To fix, simply define a single onclick
attribute and call both functions within it:
<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />
Here is an approach where Inkscape is called by Python.
Note that it suppresses certain crufty output that Inkscape writes to the console (specifically, stderr and stdout) during normal error-free operation. The output is captured in two string variables, out
and err
.
import subprocess # May want to use subprocess32 instead
cmd_list = [ '/full/path/to/inkscape', '-z',
'--export-png', '/path/to/output.png',
'--export-width', 100,
'--export-height', 100,
'/path/to/input.svg' ]
# Invoke the command. Divert output that normally goes to stdout or stderr.
p = subprocess.Popen( cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
# Below, < out > and < err > are strings or < None >, derived from stdout and stderr.
out, err = p.communicate() # Waits for process to terminate
# Maybe do something with stdout output that is in < out >
# Maybe do something with stderr output that is in < err >
if p.returncode:
raise Exception( 'Inkscape error: ' + (err or '?') )
For example, when running a particular job on my Mac OS system, out
ended up being:
Background RRGGBBAA: ffffff00
Area 0:0:339:339 exported to 100 x 100 pixels (72.4584 dpi)
Bitmap saved as: /path/to/output.png
(The input svg file had a size of 339 by 339 pixels.)
that depends on what kind of information are you passing to the conditional..
sometimes your result will be null
or undefined
or ''
or 0
, for my simple validation i use this if.
( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )
NOTE: null
!= 'null'
You could actually use xlsread
to accomplish this. After first placing your sample data above in a file 'input_file.csv'
, here is an example for how you can get the numeric values, text values, and the raw data in the file from the three outputs from xlsread
:
>> [numData,textData,rawData] = xlsread('input_file.csv')
numData = % An array of the numeric values from the file
51.9358 4.1833
51.9354 4.1841
51.9352 4.1846
51.9343 4.1864
51.9343 4.1864
51.9341 4.1869
textData = % A cell array of strings for the text values from the file
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
rawData = % All the data from the file (numeric and text) in a cell array
'ABC' [51.9358] [4.1833]
'ABC' [51.9354] [4.1841]
'ABC' [51.9352] [4.1846]
'ABC' [51.9343] [4.1864]
'ABC' [51.9343] [4.1864]
'ABC' [51.9341] [4.1869]
You can then perform whatever processing you need to on the numeric data, then resave a subset of the rows of data to a new file using xlswrite
. Here's an example:
index = sqrt(sum(numData.^2,2)) >= 50; % Find the rows where the point is
% at a distance of 50 or greater
% from the origin
xlswrite('output_file.csv',rawData(index,:)); % Write those rows to a new file
Here is the snippet that I am using to get the MD5 for a given string:
$text = "text goes here..."
$md5 = [Security.Cryptography.MD5CryptoServiceProvider]::new()
$utf8 = [Text.UTF8Encoding]::UTF8
$bytes= $md5.ComputeHash($utf8.GetBytes($text))
$hash = [string]::Concat($bytes.foreach{$_.ToString("x2")})
You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do
pip install -U scikit-learn
If you are on windows you might want to check out these pages.
Well, I guess the question is, what do you mean by 'roll back'? If you can't reset
because it's public and you want to keep the commit history intact, do you mean you just want your working copy to reflect a specific commit? Use git checkout
and the commit hash.
Edit: As was pointed out in the comments, using git checkout
without specifying a branch will leave you in a "no branch" state. Use git checkout <commit> -b <branchname>
to checkout into a branch, or git checkout <commit> .
to checkout into the current branch.
The original DateTime field : [_Date_Time]
The converted to Shortdate : 'Short_Date'
CONVERT(date, [_Date_Time]) AS 'Short_Date'
I have 2 accounts on github, and here is what I did (on linux
) to make it work.
ssh-keygen
, name them properly, so that make life easier.ssh-add path_to_private_key
~/.ssh/config
Host github-kc
Hostname github.com
User git
IdentityFile ~/.ssh/github_rsa_kc.pub
# LogLevel DEBUG3
Host github-abc
Hostname github.com
User git
IdentityFile ~/.ssh/github_rsa_abc.pub
# LogLevel DEBUG3
Set remote url for repo:
For repo in Host github-kc
:
git remote set-url origin git@github-kc:kuchaguangjie/pygtrans.git
For repo in Host github-abc
:
git remote set-url origin git@github-abc:abcdefg/yyy.git
Options in ~/.ssh/config
:
Host
github-<identify_specific_user>
Host could be any value that could identify a host plus an account,
it don't need to be a real host,
e.g
github-kc
identify one of my account on github for my local
laptop,
When set remote url for a git repo, this is the value to put after git@
, that's how a repo maps to a Host, e.g git remote set-url origin git@github-kc:kuchaguangjie/pygtrans.git
Host
]Hostname
github.com
for github,User
git git
for github,IdentityFile
LogLevel
DEBUG3
gives the most detailed info.My personal cheatsheet, covering:
.offsetWidth
/.offsetHeight
.clientWidth
/.clientHeight
.scrollWidth
/.scrollHeight
.scrollLeft
/.scrollTop
.getBoundingClientRect()
with small/simple/not-all-in-one diagrams :)
see full-size: https://docs.google.com/drawings/d/1bOOJnkN5G_lBs3Oz9NfQQH1I0aCrX5EZYPY3mu3_ROI/edit?usp=sharing
I collected many topics to make universal function with many outputs (years, months, days, hours, minutes, seconds) with string or parse to int and direction +- if you need to know what side is direction of the difference.
Use example:
$date1='2016-05-27 02:00:00';
$format='Y-m-d H:i:s';
echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format);
#1 years 3 months 2 days 22 hours 1 minutes 59 seconds (string)
echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format,false, '%a days %h hours');
#459 days 22 hours (string)
echo timeDifference('2016-05-27 00:00:00', $format, '2017-08-30 00:01:59', $format,true, '%d days -> %H:%I:%S', true);
#-3 days -> 00:01:59 (string)
echo timeDifference($date1, $format, '2016-05-27 00:05:51', $format, false, 'seconds');
#9 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, false, 'hours');
#5 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours');
#-5 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours',true);
#-5 (int)
Function
function timeDifference($date1_pm_checked, $date1_format,$date2, $date2_format, $plus_minus=false, $return='all', $parseInt=false)
{
$strtotime1=strtotime($date1_pm_checked);
$strtotime2=strtotime($date2);
$date1 = new DateTime(date($date1_format, $strtotime1));
$date2 = new DateTime(date($date2_format, $strtotime2));
$interval=$date1->diff($date2);
$plus_minus=(empty($plus_minus)) ? '' : ( ($strtotime1 > $strtotime2) ? '+' : '-'); # +/-/no_sign before value
switch($return)
{
case 'y';
case 'year';
case 'years';
$elapsed = $interval->format($plus_minus.'%y');
break;
case 'm';
case 'month';
case 'months';
$elapsed = $interval->format($plus_minus.'%m');
break;
case 'a';
case 'day';
case 'days';
$elapsed = $interval->format($plus_minus.'%a');
break;
case 'd';
$elapsed = $interval->format($plus_minus.'%d');
break;
case 'h';
case 'hour';
case 'hours';
$elapsed = $interval->format($plus_minus.'%h');
break;
case 'i';
case 'minute';
case 'minutes';
$elapsed = $interval->format($plus_minus.'%i');
break;
case 's';
case 'second';
case 'seconds';
$elapsed = $interval->format($plus_minus.'%s');
break;
case 'all':
$parseInt=false;
$elapsed = $plus_minus.$interval->format('%y years %m months %d days %h hours %i minutes %s seconds');
break;
default:
$parseInt=false;
$elapsed = $plus_minus.$interval->format($return);
}
if($parseInt)
return (int) $elapsed;
else
return $elapsed;
}
For the general case of deeply nested lists with 3 or more levels like the ones obtained from a nested JSON:
{
"2015": {
"spain": {"population": 43, "GNP": 9},
"sweden": {"population": 7, "GNP": 6}},
"2016": {
"spain": {"population": 45, "GNP": 10},
"sweden": {"population": 9, "GNP": 8}}
}
consider the approach of melt()
to convert the nested list to a tall format first:
myjson <- jsonlite:fromJSON(file("test.json"))
tall <- reshape2::melt(myjson)[, c("L1", "L2", "L3", "value")]
L1 L2 L3 value
1 2015 spain population 43
2 2015 spain GNP 9
3 2015 sweden population 7
4 2015 sweden GNP 6
5 2016 spain population 45
6 2016 spain GNP 10
7 2016 sweden population 9
8 2016 sweden GNP 8
followed by dcast()
then to wide again into a tidy dataset where each variable forms a a column and each observation forms a row:
wide <- reshape2::dcast(tall, L1+L2~L3)
# left side of the formula defines the rows/observations and the
# right side defines the variables/measurements
L1 L2 GNP population
1 2015 spain 9 43
2 2015 sweden 6 7
3 2016 spain 10 45
4 2016 sweden 8 9
A cross platform 2D graphics library for .Net is The Little Vector Library You could use it in conjunction with Unity 3D (recommended) or Xamarin, for example, to create 2D graphics on a variety of platforms.
If I run the following:
echo '<?php echo $foo; ?>' | php
I get an error:
PHP Notice: Undefined variable: foo in /home/altern8/- on line 1
If I run the following:
echo '<?php if ( isset($foo) ) { echo $foo; } ?>' | php
I do not get the error.
If I have a variable that should be set, I usually do something like the following.
$foo = isset($foo) ? $foo : null;
or
if ( ! isset($foo) ) $foo = null;
That way, later in the script, I can safely use $foo and know that it "is set", and that it defaults to null. Later I can if ( is_null($foo) ) { /* ... */ }
if I need to and know for certain that the variable exists, even if it is null.
The full isset documentation reads a little more than just what was initially pasted. Yes, it returns false for a variable that was previously set but is now null, but it also returns false if a variable has not yet been set (ever) and for any variable that has been marked as unset. It also notes that the NULL byte ("\0") is not considered null and will return true.
Determine whether a variable is set.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
I've slightly modified Peter's answer here to create a reusable, non-interactive shell script called git-split.sh
:
#!/bin/sh
if [[ $# -ne 2 ]] ; then
echo "Usage: git-split.sh original copy"
exit 0
fi
git mv "$1" "$2"
git commit -n -m "Split history $1 to $2 - rename file to target-name"
REV=`git rev-parse HEAD`
git reset --hard HEAD^
git mv "$1" temp
git commit -n -m "Split history $1 to $2 - rename source-file to temp"
git merge $REV
git commit -a -n -m "Split history $1 to $2 - resolve conflict and keep both files"
git mv temp "$1"
git commit -n -m "Split history $1 to $2 - restore name of source-file"
Possible alternatives
js-floating-table-headers
js-floating-table-headers (Google Code)
In Drupal
I have a Drupal 6 site. I was on the admin "modules" page, and noticed the tables had this exact feature!
Looking at the code, it seems to be implemented by a file called tableheader.js
. It applies the feature on all tables with the class sticky-enabled
.
For a Drupal site, I'd like to be able to make use of that tableheader.js
module as-is for user content. tableheader.js
doesn't seem to be present on user content pages in Drupal. I posted a forum message to ask how to modify the Drupal theme so it's available. According to a response, tableheader.js
can be added to a Drupal theme using drupal_add_js()
in the theme's template.php
as follows:
drupal_add_js('misc/tableheader.js', 'core');
You don't "commit the folder" - you add the folder, as you have done, and then simply commit all changes. The command should be:
git add foldername
git commit -m "commit operation"
From what I understand the key difference is that live() keeps an eye open for new DOM elements that match the selector you are working on, whereas click() (or bind('click')) attach the event hook and are finished.
Given that alot of your code is loaded asynchronously, using live() will make your life alot easier. If you don't know exactly the code you are loading but you do know what kind of elements you will be listening to, then using this function makes perfect sense.
In terms of performance gains, one alternative to using live() would be to implement an AJAX callback function to re-bind the event hooks.
var ajaxCallback = function(){
$('*').unbind('click');
$('.something').bind('click', someFunction);
$('.somethingElse').bind('click', someOtherFunction);
}
You will need to keep proper track of your event hooks and make sure this function is rebinding the proper events.
p.s. Ajax methods .get(), .post(), .load() and .ajax() all let you specify a callback function.
NO,but there are some other options to implement default value. There are some good blog posts on the subject, but here are some specific examples.
// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
if a == "" {
a = "default-a"
}
if b == 0 {
b = 5
}
return fmt.Sprintf("%s%d", a, b)
}
// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional ...int) string {
b := 5
if len(b_optional) > 0 {
b = b_optional[0]
}
return fmt.Sprintf("%s%d", a, b)
}
// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
A string `default:"default-a"` // this only works with strings
B string // default is 5
}
func Concat3(prm Parameters) string {
typ := reflect.TypeOf(prm)
if prm.A == "" {
f, _ := typ.FieldByName("A")
prm.A = f.Tag.Get("default")
}
if prm.B == 0 {
prm.B = 5
}
return fmt.Sprintf("%s%d", prm.A, prm.B)
}
func Concat4(args ...interface{}) string {
a := "default-a"
b := 5
for _, arg := range args {
switch t := arg.(type) {
case string:
a = t
case int:
b = t
default:
panic("Unknown argument")
}
}
return fmt.Sprintf("%s%d", a, b)
}
If you don't overly care about the 'randomness' of the low-order bits, just rand() % HI_VAL.
Also:
(double)rand() / (double)RAND_MAX; // lazy way to get [0.0, 1.0)
Here is a list of available builds for debian: https://github.com/nodesource/distributions/tree/master/deb
For this example, lets assume you want version 14 (LTS at the time of writing)
We can download this script from github, execute it and install the version of node we want. For security reasons it's a good idea to read the script prior to executing it.
curl -sL https://raw.githubusercontent.com/nodesource/distributions/master/deb/setup_14.x | bash
apt-get install -y nodejs # may or may not require sudo based on your setup
I like this approach because it doesn't require extraneous dependencies like nvm to target specific versions
If you are building for a different distro or architecture you can find more builds here https://nodejs.org/dist/
function GetPixel(context, x, y)
{
var p = context.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
return hex;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
Several of the responses rely on an exception being thrown and having it handled in the OnException override. In my case, I wanted to return statuses such as bad request if the user, say, had passed in a bad ID. What works for me is to use the ControllerContext:
var jsonResult = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = "whoops" };
ControllerContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return jsonResult;
Depending on your needs, a simple divide-and-conquer strategy can be used. It won't converge as fast as some other methods but it may be a lot easier for a novice to understand. In addition, since it's an O(log n) algorithm (halving the search space each iteration), the worst case for a 32-bit float will be 32 iterations.
Let's say you want the square root of 62.104. You pick a value halfway between 0 and that, and square it. If the square is higher than your number, you need to concentrate on numbers less than the midpoint. If it's too low, concentrate on those higher.
With real math, you could keep dividing the search space in two forever (if it doesn't have a rational square root). In reality, computers will eventually run out of precision and you'll have your approximation. The following C program illustrates the point:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
float val, low, high, mid, oldmid, midsqr;
int step = 0;
// Get argument, force to non-negative.
if (argc < 2) {
printf ("Usage: sqrt <number>\n");
return 1;
}
val = fabs (atof (argv[1]));
// Set initial bounds and print heading.
low = 0;
high = mid = val;
oldmid = -1;
printf ("%4s %10s %10s %10s %10s %10s %s\n",
"Step", "Number", "Low", "High", "Mid", "Square", "Result");
// Keep going until accurate enough.
while (fabs(oldmid - mid) >= 0.00001) {
oldmid = mid;
// Get midpoint and see if we need lower or higher.
mid = (high + low) / 2;
midsqr = mid * mid;
printf ("%4d %10.4f %10.4f %10.4f %10.4f %10.4f ",
++step, val, low, high, mid, midsqr);
if (mid * mid > val) {
high = mid;
printf ("- too high\n");
} else {
low = mid;
printf ("- too low\n");
}
}
// Desired accuracy reached, print it.
printf ("sqrt(%.4f) = %.4f\n", val, mid);
return 0;
}
Here's a couple of runs so you hopefully get an idea how it works. For 77:
pax> sqrt 77
Step Number Low High Mid Square Result
1 77.0000 0.0000 77.0000 38.5000 1482.2500 - too high
2 77.0000 0.0000 38.5000 19.2500 370.5625 - too high
3 77.0000 0.0000 19.2500 9.6250 92.6406 - too high
4 77.0000 0.0000 9.6250 4.8125 23.1602 - too low
5 77.0000 4.8125 9.6250 7.2188 52.1104 - too low
6 77.0000 7.2188 9.6250 8.4219 70.9280 - too low
7 77.0000 8.4219 9.6250 9.0234 81.4224 - too high
8 77.0000 8.4219 9.0234 8.7227 76.0847 - too low
9 77.0000 8.7227 9.0234 8.8730 78.7310 - too high
10 77.0000 8.7227 8.8730 8.7979 77.4022 - too high
11 77.0000 8.7227 8.7979 8.7603 76.7421 - too low
12 77.0000 8.7603 8.7979 8.7791 77.0718 - too high
13 77.0000 8.7603 8.7791 8.7697 76.9068 - too low
14 77.0000 8.7697 8.7791 8.7744 76.9893 - too low
15 77.0000 8.7744 8.7791 8.7767 77.0305 - too high
16 77.0000 8.7744 8.7767 8.7755 77.0099 - too high
17 77.0000 8.7744 8.7755 8.7749 76.9996 - too low
18 77.0000 8.7749 8.7755 8.7752 77.0047 - too high
19 77.0000 8.7749 8.7752 8.7751 77.0022 - too high
20 77.0000 8.7749 8.7751 8.7750 77.0009 - too high
21 77.0000 8.7749 8.7750 8.7750 77.0002 - too high
22 77.0000 8.7749 8.7750 8.7750 76.9999 - too low
23 77.0000 8.7750 8.7750 8.7750 77.0000 - too low
sqrt(77.0000) = 8.7750
For 62.104:
pax> sqrt 62.104
Step Number Low High Mid Square Result
1 62.1040 0.0000 62.1040 31.0520 964.2267 - too high
2 62.1040 0.0000 31.0520 15.5260 241.0567 - too high
3 62.1040 0.0000 15.5260 7.7630 60.2642 - too low
4 62.1040 7.7630 15.5260 11.6445 135.5944 - too high
5 62.1040 7.7630 11.6445 9.7037 94.1628 - too high
6 62.1040 7.7630 9.7037 8.7334 76.2718 - too high
7 62.1040 7.7630 8.7334 8.2482 68.0326 - too high
8 62.1040 7.7630 8.2482 8.0056 64.0895 - too high
9 62.1040 7.7630 8.0056 7.8843 62.1621 - too high
10 62.1040 7.7630 7.8843 7.8236 61.2095 - too low
11 62.1040 7.8236 7.8843 7.8540 61.6849 - too low
12 62.1040 7.8540 7.8843 7.8691 61.9233 - too low
13 62.1040 7.8691 7.8843 7.8767 62.0426 - too low
14 62.1040 7.8767 7.8843 7.8805 62.1024 - too low
15 62.1040 7.8805 7.8843 7.8824 62.1323 - too high
16 62.1040 7.8805 7.8824 7.8815 62.1173 - too high
17 62.1040 7.8805 7.8815 7.8810 62.1098 - too high
18 62.1040 7.8805 7.8810 7.8807 62.1061 - too high
19 62.1040 7.8805 7.8807 7.8806 62.1042 - too high
20 62.1040 7.8805 7.8806 7.8806 62.1033 - too low
21 62.1040 7.8806 7.8806 7.8806 62.1038 - too low
22 62.1040 7.8806 7.8806 7.8806 62.1040 - too high
23 62.1040 7.8806 7.8806 7.8806 62.1039 - too high
sqrt(62.1040) = 7.8806
For 49:
pax> sqrt 49
Step Number Low High Mid Square Result
1 49.0000 0.0000 49.0000 24.5000 600.2500 - too high
2 49.0000 0.0000 24.5000 12.2500 150.0625 - too high
3 49.0000 0.0000 12.2500 6.1250 37.5156 - too low
4 49.0000 6.1250 12.2500 9.1875 84.4102 - too high
5 49.0000 6.1250 9.1875 7.6562 58.6182 - too high
6 49.0000 6.1250 7.6562 6.8906 47.4807 - too low
7 49.0000 6.8906 7.6562 7.2734 52.9029 - too high
8 49.0000 6.8906 7.2734 7.0820 50.1552 - too high
9 49.0000 6.8906 7.0820 6.9863 48.8088 - too low
10 49.0000 6.9863 7.0820 7.0342 49.4797 - too high
11 49.0000 6.9863 7.0342 7.0103 49.1437 - too high
12 49.0000 6.9863 7.0103 6.9983 48.9761 - too low
13 49.0000 6.9983 7.0103 7.0043 49.0598 - too high
14 49.0000 6.9983 7.0043 7.0013 49.0179 - too high
15 49.0000 6.9983 7.0013 6.9998 48.9970 - too low
16 49.0000 6.9998 7.0013 7.0005 49.0075 - too high
17 49.0000 6.9998 7.0005 7.0002 49.0022 - too high
18 49.0000 6.9998 7.0002 7.0000 48.9996 - too low
19 49.0000 7.0000 7.0002 7.0001 49.0009 - too high
20 49.0000 7.0000 7.0001 7.0000 49.0003 - too high
21 49.0000 7.0000 7.0000 7.0000 49.0000 - too low
22 49.0000 7.0000 7.0000 7.0000 49.0001 - too high
23 49.0000 7.0000 7.0000 7.0000 49.0000 - too high
sqrt(49.0000) = 7.0000
function get_mime($file) {
if (function_exists("finfo_file")) {
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mime = finfo_file($finfo, $file);
finfo_close($finfo);
return $mime;
} else if (function_exists("mime_content_type")) {
return mime_content_type($file);
} else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
// http://stackoverflow.com/a/134930/1593459
$file = escapeshellarg($file);
$mime = shell_exec("file -bi " . $file);
return $mime;
} else {
return false;
}
}
For me, nothing of this does work - mime_content_type
is deprecated, finfo
is not installed, and shell_exec
is not allowed.
It's unclear if the original problem was the same problem I had: wanting to max CPU threads on computation inside a loop while preserving the iterator's value and keeping inline to avoid passing a ton of variables to a worker function.
for (int i = 0; i < 300; i++)
{
Task.Run(() => {
var x = ComputeStuff(datavector, i); // value of i was incorrect
var y = ComputeMoreStuff(x);
// ...
});
}
I got this to work by changing the outer iterator and localizing its value with a gate.
for (int ii = 0; ii < 300; ii++)
{
System.Threading.CountdownEvent handoff = new System.Threading.CountdownEvent(1);
Task.Run(() => {
int i = ii;
handoff.Signal();
var x = ComputeStuff(datavector, i);
var y = ComputeMoreStuff(x);
// ...
});
handoff.Wait();
}
Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;
. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.
SendRedirect()
will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.
RquestDispatcher
is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect()
method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.
In SQL Server 2008, you can use:
CONVERT(DATE, getdate(), 101)
This might not be the exact thing you are looking for, but you can create a very similar effect by using rgba
in combination with linear-gradient
:
background: linear-gradient(rgba(0,0,0,.5) 0%, rgba(0,0,0,0) 30%);
This creates a linear-gradient from black with 50% opacity (rgba(0,0,0,.5)
) to transparent (rgba(0,0,0,0)
) which starts being competently transparent 30% from the top. You can play with those values to create your desired effect. You can have it on a different side by adding a deg-value (linear-gradient(90deg, rgba(0,0,0,.5) 0%, rgba(0,0,0,0) 30%)
) or switching the colors around. If you want really complex shadows like different angles on different sides you could even start layering linear-gradient
.
Here is a snippet to see it in action:
.box {_x000D_
background: linear-gradient(rgba(0,0,0,.5) 0%, rgba(0,0,0,0) 30%);_x000D_
}_x000D_
_x000D_
.text {_x000D_
padding: 20px;_x000D_
}
_x000D_
<div class="box">_x000D_
<div class="text">_x000D_
Lorem ipsum ...._x000D_
</div>_x000D_
</div>
_x000D_
It might be a wrong path. Ensure in your main app file you have:
app.use(express.static(path.join(__dirname,"public")));
Example link to your css as:
<link href="/css/clean-blog.min.css" rel="stylesheet">
similar for link to js files:
<script src="/js/clean-blog.min.js"></script>
This is an old topic, but in case anyone else is still looking...
I was having trouble after an undock event. An open db connection saved in a global object would error, even after reconnecting to the network. This was due to the TCP connection being forcibly terminated by remote host. (Error -2147467259: TCP Provider: An existing connection was forcibly closed by the remote host.)
However, the error would only show up after the first transaction was attempted. Up to that point, neither Connection.State nor Connection.Version (per solutions above) would reveal any error.
So I wrote the small sub below to force the error - hope it's useful.
Performance testing on my setup (Access 2016, SQL Svr 2008R2) was approx 0.5ms per call.
Function adoIsConnected(adoCn As ADODB.Connection) As Boolean
'----------------------------------------------------------------
'#PURPOSE: Checks whether the supplied db connection is alive and
' hasn't had it's TCP connection forcibly closed by remote
' host, for example, as happens during an undock event
'#RETURNS: True if the supplied db is connected and error-free,
' False otherwise
'#AUTHOR: Belladonna
'----------------------------------------------------------------
Dim i As Long
Dim cmd As New ADODB.Command
'Set up SQL command to return 1
cmd.CommandText = "SELECT 1"
cmd.ActiveConnection = adoCn
'Run a simple query, to test the connection
On Error Resume Next
i = cmd.Execute.Fields(0)
On Error GoTo 0
'Tidy up
Set cmd = Nothing
'If i is 1, connection is open
If i = 1 Then
adoIsConnected = True
Else
adoIsConnected = False
End If
End Function
System.IO.Path.GetRandomFileName()
Something like this...
var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;
See also LINQ query on a DataTable
The problem seems to be in the way how ng-model
works with input
and overwrites the name
object, making it lost for ng-repeat
.
As a workaround, one can use the following code:
<div ng-repeat="name in names">
Value: {{name}}
<input ng-model="names[$index]">
</div>
Hope it helps
where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month
where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)
You can use following format:
<connectionStrings>
<add name="ConStringBDName" connectionString="Data Source=serverpath;Initial Catalog=YourDataBaseName;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
Most probably you will fing connectionstring tag in web.config after <appSettings>
Try out this.
Lookup pom.xml > project tag > build tag.
I would like solution below.
<artifactId>bird</artifactId>
<name>bird</name>
<build>
...
<finalName>${project.artifactId}</finalName>
OR
<finalName>${project.name}</finalName>
...
</build>
Worked for me. ^^
The blick tag is deprecated, and the effect is kind of old :) Current browsers don't support it anymore. Anyway, if you need the blinking effect, you should use javascript or CSS solutions.
CSS Solution
blink {_x000D_
animation: blinker 0.6s linear infinite;_x000D_
color: #1c87c9;_x000D_
}_x000D_
@keyframes blinker { _x000D_
50% { opacity: 0; }_x000D_
}_x000D_
.blink-one {_x000D_
animation: blinker-one 1s linear infinite;_x000D_
}_x000D_
@keyframes blinker-one { _x000D_
0% { opacity: 0; }_x000D_
}_x000D_
.blink-two {_x000D_
animation: blinker-two 1.4s linear infinite;_x000D_
}_x000D_
@keyframes blinker-two { _x000D_
100% { opacity: 0; }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Title of the document</title>_x000D_
</head>_x000D_
<body>_x000D_
<h3>_x000D_
<blink>Blinking text</blink>_x000D_
</h3>_x000D_
<span class="blink-one">CSS blinking effect for opacity starting with 0%</span>_x000D_
<p class="blink-two">CSS blinking effect for opacity starting with 100%</p>_x000D_
</body>_x000D_
</html>
_x000D_
sourse: HTML blink Tag
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable
whereas
PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments
However, there are pros and cons to both and one should choose as per their specific use case.
I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.
VAR1=value1 VAR2=value2 myScript args ...
It sounds like you're trying to SELECT
a column that doesn't exist.
Perhaps you're trying to ORDER BY
a column that doesn't exist?
Any typos in your SQL statement?
I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you settings.py:
MEDIA_ROOT = "<path_to_files>" (i.e. /home/project/django/app/templates/static)
MEDIA_URL = "http://localhost:8000/static/"
*(remember that MEDIA_ROOT is where the files are and MEDIA_URL is a constant that you use in your templates.)*
Then in you url.py place the following:
import settings
# stuff
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
Then in your html you can use:
<img src="{{ MEDIA_URL }}foo.jpg">
The way django works (as far as I can figure is:
The jQuery selector for all h tags (h1, h2 etc) is " :header ". For example, if you wanted to make all h tags red in color with jQuery, use:
$(':header').css("color","red")
_x000D_
The IF
statement does not support logical operators AND
and OR
.
Cascading IF
statements make an implicit conjunction:
IF Exist File1.Dat IF Exist File2.Dat GOTO FILE12_EXIST_LABEL
If File1.Dat
and File2.Dat
exist then jump to the label FILE12_EXIST_LABEL
.
See also: IF /?
You have to actually call some method to create the directories. Just creating a file
object will not create the corresponding file or directory on the file system.
You can use File#mkdirs()
method to create the directory: -
theFile.mkdirs();
Difference between File#mkdir()
and File#mkdirs()
is that, the later will create any intermediate directory if it does not exist.
Note, this method has been deprecated for more recent versions of django! (> 1.3)
An alternative answer, you could add this to the top of my_script.py
from django.core.management import setup_environ
import settings
setup_environ(settings)
and execute my_script.py
just with python in the directory where you have settings.py
but this is a bit hacky.
$ python my_script.py
Generally the first 2 package "words" are your web address in reverse. (You'd have 3 here as convention, if you had a subdomain.)
So something stackoverflow produces would likely be in package com.stackoverflow.whatever.customname
something asp.net produces might be called net.asp.whatever.customname.omg.srsly
something from mysubdomain.toplevel.com would be com.toplevel.mysubdomain.whatever
Beyond that simple convention, the sky's the limit. This is an old linux convention for something that I cannot recall exactly...
In many cases an element must be positioned for z-index
to work.
Indeed, applying position: relative
to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).
Actually, position: fixed
, position: absolute
and position: sticky
will also enable z-index
, but those values also change the layout. With position: relative
the layout isn't disturbed.
Essentially, as long as the element isn't position: static
(the default setting) it is considered positioned and z-index
will work.
Many answers to "Why isn't z-index working?" questions assert that z-index
only works on positioned elements. As of CSS3, this is no longer true.
Elements that are flex items or grid items can use z-index
even when position
is static
.
From the specs:
Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.5.4. Z-axis Ordering: the
z-index
propertyThe painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.
Here's a demonstration of z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/
The Public Key is not stored in the PEM file as some people think. The following DER structure is present on the Private Key File:
openssl rsa -text -in mykey.pem
RSAPrivateKey ::= SEQUENCE {
version Version,
modulus INTEGER, -- n
publicExponent INTEGER, -- e
privateExponent INTEGER, -- d
prime1 INTEGER, -- p
prime2 INTEGER, -- q
exponent1 INTEGER, -- d mod (p-1)
exponent2 INTEGER, -- d mod (q-1)
coefficient INTEGER, -- (inverse of q) mod p
otherPrimeInfos OtherPrimeInfos OPTIONAL
}
So there is enough data to calculate the Public Key (modulus and public exponent), which is what openssl rsa -in mykey.pem -pubout
does
What you can also do is to use apt-get:
apt-get install python3-pip
In my experience this works pretty fluent too, plus you get all the benefits from apt-get.
Something like this - for each line read into string variable a
:
>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456
Now you can do what is necessary with x
and y
as assigned, which are integers.
I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month!
e.g.: CONVERT(Datetime, '2015-06-31')
caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.
You could wrap your h1
tags in another div
and then the first one would be the first-child
. That div
doesn't even need styles. It's just a way to segregate those children.
<div class="h1-holder">
<h1>Title 1</h1>
<h1>Title 2</h1>
</div>
This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.
Also the foreach examples will throw a warning when using strict PHP error handling.
Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.
function multi_rename_key(&$array, $old_keys, $new_keys)
{
if(!is_array($array)){
($array=="") ? $array=array() : false;
return $array;
}
foreach($array as &$arr){
if (is_array($old_keys))
{
foreach($new_keys as $k => $new_key)
{
(isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
$arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
unset($arr[$old_keys[$k]]);
}
}else{
$arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
unset($arr[$old_keys]);
}
}
return $array;
}
Usage is simple. You can either change a single key like in your example:
multi_rename_key($tags, "url", "value");
or a more complex multikey
multi_rename_key($tags, array("url","name"), array("value","title"));
It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.
Use this all the time, hope it helps!
check whether you import FormsModule. There's no ngControl in the new forms angular 2 release version. you have to change your template to as an example
<div class="row">
<div class="form-group col-sm-7 col-md-5">
<label for="name">Name</label>
<input type="text" class="form-control" required
[(ngModel)]="user.name"
name="name" #name="ngModel">
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
Name is required
</div>
</div>
</div>
Like this:
{% if age > 18 %}
{% with patient as p %}
<my html here>
{% endwith %}
{% else %}
{% with patient.parent as p %}
<my html here>
{% endwith %}
{% endif %}
If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:
p = (age > 18 && patient) or patient.parent
and then just use {{ p }} in the template.
CodePress does this, as does EditArea. Both are open source.
With docker 1.3, there is a new command docker exec
. This allows you to enter a running container:
docker exec -it [container-id] bash
SVG animations are probably a better solution to this problem. You won't need to worry about writing CSS and compared to GIFs, you'll get better resolution and alpha transparency. Some very good SVG loading animations that you can use are here: http://samherbert.net/svg-loaders/
You can also use those animations directly through a service I built: https://svgbox.net/iconset/loaders. It allows you to customize the fill and direct usage (hotlinking) is permitted.
To accomplish what you want to do with jQuery, you probably should have a loading info element hidden and use .show()
when you want to show the loader. For eg, this code shows the loader after one second:
setTimeout(function() {
$("#load").show();
}, 1000)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="load" style="display:none">
Please wait...
<img src="//s.svgbox.net/loaders.svg?fill=maroon&ic=tail-spin"
style="width:24px">
</div>
_x000D_
i would recommend Modern UI for WPF .
It has a very active maintainer it is awesome and free!
I'm currently porting some projects to MUI, first (and meanwhile second) impression is just wow!
To see MUI in action you could download XAML Spy which is based on MUI.
EDIT: Using Modern UI for WPF a few months and i'm loving it!
Try downloading the certificates/profiles directly from the member centre rather than doing it from Xcode.
It worked for me when I manually downloaded them from the member centre.
You can simply use background
CSS property as follows:
tr:hover{
background: #F1F1F2;
}
with 'nonlocal' inner functions(ie;nested inner functions) can get read & 'write' permission for that specific variable of the outer parent function. And nonlocal can be used only inside inner functions eg:
a = 10
def Outer(msg):
a = 20
b = 30
def Inner():
c = 50
d = 60
print("MU LCL =",locals())
nonlocal a
a = 100
ans = a+c
print("Hello from Inner",ans)
print("value of a Inner : ",a)
Inner()
print("value of a Outer : ",a)
res = Outer("Hello World")
print(res)
print("value of a Global : ",a)
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?
) as the request body.
This requires Content-Type
and Content-Length
headers, so the receiving server knows how to interpret the incoming data. (*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded
for the traditional format that a standard HTML form would use.
It's easy to send JSON (application/json
) in exactly the same manner; just JSON.stringify()
the data beforehand.
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
The bottom line is: The server must be able to interpret the content type in question. It could be text/plain
or anything else; there is no need to convert data if the receiving server understands it as it is.
Add a charset parameter (e.g. application/json; charset=Windows-1252
) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
you might want to start with max(trans_seq_no) + 1.
watch:
SQL> create table my_numbers(my_number number not null primary key);
Table created.
SQL> insert into my_numbers(select rownum from user_objects);
260 rows created.
SQL> select max(my_number) from my_numbers;
MAX(MY_NUMBER)
--------------
260
SQL> create sequence my_number_sn start with 260;
Sequence created.
SQL> insert into my_numbers(my_number) values (my_number_sn.NEXTVAL);
insert into my_numbers(my_number) values (my_number_sn.NEXTVAL)
*
ERROR at line 1:
ORA-00001: unique constraint (NEIL.SYS_C00102439) violated
When you create a sequence with a number, you have to remember that the first time you select against the sequence, Oracle will return the initial value that you assigned it.
SQL> drop sequence my_number_sn;
Sequence dropped.
SQL> create sequence my_number_sn start with 261;
Sequence created.
SQL> insert into my_numbers(my_number) values (my_number_sn.NEXTVAL);
1 row created.
If you're trying to do the 'gapless' thing, I strongly advise you to
pip3 install "package_name" -t "target_dir"
source - https://pip.pypa.io/en/stable/reference/pip_install/
-t switch = target
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
First you will need to install node definitions for Typescript. You can find the definitions file here:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts
Once you've got file, just add the reference to your .ts
file like this:
/// <reference path="path/to/node.d.ts" />
Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts
can look like this:
/// <reference path="path/to/node.d.ts" />
class MyClass {
// Here we import the File System module of node
private fs = require('fs');
constructor() { }
createFile() {
this.fs.writeFile('file.txt', 'I am cool!', function(err) {
if (err) {
return console.error(err);
}
console.log("File created!");
});
}
showFile() {
this.fs.readFile('file.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
}
}
// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();
Once you transpile your .ts
file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:
> node myClass.js
Entity interface
public interface Entity<I> extends Serializable {
/**
* @return entity identity
*/
I getId();
/**
* @return HashCode of entity identity
*/
int identityHashCode();
/**
* @param other
* Other entity
* @return true if identities of entities are equal
*/
boolean identityEquals(Entity<?> other);
}
Basic implementation for all Entities, simplifies Equals/Hashcode implementations:
public abstract class AbstractEntity<I> implements Entity<I> {
@Override
public final boolean identityEquals(Entity<?> other) {
if (getId() == null) {
return false;
}
return getId().equals(other.getId());
}
@Override
public final int identityHashCode() {
return new HashCodeBuilder().append(this.getId()).toHashCode();
}
@Override
public final int hashCode() {
return identityHashCode();
}
@Override
public final boolean equals(final Object o) {
if (this == o) {
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
return identityEquals((Entity<?>) o);
}
@Override
public String toString() {
return getClass().getSimpleName() + ": " + identity();
// OR
// return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
Room Entity impl:
@Entity
@Table(name = "ROOM")
public class Room extends AbstractEntity<Integer> {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "room_id")
private Integer id;
@Column(name = "number")
private String number; //immutable
@Column(name = "capacity")
private Integer capacity;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "building_id")
private Building building; //immutable
Room() {
// default constructor
}
public Room(Building building, String number) {
// constructor with required field
notNull(building, "Method called with null parameter (application)");
notNull(number, "Method called with null parameter (name)");
this.building = building;
this.number = number;
}
public Integer getId(){
return id;
}
public Building getBuilding() {
return building;
}
public String getNumber() {
return number;
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
//no setters for number, building nor id
}
I don't see a point of comparing equality of entities based on business fields in every case of JPA Entities. That might be more of a case if these JPA entities are thought of as Domain-Driven ValueObjects, instead of Domain-Driven Entities (which these code examples are for).
You can't avoid polling, there isn't any event for href change.
Using intervals is quite light anyways if you don't go overboard. Checking the href every 50ms or so will not have any significant effect on performance if you're worried about that.
After replacing the character, you need to be asign to the variable.
var tt = "88,9827";
tt = tt.replace(/,/g, '.')
alert(tt)
In the alert box it will shows 88.9827
If your data changes a lot, you can use
mAdapter.notifyItemRangeChanged(0, yourData.size());
or some single items in your data set changes, your can use
mAdapter.notifyItemChanged(pos);
For detailed methods usage, you can refer the doc, in a way, try not to directly use mAdapter.notifyDataSetChanged()
.
This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.
To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.
For CMake 3.13 or newer, run the following commands:
cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release
For earlier versions of CMake, run the following commands:
mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release
CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build
followed by the build directory. The --config
option specifies the build configuration.
Also we can try like this,
string[] selectedColumns = new[] { "Column1","Column2"};
DataTable dt= new DataView(fromDataTable).ToTable(false, selectedColumns);
You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl"
android:state_pressed="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_checked="true"/>
<item android:drawable="@drawable/sub_screens_aus"
android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />
</selector>
Here you can use 3 different images for radiobutton
and use this file to RadioButton like:
android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content"
I use testproxy to do this.
npm install testproxy
testproxy http://10.0.2.2
You then get the url (and QR code) you can access on your mobile device. It even works with virtual machines you can't reach by just entering the IP of your dev machine.
You can also do
console.log("a = %o, b = %o", a, b);
where a and b are objects.
You can use the static method Enum.GetNames
which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum
var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;
In jQuery you can do like this.
function random_no(){_x000D_
var ran=Math.random();_x000D_
jQuery('#random_no_container').html(ran);_x000D_
}_x000D_
_x000D_
window.setInterval(function(){_x000D_
/// call your function here_x000D_
random_no();_x000D_
}, 6000); // Change Interval here to test. For eg: 5000 for 5 sec
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="random_no_container">_x000D_
Hello. Here you can see random numbers after every 6 sec_x000D_
</div>
_x000D_
This is not intended to directly answer the OP, but I wanted to share some related ideas.
I was very interested in @steveha answer above, which seemed to give an example where duck typing seems to break. On second thought, however, his example suggests that duck typing is hard to conform to, but it does not suggest that str
deserves any special handling.
After all, a non-str
type (e.g., a user-defined type that maintains some complicated recursive structures) may cause @steveha srepr
function to cause an infinite recursion. While this is admittedly rather unlikely, we can't ignore this possibility. Therefore, rather than special-casing str
in srepr
, we should clarify what we want srepr
to do when an infinite recursion results.
It may seem that one reasonable approach is to simply break the recursion in srepr
the moment list(arg) == [arg]
. This would, in fact, completely solve the problem with str
, without any isinstance
.
However, a really complicated recursive structure may cause an infinite loop where list(arg) == [arg]
never happens. Therefore, while the above check is useful, it's not sufficient. We need something like a hard limit on the recursion depth.
My point is that if you plan to handle arbitrary argument types, handling str
via duck typing is far, far easier than handling the more general types you may (theoretically) encounter. So if you feel the need to exclude str
instances, you should instead demand that the argument is an instance of one of the few types that you explicitly specify.
C++ has Automatic variables - not Stack variables.
Automatic variable means that C++ compiler handles memory allocation / free by itself. C++ can automatically handle objects of any class - no matter whether it has dynamically allocated members or not. It's achieved by strong guarantee of C++ that object's destructor will be called automatically when execution is going out of scope where automatic variable was declared. Inside of a C++ object can be a lot of dynamic allocations with new
in constructor, and when such an object is declared as an automatic variable - all dynamic allocations will be performed, and freed then in destructor.
Stack variables in C can't be dynamically allocated. Stack in C can store pointers, or fixed arrays or structs - all of fixed size, and these things are being allocated in memory in linear order. When a C program frees a stack variable - it just moves stack pointer back and nothing more.
Even though C++ programs can use Stack memory segment for storing primitive types, function's args, or other, - it's all decided by C++ compiler, not by program developer. Thus, it is conceptually wrong to equal C++ automatic variables and C stack variables.
I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post.
You can also use something like Bugsnag to track your uncaught exceptions and be notified via email, chatroom or have a ticket created for an uncaught exception (I am the co-founder of Bugsnag).
This might be optimal
public static string GetPropertyName<TResult>(Expression<Func<TResult>> expr)
{
var memberAccess = expr.Body as MemberExpression;
var propertyInfo = memberAccess?.Member as PropertyInfo;
var propertyName = propertyInfo?.Name;
return propertyName;
}
It seems like an IllegalArgumentException
is called for if you don't want null
to be an allowed value, and the NullPointerException
would be thrown if you were trying to use a variable that turns out to be null
.
You can access elements using $document ($document need to be injected)
var target = $document('#appBusyIndicator');
var target = $document('appBusyIndicator');
or with angular element, the specified elements can be accessed as:
var targets = angular.element(document).find('div'); //array of all div
var targets = angular.element(document).find('p');
var target = angular.element(document).find('#appBusyIndicator');
Use two periods before /
, example:
../style.css
Take a look at this: slide ExpandableListView at DrawerLayout form right to left
I assume you have the ActionBarDrawerToggle implemented, the trick is to override the onOptionsItemSelected(MenuItem item)
method inside the ActionBarDrawerToggle object with this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (mDrawer.isDrawerOpen(Gravity.RIGHT)) {
mDrawer.closeDrawer(Gravity.RIGHT);
} else {
mDrawer.openDrawer(Gravity.RIGHT);
}
return true;
}
return false;
}
make sure and call this from onOptionsItemSelected(MenuItem item)
in the Activity:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
This will allow you to use the the home button functionality. To move the button to the right side of the action bar you will have to implement a custom action item, and maybe some other stuff to get it to work like you want.
I had the same issue. I think it would be appropriate to check whether your class can be compiled or not. Click recompile (Ctrl+Shift+F9 by default). If its not working then you have to investigate why it isn't compiling.
In my case the code wasn't autocompiling because there were hidden errors with compilation (they weren't shown in logs anywhere and maven clean-install was working). The rootcause was incorrect Project Structure -> Modules configuration, so Intellij Idea wasn't able to build it according to this configuration.