text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Java Quiz: Introducing Mathematical Tricks
Java Quiz: Introducing Mathematical Tricks
The latest advanced Java quiz from DZone's resident quizmaster!
Join the DZone community and get the full member experience.Join For Free
How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.
Last Week's Answer
First Method: mc.method(3)
int x = 0; if(i > 2) //3 > 2 is true; i = (1 / 0) + Integer.parseInt("x"); //The first part of this equation is dividing by 0. //That is why the exception is handled by the “ArithmeticException” block. x += 4; x = 4; //Finally and the last statement are always executed: x = 4+2+1=7;
Second Method: mc.method(2)
//2 > 2 is false i = Integer.parseInt("x") + (1 / 0); //The first part of the exception would be handled in the “RuntimeException” block not in the “ArithmeticException” block. See the RuntimeException hirarchy Java library. X = 7+3 = 10 //finally and the last statement are always executed, that is why the end result is: 10 + 2 + 1 = 13
This Week's Quiz
Purpose
Demonstrating a trick that might distract programmers.
Helps to stay focused by programming.
What is written to the standard output as a result of executing the following code?
public class MyClass { int x; int[] arrayInt = {4,3,0 }; int methodA(int i, int i2){ int i3 = i + i2 - 1; return(i3 - (2 * i) / x - x / 2); } int methodB(){ for(int i:arrayInt) { switch(i) { case 3: x ++ ; case 5: x += 2; break; default: x += 3; case 0: x += 4; case 1: x += 5; } } return x / 2; } public static void main(String[] args){ MyClass mc = new MyClass(); System.out.println("result: " + mc.methodA(mc.methodB(),2)); } }
Let us know your thoughts in the comments, and check out Sar's site }} | https://dzone.com/articles/java-quiz-introducing-mathematical-tricks | CC-MAIN-2018-34 | refinedweb | 304 | 63.8 |
In this article we'll look at how to define EarthAI Catalog API queries using vector files that you import into the EarthAI Notebook environment from an external source. It is often useful in geospatial analysis to associate raster data with vector shapes and their attributes. In this case we'll use the polygons of two U.S. states, Florida and Washington, then use these to query the EarthAI Catalog.
We'll start by importing the needed libraries.
from earthai.init import *
import pyspark.sql.functions as F
import geopandas as gpd
import pandas as pd
%matplotlib inline
The first step in the workflow is reading in the vector data we'll use to query the imagery catalog. We will read in these data from a GeoJSON file by referencing its URL and loading it into a GeoPandas DataFrame. We will use state polygons from Natural Earth, which we access through DataHub.io. Note that you can also upload the GeoJSON file into EarthAI Notebook and access it locally if you prefer.
To get the URL, go to. You will see an embedded web map as shown in the screenshot below.
Click on the Raw tab in the upper right of the embedded web map; this will open the raw GeoJSON file in a web browser. Copy this URL and assign a variable to it. You can then load the geometries into a GeoPandas DataFrame.
states_url = ''
states_df = gpd.read_file(states_url)
Now select the desired states, downsample to the area of interest, and save it to a new DataFrame.
We selected Florida and Washington here, but you can choose whichever state(s) you like for this exercise. In the code below, we're using the condition that the "state_code" attribute is in the list of the states abbreviations we want, and only selecting that data. You can plot the state outlines to confirm the shapes.
states_flwa = states_df[states_df.state_code.isin(['FL', 'WA'])]
states_flwa.plot()
Now we have geographic constraints for an EarthAI Catalog query, namely the geographic areas of Florida and Washington. These are be geometry coordinates of the two polygons representing the states. We'll query using specified start and end dates, a maximum cloud cover, and the Landsat 8 collection. For the "geo" argument we'll simply pass in our selected states vector data.
catalog = earth_ondemand.read_catalog(
states_flwa,
start_datetime = '2018-01-01',
end_datetime = '2018-03-31',
max_cloud_cover = 10,
collections = 'landsat8_l1tp')
The "geo" argument is very flexible and can take a wide range of vector geometry representations such as GeoPandas DataFrames and Well-known text (WKT).
Now we need to attach the states' features information to the imagery catalog generated from our query. We'll do this using a spatial join in GeoPandas. Part of this involves ensuring both the imagery and the vector data are in the same coordinate reference system (CRS). In this case we'll convert the query catalog's CRS to the states' vector data CRS. You can also check that the resulting join is still a GeoPandas DataFrame.
states_catalog = gpd.sjoin(states_flwa, catalog.to_crs(states_flwa.crs))
type(states_catalog)
We'll also quickly check to see how many images were returned for each state from the query. The resulting line of code shows that there are 48 images for Florida and 11 for Washington.
states_catalog.groupby('state_code').count().name
Just as another check look to see what columns (attributes) are in the newly joined DataFrame.
states_catalog.columns
For this exercise, we're interested in the short-wave and near-IR bands of Landsat 8 for our raster data. For clarity we'll check what the band names are in Landsat 8 and then convert those to common names.
earth_ondemand.bands('landsat8_l1tp')
For Landsat 8, the near-IR ('nir') corresponds to band 'B5' and shortwave-IR ('swir16') corresponds to band 'B6'. We'll now read these two raster bands (B5 and B6) into a new SparkDataFrame, df, and then rename each column with the common names.
df = spark.read.raster(states_catalog, catalog_col_names=['B6', 'B5']) \
.withColumnRenamed('B6', 'swir16').withColumnRenamed('B5', 'nir')
Finally, we'll create a new column in the df DataFrame that reprojects the state polygons to the same CRS as the imagery data. This column is called "geo_native". We'll also filter out rows in the DataFrame where the image does not cover the entire state and include a filter to remove fill values that appear in Landsat imagery. The fill values are the result of null values in the imagery data.
df = df.withColumn('geo_native',
st_reproject('geometry', rf_mk_crs(str(states_flwa.crs)), rf_crs('swir16'))) \
.filter(st_intersects(rf_geometry('swir16'), 'geo_native')).filter(rf_tile_max('swir16') > 0)
Now look at the first five rows of the data. The code below shows the shortwave-IR and near-IR bands along with the state name and state code. It also shows the coordinates of the center of the state and the tile center. Since these first five are all for Florida the state center remains the same for each, but the tiles (each row) represent different portions of the larger scenes. As such, the center of the tiles will vary.
df.select('swir16', 'nir', 'state_code', 'name', st_centroid('geo_native') \
.alias('state_center'), st_centroid(rf_geometry('swir16')) \
.alias('tile_center'))
Please sign in to leave a comment. | https://docs.astraea.earth/hc/en-us/articles/360043914832-Query-the-EarthAI-Catalog-using-a-Vector-File | CC-MAIN-2021-31 | refinedweb | 870 | 55.74 |
Opened 9 years ago
Last modified 3 years ago
#624 reopened enhancement
Add Latent BuildSlave for DRMAA supporting systems
Description (last modified by dustin)
Supplied are two modules drmaabuildslave - contains a basic latent buildslave which uses a DRMA api (Requires the drmaa python module)
sgebuildslave - a latent drmaa buildslave, extended for Grid Engine - a popular open-source distribution system by Sun
Attachments (7)
Change History (35)
Changed 9 years ago by smackware
Changed 9 years ago by smackware
drmaabuildslave.py
comment:1 Changed 9 years ago by dustin
- Milestone changed from undecided to 0.8.+
smackware - can you provide some snippets of documentation that I can include in the manual?
comment:2 Changed 8 years ago by dustin
- Keywords drmaa grid sge removed
- Priority changed from trivial to major
comment:3 Changed 8 years ago by dustin
- Keywords virtualization added; latent removed
comment:4 Changed 7 years ago by dustin
As a reminder, hopefully we can get this documented and merged soon!
comment:5 Changed 6 years ago by dustin
- Resolution set to wontfix
- Status changed from new to closed
No response for quite a while -- feel free to re-open if there's further work on this.
comment:6 Changed 5 years ago by mvpel
My colleague has implemented DRMAA-based latent slaves in 0.8.4p2, and we're about to port it to 0.8.8 on Monday. He said it was very easy to implement, and it's working fine with Grid Engine now, and we'll be using it with HTCondor after the upgrade.
comment:7 Changed 5 years ago by dustin
Sounds good - do you want to re-open this?
comment:8 Changed 5 years ago by mvpel
Yeah, let's reopen, why not?
I got the attached code working with just a small bit of change to fix the lack of a delay and status-checking mechanism that caused the master to not wait for the slave to be scheduled and dispatched before giving up on it, and reporting that it failed to substantiate. I'll provide an updated file later.
I also adapted the sgebuildslave.py into an htcondorbuildslave.py, though my lack of familiarity with Python is tripping me up a bit - I need to figure out how to pass arguments to the buildslave_setup_command, or set environment variables, since I need to provide it with the slave name. I've got an ugly little hack in there at the moment.
For the slave names, I'm using "LatentSlave01" through "LatentSlave16" (we have several different builds), rather than host names (hence my need for a setup-command argument), since a given latent slave could wind up running on any of the exec hosts in the pool (we'll have 42 when finished), and it's preferable to avoid having to update the slave list every time an exec host is added or removed.
The slave is created fresh by the buildslave_setup_command script each time a latent slave starts. The setup command runs "buildslave create-slave" using the HTCondor-managed scratch directory, and then execs the buildslave in there. HTCondor takes care of deleting that directory when the job exits or is terminated. I also have a bit of code that creates the info/host file so you can tell which exec host the slave wound up on.
I've noticed that when the slave terminates, it's marked as "removed" in the HTCondor history. I'd prefer to have the slave shut itself down gracefully rather than being killed off through the scheduler, so that HTCondor will see it as "completed," rather than "removed."
I'm also trying to figure out if it's possible to have the slave do the checkout and build in the buildslave's HTCondor scratch directory, and then use the file transfer for anything that needs to go back to the master. The catch is that the master won't know the name of that directory, and in fact it won't be created at all until the slave starts up, so the master-side checkouts from buildbot.steps.source.svn.SVN may not play well. I'm not entirely clear on how the checkout mechanism works yet.
comment:9 Changed 5 years ago by mvpel
When creating the DRMAA session in the master.cfg, the reconfig doesn't work because the session was already established at startup. You have to do:
Session = drmaa.Session() try: Session.initialize() except drmaa.errors.AlreadyActiveSessionException: print "Using previously-initialized " + Session.contact + " DRMAA session"
comment:10 Changed 5 years ago by rutsky
- Cc rutsky.vladimir@… added
comment:11 Changed 5 years ago by mvpel
After some Python learning-curve issues, and a bit of tweaking and poking, it looks like we've got a fully-functional DRMAA latent build slave submitting to HTCondor. I'll give it overnight to make sure that the wheels don't fall off, but it appears to be in good shape. I'll provide the revised files and some instructions.
There's probably a better way to handle the job resource requirements than the hardcoding I'nm doing, it'd be nice to be able to pass memory and disk space requirements in from the master.cfg.
Changed 5 years ago by mvpel
DRMAA Abstract Latent Build Slave
Changed 5 years ago by mvpel
DRMAA HTCondor Abstract Latent Build Slave
Changed 5 years ago by mvpel
Startup script for HTCondor latent build slave
Changed 5 years ago by mvpel
Sample master.cfg to create HTCondor latent slave instances
Changed 5 years ago by mvpel
Sample master.cfg to create HTCondor latent slave instances
comment:12 Changed 5 years ago by mvpel
This is what's working on our HTCondor pool. The sgebuildslave.py may also need some adjustment as well.
One caveat is that the twistd.log files for the buildslave are deleted when the slave terminates, along with the rest of the Condor scratch directory. There may be a way to transfer them back to the master by using Condor's output-transfer mechanisms, with transfer_output_remaps to differentiate the log files from the various slaves. However since the slave is killed in the above, rather than exiting on its own, that'll pose a problem - Condor won't transfer files back to the owner if a job is killed.
It appears that the build_wait_timeout=0 is not actually causing the slave to shut itself down when the build finishes as some of the docs imply, but rather causing the insubstantiate to be invoked by the master to force the slave to shut down. If the slave could be directed to simply exit after the build finishes... am I missing a step somewhere?
The run_buildslave script can translate the TERM signal to a HUP signal to initiate a graceful shutdown of the slave, but I don't think that'll be sufficient to get the automatic file transfer to occur. So probably the slave-start script would need to do it in the TERM trap.
comment:13 Changed 5 years ago by dustin
I don't think users will be terribly worried about twistd.log files. There's seldom much of interest in there.
Jc2k, can you take a look at these additions? mvpel, do you think you could turn this into a pull req so that we can include tests, docs, etc.?
comment:14 Changed 5 years ago by dustin
- Cc Jc2k added
comment:15 Changed 5 years ago by dustin
- Resolution wontfix deleted
- Status changed from closed to reopened
comment:16 Changed 5 years ago by mvpel
Thanks for the pointer - I've forked the Github repo, so I'll plan to convert things into a branch when I have some time this week. I found a typo or two in any case, and perhaps I'll use the exercise of converting run_buildslave into Python as an educational experience. Reaching for /bin/sh is a 30-year-old habit for me, and from what I've learned over the last couple of months Python seems pretty spiffy.
With some further research, I found the "kill_sig=SIGHUP" Condor directive, which results in a HUP signal being sent to the run_buildslave script instead of a TERM, so that should mean that the "trap" wouldn't be required since a HUP would propagate to the buildslave child, which would close out due to the --allow-shutdown=signal.
However, having the trap would allow the startup script to try to append the twistd.log file somewhere before exiting, or whatever else - but like you said perhaps that's not worth the effort.
And after reading up on Python function arguments, I'm going to turn the nativeSpecification pieces into default-value keyword arguments, so the creator of the HTCondor latent slave in master.cfg can adjust them as appropriate, and perhaps a way to sanity-check and accept arbitrary submit description directives - perhaps something as simple as a string list called "extra_submit_descriptions".
comment:17 Changed 5 years ago by mvpel
First cut:
I fleshed out some documentation in the sample file as well, to help clarify what's going on and why.
Still have the gross hardcoded submit description directives, I'll deal with that later. I'll pull it, transfer it to my pool, and test it later this week or early next week, and do another commit to this branch as things progress.
comment:18 Changed 5 years ago by mvpel
It occurs to me - would the master get offended if the slave signals a graceful shutdown after the master had already called stop_instance()?
comment:19 Changed 5 years ago by Jc2k
I'm not sure what would happen in that case - I think i've always disable graceful shutdown of slaves by the master.
One nice thing you can add to this branch is something like this:
from buildbot import config try: from drmaa import drmaa except ImportError: drmaa = None
And then in your ___init___:
if not drmaa: config.error("The python module 'drmaa' is needed to use a %s" % self.__class__.__name__)
Then when the user uses buildbot checkconfig they will get a helpful error message, rather than a python stack trace.
comment:20 Changed 5 years ago by mvpel
Great, thanks for that! I realized it's probably is not necessary in htcondor.py to gripe about a missing buildbot.buildslave.drmaa, since it's an Buildbot internal component. Yes?
Here's the commit:
comment:21 Changed 5 years ago by mvpel
I just had an idle buildslave fail to shut down after a HUP, in spite of cheerfully logging that it would inform the master, so maybe we do need to stick with a TERM, or try a HUP first and then a TERM.
comment:22 Changed 5 years ago by mvpel
I've committed some updates I worked on last night in the wake of some testing with our Buildbot, as well as adding keyword arguments to allow the user to define certain aspects of the resource requests and set the accounting group and user. I also added the "extra_submit_description" for arbitrary directives, and improved the docstrings quite a bit.
With the ability to specify different resource requests for different latent buildslaves, you can set up big ones for larger builders by calling for more memory, disk space, and even CPUs, while having the smaller builders use a different set of latent buildslaves which request fewer resources from the scheduler.
comment:23 Changed 5 years ago by mvpel
I found what may be an issue in Enrico's code or possibly the HTCondor code, in that when jobs are sent to a remote scheduler's queue as a result of having the "SCHEDD_HOST" config value set to the remote machine's hostname, the job ID provided by DRMAA uses the local hostname instead of the remote:
DRMAA-provided job ID: buildbot_host.23456.0
Actual Job ID? sched_host.23456.0
The master gets an invalid job ID exception when it tries to DRMAA-terminate the former. I can tell at least that the HUP signal is working well because the slave goes promptly and gracefully away when I condor_rm the job, and the master doesn't seem to mind seeing a shutdown message after termination and releaseLocks in the slightest.
After reverting to a queue located on the buildmaster's host, the DRMAA job ID is working properly to terminate the slaves. I've got a support case open with HTCondor about it to see whether it's in their DRMAA or DRMAA-Python.
comment:24 Changed 5 years ago by mvpel
Ok, it appears that when the master goes to terminate the latent slave, it does not want to hear anything further from that slave whatsoever, otherwise it thinks that the slave is withdrawing from participation in builds - does that sound correct? If the master says "slave wants to shut down," then it's not going to try to use that slave again? So maybe I do need to just kill -9 when the DRMAA terminate occurs?
comment:25 Changed 5 years ago by mvpel
Good news Monday morning - everything appears to be working smoothly with the code I have in place right now, so now it's just a matter of adding the additional features to allow user control over the scheduler parameters and we'll have a solid piece of code for latent slaves on HTCondor and eventually Grid Engine.
I rewrote the run-buildslave script in Python over the weekend, so I'll see how that goes when I bring it over. If anyone wants to give me some Python-newbie pointers as to style and syntax, I'd appreciate it:
comment:26 Changed 4 years ago by dustin
- Milestone changed from 0.8.+ to 0.9.+
Ticket retargeted after milestone closed
comment:27 Changed 3 years ago by Edemaster
Registering my interest on this feature. I'm starting to look at the code and get it running in my environment. So far, I've rebased the code onto nine here:
comment:28 Changed 3 years ago by Edemaster
- Cc grand.edgemaster@… added
sgebuildslave.py | http://trac.buildbot.net/ticket/624 | CC-MAIN-2018-26 | refinedweb | 2,357 | 65.25 |
CodeGuru Forums
>
Visual C++ & C++ Programming
>
C++ (Non Visual C++ Issues)
> checking if allocation through new fails or not?
PDA
Click to See Complete Forum and Search -->
:
checking if allocation through new fails or not?
miteshpandey
April 14th, 2006, 12:45 PM
I want to start a discussion on why is it generally considered to be useless to check if the allocation done through new failed or not.
If it's already discussed please point me in the right direction
I used "generally" becuase one probable reason would be if new fails then we can ask for fewer number of bytes.
Any answers are appreciated much
ahoodin
April 14th, 2006, 12:49 PM
No it is most definitely not useless Mitesh....
What about the case where we are running out of memory? Or any of the memory exceptions that can occur?
Mitsukai
April 14th, 2006, 01:02 PM
its not useless, but also it could be a pain in the ***.
humptydumpty
April 14th, 2006, 01:04 PM
use set_new_handler it Installs a user function that is to be called when operator new fails in its attempt to allocate memory.
#include<new>
#include<iostream>
using namespace std;
void __cdecl newhandler( )
{
cout << "The new_handler is called:" << endl;
throw bad_alloc( );
return;
}
int main( )
{
set_new_handler (newhandler);
try
{
while ( 1 )
{
new int[5000000];
cout << "Allocating 5000000 ints." << endl;
}
}
catch ( exception e )
{
cout << e.what( ) << " xxx" << endl;
}
}
For more detail have a look in MSDN
if still Problem let us know.
Thankyou
SuperKoko
April 14th, 2006, 01:48 PM
I want to start a discussion on why is it generally considered to be useless to check if the allocation done through new failed or not.
It is not useless.
IMHO, catching a potential bad_alloc exception is a requirement in a correct program.
But perhaps, you misunderstood what said some C++ programmers.
It is useless to check that the returned pointer is not NULL, because it can't be NULL.
new throws calls a handler, which, by default, throws a bad_alloc exception!
I am aware that a few old C++ compilers are not compliant on that point, and returns NULL in case of allocation failure. :(
Graham
April 14th, 2006, 03:38 PM
new (std::nothrow)
is a standard-compliant way of getting the same behaviour.
stober
April 14th, 2006, 04:32 PM
use set_new_handler it Installs a user function that is to be called when operator new fails in its attempt to allocate memory.
Your program didn't work on my computer. I'm running XP with 1 Gig RAM. I first compiled it with VC++ 6.0 and got (almost) immediate assertion failure and abnormal program termination. Then I compiled it the VC++ 2005 Pro, that program just kept attempting to allocate more and more memory -- eventually my computer slowed down to a crawl and I finally killed that program. It never did call that newhandler() function.
[edit]I debugged VC++ 6.0 and found out that it doesn't implement set_new_handler()., Here is the assertion in M$'s function :eek:
// cannot use stub to register a new handler
assert(new_p == 0);
[edit again]VC++ 6.0 uses _set_new_handler() instead of set_new_handler(). made that change and the program worked the same as it did with 2005 compiler.
MrViggy
April 14th, 2006, 04:42).
Of course, if you have an app that is using this much memory, it might be time to think about using your own memory management, and develop some kind of cache system.
My $0.02...
Viggy
SuperKoko
April 14th, 2006, 05:06).
I have experienced applications that supported very well out-of-memory conditions.
Simply, the current operation fail, but it is still possible to use the software, save, modify what I want, etc...
I have also seen applications crashing stupidly...
MrViggy
April 14th, 2006, 05:10 PM
It really depends on the application. Our applications just exit. The issue is that if we can't get the memory we need, then the design we are working on writing is hosed already. So, we delete the design, and inform the user to call the s/w hotline for some possible solutions.
Viggy
miteshpandey
April 14th, 2006, 09:04 PM
Here is a link to an article by Herb_Sutter on this matter.
Link ()
Perhaps I misunderstood what he says. Maybe he meant is that there is no use in checking if new allocation succeeded or not in systems which commit memory long after the request for memory.
Maybe this doesn't happen in Windows system and we should check for new allocations.
What are your thoughts after reading the article?
Bornish
April 15th, 2006, 01:03 AM
If talking about non-POD objects, I believe best error handling is offered by a dummy interface instance (probably static) providing a default behaviour of the class. Overriding the creation of instances from a class, the reason for failure can be stored on per thread basis and retrieved by the client (caller of the allocation) through the dummy interface. In some cases, it is also useful to provide a mechanism for testing if the instance is a dummy or a real object. My personal favorite safety method is providing objects with a signature that gets overwritten on destruction, thus being able to test a pointer for validity when received through posted messages or shared by multiple threads.
exterminator
April 15th, 2006, 06:47 AM
Dissection - It is not necessary to check for successful memory allocations if you are using the non-nothrow version of new. It would throw std::bad_alloc exception. Work with exceptions instead of NULL checks all over the place unless that is the requirement (as for Graham working with the nothrow version).
There is a nothrow version of new ... and it returns NULL if the memory allocation fails. And a program should have checks for that. Atleast notifying the user about it, logging the failure.
There should be some precise reason about the failure so that the worries following it are directed rightly. If there are no checks, no logging and the program fails you are just left with no clues as to what should be done! What part of the program caused the abrupt failure? What should we tell the client? How must we target the situation? Start debugging from Line 1 on the client's machine? Totally inacceptible!
Lazy initialized or COW implementations (some implementations of std::string) are different. Let them be.. but you can not always program your applications based on assumptions about certain implementations. That is not the best practice. Moreover, if the handlers fail to give you proper diagnostic signals - that's the particular implementations problem - and not yours!.
Trying/Ability to recover is important. You should not always catch exceptions that you cannot do nothing about because in the end you are left with no other option than re-throwing the exception with a little log created which could also have had been done in the code that actually is capable of handling/recovering from the exception. If you consider from that point of view - handling new related exceptions is meaningless - because you really can't do anything about it... but this is an exceptional case - you program is going to end - and no other part of the code will be able to handle it. So, a little logging can always prove helpful in predicting the error to determine if this failure was because of new failure or some other exception that was left unhandled by a bad programmer! Be it done - using new handlers or exception catching mechanism.
Conclusion - use new handlers (set_new_handler) as well as catch std:bad_alloc exceptions. Herb Sutter's article in not suggesting against their usage but targets lazy initialization and how it makes our life tough (showing success when actually later the program fails) and standard conformance issues. He shows the practical significance of this exception - it is very rare true but it can happen! If they really felt they are un-necessary then may be the standards specifications could be made a few pages shorter. ;)
Suggestion - read the article again. :) - kidding, but its no harm you know! Use new handlers as well as exception handling depending upon the program's specifications as to what must be done in such cases.
SuperKoko
April 15th, 2006, 07:57 AM).
It does little... but I claim that it is recovers properly from the exception.
Similarly, a MDI application (Word processor... or web brower), can have many open windows, and if a new one is created and there is not enough memory, instead of crashing, it is MUCH better to simply don't create the new window. Because as a user, I can't accept to see all of my browsing windows suddenly close with a message "Not enough memory... bye bye!".
And guys who think that there is enough memory are wrong. I experience often out-of-memory.
And there are many programs that crash... and others that recover properly. I always prefer to use programs that recover properly.
Furthermore, there are cases where we can really recover and make the operation success.
A simple example:
std::vector::push_back may use an exponential growth strategy (allocating 1.3 or 1.5 times the memory needed).
And, you know that, for a std::vector reallocation, you need twice the memory of the vector. That is much.
So, a std::bad_alloc is not so exceptionnal. In that case, one can recover by allocating exactly the needed memory (and not 1.5 times the needed memory).
Back to the web browser example : Many (all?) web browser keep in cache a lot of data. In fact, web browser would use a very very little amount of memory if they had no cache.
So, if there is an out-of-memory condition, it is very easy to free much memory.
But, for example, I admit that a C++ compiler can't do much when it has not enough memory, except exit cleanly.
miteshpandey
April 15th, 2006, 09:09 AM
From the above discussion, I have come to understand that:
Failure of allocation through new should be checked (whether bad_alloc is thrown or the nothrow version which returns null)
1. If the program can't do without that specific memory that could not be allocated through new, the program should log this and exit. The logging is for diagnostic purpose.
2. If the programmer has alternative strategies(like requesting for fewer bytes or etc.) then the program can take this alternative path instead of exiting the application.
Am I far from correct?
Mitsukai
April 15th, 2006, 09:27 AM
i would rather check if it returned 0 or not, throw has to much power of the application for me.
exterminator
April 15th, 2006, 09:35 AM)...... (and more......)Correct... I totally agree. In fact, I considered this case in my post as well when I said the following in the suggestions part:Use new handlers as well as exception handling depending upon the program's specifications as to what must be done in such cases.Am I far from correct?No. You are not incorrect. You are on right track! In fact, now just leave new failure away and think about any kind of exception. That is what you actually do for any other exception. Then why should new be given special treatment? Yeah, I agree they are all specific exceptional cases but still you have to handle them as far as you can and take remedial action specific to that exception, if you can. Otherwise - why would there be a need to write anything else except catch(...)?
Again, I put stress on this that the ability to recover is important if you are planning to put a catch block! How you are planning to recover depends on the programmer and the specifications that have been laid down in the design phase! Good examples are provided in SuperKoko's post above.
Regards.
exterminator
April 15th, 2006, 09:44 AM
i would rather check if it returned 0 or not, throw has to much power of the application for me.Mitsukai, this does not make sense? What are you trying to say? Please be explicit while explaining things. The way you have written your post - its too confusing and in fact does not make sense.
If you are suggesting not use exception handling and using the historical ways of catching errors then I guess you must go ahead with reading the following FAQs for a start.
Exception handling FAQs ()
It has been unanimously decided on Codeguru that people use exception handling and hence you should too... if you don't agree do a search for exception handling on this forum and come back with the arguments. We would like to settle this forever! ;) :D
codeguru.com | http://forums.codeguru.com/archive/index.php/t-383728.html | crawl-003 | refinedweb | 2,136 | 64.71 |
Hello All,
So I have a program I am working on that utilizes a dynamic array and then takes a series of lowercase letters and changes them to uppercase. I have this program so far but when I entered in the toupper to switch from lowercase to uppercase I keep getting errors. I do not know what I am doing wrong so any pointers would be appreciated. I am pretty positive that my code is pretty much done but I am just making a mistake somewhere. Thanks in advance for any help.
Code:#include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { char* letter; int numberOfLetter; cout << "Please enter the number of letters " << "you would like to capitalize:" << endl; cin >> numberOfLetter; letter = new char[numberOfLetter]; for (int i = 0; i < numberOfLetter; i++){ cout << "Please enter a letter " << i + 1 << endl; cin >> letter[i]; } cout << "The letters you entered were:" << endl; char *letter2 = new; for (int i = 0; i < numberOfLetter; i++){ cout << letter2[i] << endl; letter[i] = letter2[i]; if(isalpha(letter2[i])) { letter2[i] = toupper(letter2[i]); } } system("PAUSE"); return EXIT_SUCCESS; } | http://cboard.cprogramming.com/cplusplus-programming/126323-dynamic-array.html | CC-MAIN-2015-32 | refinedweb | 185 | 51.01 |
Guide to 24 PHP Frameworks (Part 2)
In Part 2 of this series, we look at several great PHP frameworks and a few PHP compatible CRMs to help you choose the framework for your next project.
Join the DZone community and get the full member experience.Join For Free
follow the series
this blog post is the second part of " the definitive guide to your next php framework. "
didn't read it yet? you can check it out here .
the following parts will be published during the next couple of weeks or you can click the link below to download the full version of the kindle book " the definitive guide to your next php framework ."
introduction
if you have read the first part of this article, you should be confident when your colleagues ask you what a framework is and why php has so many of them.
if you are new to this topic and you want to scale up your web development skills, or you are a veteran and you would like to explore more choice out there, below you will find several others framework reviews that will let you decide which one to use next.
enjoy!
table of contents
codeigniter
i need to be honest here, this was the first framework i used, read the first 4-5 pages of its documentation.
suddenly everything became clear and, in a couple of hours, i was able to recreate functionalities and properly divide up code using the framework, and it helped me a lot when i learned more advanced frameworks.
codeigniter is quite old, it released initially in 2006, but, after being taken into the stewardship of the folks at the british columbia institute of technology, it still gets updated often.
in fact, at the time of my writing, the latest version (3.1.8) was released at the end of march 2018.
the most important characteristics of codeigniter are the lightness and the speed at which it procesess data.
it's the framework i'll be discussing in this post that looks the least like a framework.
compared to the other php frameworks, codeigniter has a clear and easy to understand file structure, very detailed documentation, and lots of users and companies that still use it and can help provide support.
it is definitely the way to go if you feel ready and you have enough experience with vanilla php.
with this framework you are ready to take the step further.
resources:.
unlike other popular cmss based on php, drupal requires more time to be fully understood.
it has backend, even the front-end could be improved and, just like modules, there are several themes that can be enabled.
it's also reliabile. having been founded almost 20 years ago, there has been a lot of time to improve and create a robust and secure product.
it is also perfect for a wide range of different projects, from websites to blogs and forums to e-commerce and social networks.
they can be scaled out just by adding the necessary modules.
there is also a continually growing community that creates and deploys tons of resources on a daily basis.
in conclusion, it is a very good cms and if you have time to to learn it, it will be time well invested.
resources:
fat-free php framework
fat-free is a micro-framework created by bong costa, a filipino web developer and consultant.
as you can probably glean from the name, the key. for the developer, this means no wasting time learning how things work and so you can put all your time into coding.
fat-free requires php 5.3 or higher and supports a limitation.
results:
fuelphp
one of the most interesting (in my opinion) php frameworks available is fuel.
it was created by several web developers with lots of years working and building php frameworks — dan horrigan and philip sturgeon (famous for their contributions to codeigniter), among them.
fuel seemed to be a good mixture between codeigniter 3.x and kohana 2.x taking the best parts and improving on each of them.
the result was a very fast structure to work with.
it was designed to have full support of the hierarchical model view controller principle, which means that the selected code can be used in several pages across the entire project — just think of a shopping cart or blog posts.
let's forget the presence of the presentation model, also called viewmodels. it basically adds another level between the views and the controllers.
the idea of the file structure for fuelphp was copied from kohana and improved upon, a wise use of namespaces and autoload which allows the calling of class to happen clearly faster than the parents.
it also came with two packages pre-installed, activerecord and oil, the latter of which is a very useful command line utility.
fuelphp has been developed by people that surely know what they are doing and it took one of the best features of kohana (its file structure) and mixed it with codeigniter, which, as seen above, has been a masterpiece for a decade.
but now, with the release of php 7, it's starting to show its age.
the downside of it may be that the community has never grown that much, thus it is very difficult to find the support and answers to questionsphp to the world.
i highlighted what i thought.
phil never rests, and he gave me a list of several projects he is currently working on. he is now mainly working at wework, a new york based company.
among his projects the newest versions of php and, among its pros, there is the size, which is less than 200 kbs and thus, its speed.
unlike the other frameworks we have just seen, gyroscope uses anlchh architecture and not the more popular mcv.
in this architecture, a div tag with a unique id is populated using previously chosen data.
this data invokes the client that sends an ajax request to the server side. then the php does its stuff like create, delete, etc., and updates the view.
this makes the path equal to an http request which is good for performance and debugging.
some problems there are more advanced frameworks out there.
resources:
jamroom
released in july 2003, jamroom is another cms.
now in its sixth version, it was developed by talldude networks and is licensed with a mozilla public license.
jamroom is a very different product from the others you are seeing here.
it is composed by a module architecture that permits the structure to increase or decrease its functionality.
the other part of jamroom is its skin, which allows you to change the features and look of the website.
everything inside it is either a module or a skin.
a relevant event is the fact that it ran on flash until version number 5, which carried some issues regarding mobile responsiveness.
nowadays, the problem has been successfully solved and all the multimedia data uploaded is then converted and available in several formats.
resources:
kajona
here is another content management framework.
this is an lgpl licensed project, which means that the external developers can enhance the code by adding and improving implementation and features.
kajona was created in 2004. the second version was deployed in 2005 immediately followed by the version 2.1 in 2006. at the moment, this cms is a sound framework arrived at its sixth version.
the system is separated it two main sectors: the backend, which is the part used to maintain the website, and the portal, which is used to show the content.
this portal has built-in in-page editing functionality.when hovering on an editable element it is possible to update its contents and the result will be seen on the fly.
from a web developer’s point of view, the architecture looks like a normal mvc with the three distinct layers..
resources:
kohana
i have already mentioned this framework when i was describing fuelphp above.
kohana was, yes i wrote was, a very good and a very unlucky framework.
its development started at the end of may 2007, from the plan of some codeigniter members and its first name was blueflame.
the first official version was released a couple of months later, without any documentation.
after some scrambling by the internal team, the second version was released in november of the same year. at that time it was written in php 5.0.
the third and last version of this php framework was released officially on september 9, 2009, and the last update, 3.3.6, was released july 25, 2016.
kohana was formally deprecated on july 1, and up-to-date thanks to post security fixes and compatible with the latest versions of php.
he also advised using a more modern product; like me, he is a fan of laravel, which you will read more about it in the next section .
resources:
laravel
here is the showpiece of the list.
from my point of view, laravel is without any doubt the most interesting framework for php.
its growth and the list of features are simply unbelievable.
created by taylor otwell as an experiment of improving codeigniter, laravel's a blade templating system that permits the developers to better integrate php with the view.
laravel 3 was released in february 2012 and, in a certain wa,y it could be considered a small breakthrough.
tthe main features are: artisan, a brand new cli (command line interface), plus database migration, events handling and bundles, and a packaging system.
in may 2013, mr. otwell released illuminate, the nickname chosen for laravel 4.
after so many successful years, it was completely rewritten and distributed as a package via composer.
with the fourth version of laravel, developers could really certify that the project was now growing at the point to be world class.
among its new features, i'd like to highlight database seeding, which allows for the populating of databases, support for different kinds of emails, soft deletion, and message queueing. not to mention the publication of a release scheduled for the minor version.
basically, from this version on, there will be a new minor version every six months or so.
laravel 5 made its appearance in march 2015. this version includes flysystem for remote storage, elixir to handle package assets, socialite for authentication, and scheduler for... guess what? scheduling tasks!
at this point, laravel was already the most popular php framework.
the first version with long-term support (lts) was laravel 5.1. the plan, then brought in again with version 5.5, was to support security and bug fixes respectively for two or three years.
at the point of writing this article, laravel is on version 5.6 , which was officially been released on february 7, 2018.
besides the unbelievable high quality and hard work from the creator and the contributors, i think that laravel changed how web developers write and think about their job.
for example, using a feature like eloquent orm (active record) presenting database tables as classes makes the developing process, thus the life of developers, so much easier.
attending laracon in either the us or europe is something that most developer have dreamed of at least once.
laravel news will keep you and your colleagues informed about what is happening around this framework, and last, but not the least, laracasts with thousands and thousands of minutes of free videos edited by jeffrey way, an incredible developer former top-mind at envato tuts+.
as you can se,e choosing laravel means choosing the entire ecosystem.
join a huge community of developers tha,t even if you do not realize it, will make your job better in the years to come.
resources:
to be continued...
now it's your turn
i hope you enjoyed my framework comparison.
the next part will be published soon.
but now, i want to hear from you:
which php framework has intrigued you the most? are you going to try one of these listed above?
Published at DZone with permission of Nico Anastasio. See the original article here.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/guide-to-24-php-frameworks-part-2?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev | CC-MAIN-2021-43 | refinedweb | 2,038 | 71.34 |
Manning's Countdown to 2014
. Use discount code crdotd14 all month for 50% off every deal.
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
Register / Login
JavaRanch
»
Java Forums
»
Certification
»
Web Services Certification (SCDJWS/OCEJWSD)
Author
SCDJWS Beta : Some findings/points
Sim Kim
Ranch Hand
Joined: Aug 06, 2004
Posts: 268
posted
Nov 13, 2008 23:47:00
0
1. Handler Framework : Handlers work in the order in which they are declared in the xml file or in the order in which they are added in the
HandlerResolver
. But the
order is for Outgoing messages
and for Incoming the order is reversed .
2.On the Client side Handlers can be added
using the HandlerReolver
also.This cannot be done on the server side.
... service.setHandlerResolver(new MyHandlerResolver()); ... public class MyHandlerResolver implements HandlerResolver { public java.util.List<Handler> getHandlerChain(PortInfo portInfo) { List<Handler> handlerChain = new ArrayList<Handler>(); QName serviceQName = portInfo.getServiceName(); if(serviceQName.getNamespaceURI().equals( "") && serviceQName.getLocalPart().startsWith( "HelloService")) { handlers.common.LogicalLoggingHandler lh = new handlers.common.LogicalLoggingHandler(); handlerChain.add(lh); handlers.common.SOAPLoggingHandler sh = new handlers.common.SOAPLoggingHandler(); handlerChain.add(sh); } }
There is one more way to add Handlers on the Client side , by setting a chain
directly on a
BindingProvider
List<Handler> handlerChain = ((BindingProvider)port).getBinding().getHandlerChain(); client.handlers.SOAP11Handler sh = new client.handlers.SOAP11Handler(); List<Handler> new_handlerChain = new ArrayList<Handler>(); new_handlerChain.add(sh); ((BindingProvider)port).getBinding().setHandlerChain(new_handlerChain);
3. LogicalHandlers are called first.
Faraz Ali
Ranch Hand
Joined: May 15, 2008
Posts: 108
posted
Nov 14, 2008 01:06:00
0
The @javax.jws.WebMethod(exclude=true) cannot be used on a service endpoint interface.
Chintan Rajyaguru
Ranch Hand
Joined: Aug 19, 2001
Posts: 341
posted
Nov 15, 2008 17:07:00
0
Sim Kim,
Are you trying to ask a question or just listing some findings about the handlers? If you were just noting handler creation strategies, there are more ways than you listed:
1. You can create handler chain using wsdl customizations. Put the customizations in a separate customization file or insert customizations directly into the wsdl (I don't recommend messing with wsdl this way).
Choose this option to configure handler chain in a top down service design.
2. You can also create a handler chain by specifying @HandlerChain (file="handler_filename.xml) annotation on web service implementation or on SEI. The file should specify the chain using the same syntax as that used in the wsdl customization.
Choose this option to configure handler chain in a bottom up service design.
3. You can define a handler chain in sun-jaxws.xml deployment descriptor. Again, the syntax to specify the chain is same as the two options above. This choice is implementation specific and will have to be reconfigured when migrating to a different implementation (e.g. from Glassfish to WebSphere or vice versa).
Choose this option to configure handler chain at the deployment time.
4. You can define a handler chain by adding it directly in the binding provider (the option you covered). This option can be used to add handler chain on the client side.
This is a great way to set the chain dynamically. For example, on the client side, you can first determine which service to invoke and then set the chain for that service.
5. You can use
HandlerResolver
to set handler chain (another option you cover). This option
automatically adds the handler chain
on ALL newly created binding objects. From design perspective,
choose this option when the chain for a given service is predetermined and you don't want every piece of client code to have the code for adding handler chains (just like you don't want to create Connection in every DAO). Also, if your team consists of junior developers and you don't want them to temper with handler configuration etc., you can provide some kind of factory which returns the service object with the chain preset on it using this method.
An interesting food for thought is to ask: What happens if the chain is being executed and a handler returns false or throws an exception? What will happen to the chain execution? Will the message become response if it was request? What if the message was already response? Section 9.3.2 of jax-ws specification has the answers.
ChintanRajyaguru.com
SOADevelopment.com
Sim Kim
Ranch Hand
Joined: Aug 06, 2004
Posts: 268
posted
Nov 15, 2008 23:24:00
0
Thanks Chintan !
I was mentioning what all I knew about handlers.But you have given some wonderful tips.
I think the
HandlerResolver
can be used at the client side only . Please correct me if I am wrong .
I read the JAX-WS Specs but could not understand some concepts regarding mapping of Exception to Fault . Will read it again and see how do I do it.
With a little knowledge, a
cast iron skillet
is non-stick and lasts a lifetime.
subject: SCDJWS Beta : Some findings/points
Similar Threads
Deploy JAXWS (Mustang) WS to Tomcat?
Message Handlers and Axis
JAX-RPC Registering a Client-Side Handler Problem
web service security
Convert SOAP response to SOAP XmL string using JAX WS
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/419112/java-Web-Services-SCDJWS/certification/SCDJWS-Beta-findings-points | CC-MAIN-2013-48 | refinedweb | 878 | 57.57 |
Ticket #4505 (closed defect: fixed)
clock_gettime() returning incorrect result
Description
I am running Ubuntu 9.04 under VirtualBox 3.0.0.
I have found a problem that is seen with clock_gettime() On some occasions, the result of clock_gettime() will go backwards. It can be shown the this code:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main (int argc,char *argv[]) { struct timespec t; struct timespec ot; int i = 0; for(i = 0;i < 100000;i++) { clock_gettime(CLOCK_MONOTONIC,&ot); clock_gettime(CLOCK_MONOTONIC,&t); printf("%d time 1 secs = %lld\n",i,(long long int)ot.tv_sec); printf("%d time 2 secs = %lld\n",i,(long long int)t.tv_sec); printf("%d time 1 nsecs = %lld\n",i,(long long int)ot.tv_nsec); printf("%d time 2 nsecs = %lld\n",i,(long long int)t.tv_nsec); if(ot.tv_sec > t.tv_sec) { printf("**** Old sec > new sec ****\n"); exit(-1); } if(ot.tv_nsec > t.tv_nsec) { printf("**** Old nsec > new ssec ****\n"); exit(-1); } } } return 0;
I have tried this on other VM clients with the same version of Ubuntu, and it works fine. There is no cleverness to detect a wrap around from 999999999 nsecs to 0 nsecs, but the failure will occur before this happens.
Attachments
Change History
comment:2 Changed 6 years ago by sandervl73
- Summary changed from clock_gettime() returning incorrect result. to clock_gettime() returning incorrect result. -> retry with 3.0.2
comment:4 Changed 6 years ago by frank
- Version changed from VirtualBox 3.0.0 to VirtualBox 3.0.2
- Summary changed from clock_gettime() returning incorrect result. -> retry with 3.0.2 to clock_gettime() returning incorrect result
comment:5 Changed 6 years ago by frank
- Status changed from new to closed
- Resolution set to fixed
Should be finally fixed with VBox 3.0.6.
comment:6 Changed 5 years ago by oneeyed
comment:7 Changed 5 years ago by mr_mop
Yes, I suspect that it is the same issue. The test program I attached above seems to be masking the problem and so appears fixed. If the printf()s used to display the current times is removed, and the for loop converted to an infinite loop, the problem is seen. With the printf()s and the loop limit, the problem is not seen.
I'd say this is not fixed, but as your bug is newer, and about the same issue, I'll leave this one as closed. The issue can then be tracked in your new bug.
Vbox.log from boot until after running the test application. | https://www.virtualbox.org/ticket/4505 | CC-MAIN-2015-18 | refinedweb | 421 | 75.5 |
This site uses strictly necessary cookies. More Information
Follwing module is attached in GUITexture, however there is no reaction in OnMouseDown(). Please help me. I couldn't find any proper answer in this page.
using UnityEngine;
using System.Collections;
public class SceneMove : MonoBehaviour
{
public string SceneName;
public void OnMouseDown(){
print ("LoadLevel");
Application.LoadLevel( SceneName );
}
void update()
{
}
}
I tested your code and it works.
So please specify what is the exact output that you expect.
Have you added any colliders? In know that On$$anonymous$$ouseDown will work if your GameObject got some kind of collider
@Super$$anonymous$$asterBlasterLaser: that's not correct; GUIText and GUITexture objects do not require colliders.
Thank you for your answer,as above answer, GUITexture is not needed collider. I have wresled with this error for hours. But not found the solution.
Well, it works fine here. Try making a new empty project, create a GUITexture, and attach the script. You'll see it works as expected.
Answer by Calum-McManus
·
Apr 28, 2014 at 01:22 PM
there are no errors in your code, the only thing that it could be is that you are not clicking on a Collider. if you want this to work when ever you click, just put a box taking up the whole screen then turn of its renderer and attach this script to it.
GUITexture objects don't use colliders.
Indeed, it should work on a GUI layer object or a collider, my advice would be to use a collider ins$$anonymous$$d if you really can't get a GUI-texture to work, although it should and has worked when I tested it. You could always try doing the OnGUI function and make a texture layer using that and see if.
Change button texture when its clicked
1
Answer
Changing texture on mouse click
1
Answer
Assigning UV Map to model at runtime
0
Answers
Trying to pick up and see paper - pop up GUI window to examine objects when clicked
3
Answers
DXF imported, Textures don't work
1
Answer
EnterpriseSocial Q&A | https://answers.unity.com/questions/696416/onmousedown-is-not-working-in-the-guitexture.html | CC-MAIN-2021-39 | refinedweb | 346 | 64.81 |
log4j - Sample Program
We have seen how to create a configuration file. This chapter describe how to generate debug messages and log them in a simple text file.
Following is a simple configuration file created for our example. Let us revise it once again: means the printed logging message will be followed by a newline character.
The contents of log4j.properties file are as follows −
#
Using log4j in Java Program
The following Java class is a very simple example that initializes, and then uses, the log4j logging library for Java applications.
import org.apache.log4j.Logger; import java.io.*; import java.sql.SQLException; import java.util.*; public class log4jExample{ /* Get actual class name to be printed on */ static Logger log = Logger.getLogger(log4jExample.class.getName()); public static void main(String[] args)throws IOException,SQLException{ log.debug("Hello this is a debug message"); log.info("Hello this is an info message"); } }
Compile and Execute
Here are the steps to compile and run the above-mentioned program. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.
All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. | http://www.tutorialspoint.com/cgi-bin/printversion.cgi?tutorial=log4j&file=log4j_sample_program.htm | CC-MAIN-2015-22 | refinedweb | 199 | 50.94 |
Lesson 17 - Interfaces in Java
In the previous lesson, Diary with a database in Java (finishing), we practiced working with List collections and created an electronic diary in Java. is the way we communicate with certain types of objects. We have already dealt with public methods in previous lessons, e.g. the ones we set up for our arena warrior. The Warrior class we made had the following public methods:
- void attack(Warrior enemy)
- void defend(int hit)
- boolean alive()
- void setMessage(String message)
- String getLastMessage()
- String healthBar()
If we store a Warrior class instance into a variable, we void chirp() { System.out.println("♫ ♫ ♫"); } public void breathe() { System.out.println("Breathing..."); } public void peck() { System.out.println("Peck, peck!"); } }
Done! Now, let's move to InterfaceSample.java and create a bird instance:
Bird bird = new Bird();
Once you've created an instance of the bird class, write whatever you called the instance, in my case, it is "bird", and add a dot right after it. NetBeans will then display all of its class methods (you can also invoke this menu. Right-click on the project, and choose New -> Java Interface.
An empty interface will be added to our project. We'll add the headers of methods which this interface will require. The implementation itself, method content, is added later by the class that implements the interface.
Let's add method headers to the BirdInterface, we'll purposely omit one of them and only add chirping and breathing:
public interface BirdInterface { void chirp(); void breathe(); }
We don't specify the public modifier since an interface contains public methods only. It wouldn't make sense otherwise since it specifies how to work with an object from the outside.
Let's go back to InterfaceSample.java and change the line with the bird variable so it won't be longer of the Bird type, but of the BirdInterface type:
BirdInterface bird = new Bird();
What the code above means is that in the bird variable, we expect an object
that contains the methods specified in the BirdInterface interface. NetBeans
reports an error since the Bird class doesn't implement BirdInterface yet.
Although it does have the needed methodsit must first be informed that it
implements this interface. Let's move to the
Bird class and let it
implement the
BirdInterface interface. We do it using the
implements keyword:
public class Bird implements BirdInterface { . . .
When we go back to InterfaceSample.java, the line with the variable of the BirdInterface type no longer causes an error. The Bird class correctly implements the BirdInterface interface. Meaning that Bird instances can now be stored in variables of this type.
Now just for completeness' sake, let's see what happens when we remove a method from the class, which is required by the interface, like the chirp() method. NetBeans will warn us that the implementation is not complete. Once you have visual confirmation of the interface's dependency on the class, put the method back where it belongs.
Let's write bird with a dot after it. Again, NetBeans will offer the following methods:
We can see that now we can call only the methods provided by the interface on the instance. That's because the bird is now a variable of the BirdInterface BirdInterface bird = new BirdInterface();
Multiple inheritance
Java, like most programming languages, doesn't support multiple inheritance. Meaning that we can't inherit one class from more than one other class. Mainly, because method naming collisions could very well occur when multiple classes of what object type it actually is, or what it provides beyond the interfaces.
Now let's add a LizardInterface to our project. Lizards will be able to breathe and crawl:
public interface LizardInterface { void crawl(); void breathe(); }
Next, we'll try "multiple inheritance", more accurately, implement multiple interfaces by a single class. We'll add a Pterodactyl.java class to the project. It will implement BirdInterface and LizardInterface interfaces:
class Pterodactyl implements LizardInterface, BirdInterface { }
If we click on the "light-bulb" icon, we can choose to Implement all abstract methods. NetBeans will then automatically generate the necessary class methods.
After having both interfaces implemented, the code will look like this:
class Pterodactyl implements LizardInterface, BirdInterface { @Override public void crawl() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void breathe() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void chirp() { throw new UnsupportedOperationException("Not supported yet."); } }
Notice that NetBeans has added the @Override annotation to methods implementing the interfaces. It's more clear this way so we'll add the same annotation to the chirp() and breathe() methods in the Bird class as well.
Now all we have to do is specify what we want each method to do:
@Override public void crawl() { System.out.println("I'm crawling..."); } @Override public void breathe() { System.out.println("I'm breathing..."); } @Override public void chirp() { System.out.println("♫ ♫♫ ♫ ♫ ♫♫"); }
That's pretty much it! Now, let's add an instance of the Pterodactyl class in InterfaceSample.java:
Pterodactyl Java, you will learn more advanced techniques of the object-oriented programming.
No one has commented yet - be the first! | https://www.ictdemy.com/java/oop/interfaces-in-java | CC-MAIN-2021-31 | refinedweb | 852 | 55.95 |
This is a presentation of notes on the first four units of Django for Everybody:
The goal is not to reproduce the most excellent materials Dr. Chuck has already provided us, but rather to supplement them with a few comments, adaptations, and demonstrations.
The first big takeaway is that web applications use a client-server architecture with the following characteristics:
Software Stack
The following are the specific technologies we focus on at NOVA Web Development:
Your goal for the internship should be to learn as much of this development stack as you can, and to identify which parts of it are the most appealing to you.
Our plan is to launch our business by offering custom web application development using Django and the other tools in our stack.
We will begin marketing our skills using the three applications in our portfolio that demonstrate what we can do:
A high end goal of the Summer internship would be to add another application to this list. In order for that to happen, you would not only learn the basics of the development tools, but the best practices including agile software development, which we aspire to learn and adopt.
We will use the
GET HTTP/1.0 request with
telnet to retrieve a web
page from a
virtual machine
running Nginx on my laptop.
By the way, the linux kernel comes with virtualization built-in. I use Virt-Manager all the time to manage KVM VMs.
We'll pause here for the demo...
import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('rms.local', 80)) cmd = 'GET HTTP/1.0\r\n\r\n'.encode() mysock.send(cmd) while True: data = mysock.recv(512) if len(data) < 1: break print(data.decode(), end=' ') mysock.close()
from socket import * def create_server(): serversock = socket(AF_INET, SOCK_STREAM) try: serversock.bind(('0.0.0.0', 9000)) serversock.listen(5) while True: (clientsock, address) = serversock.accept() recved = clientsock.recv(5000).decode() pieces = recved.split('\n') if (len(pieces) > 0): print(pieces[0]) data = 'HTTP/1.1 200 OK\r\n' data += 'Context-Type: text/html; charset=utf-8\r\n\r\n' data += '<!DOCTYPE html>\n<html lang="en">\n<head>' data += '<meta charset="utf-8">\n<title>Simplest Web Server' data += '</title>\n</head>\n<body>\n<h1>Hello, from the Simplest' data += ' Web Server!</h1>\n</body></html>\r\n\r\n' clientsock.sendall(data.encode()) clientsock.shutdown(SHUT_WR) except KeyboardInterrupt: print('\nShutting down...\n'); except Exception as exc: print('Error:\n', exc) serversock.close() print('Access') create_server()
Let's end with a demo of the
simplest_browser.py accessing the
simplest_server.py. I'll be running the server on a virtual
machine named
rms, running inside my host machine (the laptop from
which you are viewing this).
The VM can be accessed using the naming provided by
Avahi,
which enables services and hosts on a local network to discover each other, so
I can access
rms with the name,
rms.local, without
having to figure out what its
IP address is.
After this last demo we will discuss our study plan for next week. | https://www.elkner.net/static/DJ4Enotes/index.html | CC-MAIN-2022-33 | refinedweb | 520 | 58.08 |
Opened 2 years ago
Closed 2 years ago
Last modified 2 years ago
#10171 closed defect (fixed)
CC parsing should use NotifyEmail.addrsep_re.split(ticket['cc'])
Description (last modified by rjollos)
CC parsing should use NotifyEmail.addrsep_re.split(ticket['cc']) as this is what it is used by Trac:
from trac.notification import NotifyEmail ... if not username or username == 'anonymous': return False return (self.allow_owner and (ticket['owner'] == username)) or \ (self.allow_reporter and (ticket['reporter'] == username)) or \ (self.allow_cc and username in NotifyEmail.addrsep_re.split(ticket['cc']))
Attachments (0)
Change History (3)
comment:1 Changed 2 years ago by dkgdkg
- Resolution set to fixed
- Status changed from new to closed
comment:2 Changed 2 years ago by rjollos
Has this been tested? It seems that from trac.notification import NotifyEmail is missing.
There's also the Chrome.cc_list function, which is more directly intended for what you are trying to accomplish, I think.
from trac.web.chrome import Chrome ... ... username in Chrome(self.env).cc_list(ticket['cc'])
comment:3 Changed 2 years ago by rjollos
Note: See TracTickets for help on using tickets.
(In [11906]) use NotifyEmail.addrsep_re to parse cc field (Closes #10171) | http://trac-hacks.org/ticket/10171 | CC-MAIN-2014-23 | refinedweb | 194 | 53.88 |
JSON::Parse - Read JSON into a Perl variable
use JSON::Parse 'parse_json'; my $json = '["golden", "fleece"]'; my $perl = parse_json ($json); # Same effect as $perl = ['golden', 'fleece'];
Convert JSON into Perl.
JSON::Parse offers the function "parse_json", which takes one argument, a string containing JSON, and returns a Perl reference or scalar. The input to
parse_json must be a complete JSON structure.
JSON::Parse also offers two high-speed validation functions, "valid_json", which returns true or false, and "assert_valid_json", which produces a descriptive fatal error if the JSON is invalid. These are much faster than "parse_json". See "PERFORMANCE" for a comparison.
JSON::Parse also offers one convenience function to read JSON directly from a file, "json_file_to_perl", and a safer version of "parse_json" called "parse_json_safe" which doesn't throw exceptions.
For special cases, such as JSON objects with non-unique names (key collisions), or round-trips with JSON booleans, there are also "new" and "run", which create a JSON parsing object and run it on text.
JSON::Parse accepts only UTF-8 as input. If its input is marked as Unicode characters, the strings in its output are also marked as Unicode characters. If its input contains Unicode escapes of the form
"\u3000", its output is upgraded to Unicode character strings.
(JSON means "JavaScript Object Notation" and it is specified in "RFC 7159".)
use JSON::Parse 'parse_json'; my $perl = parse_json ('{"x":1, "y":2}');
This function converts JSON into a Perl structure, either an array reference, a hash reference, or a scalar.
If the first argument does not contain a complete valid JSON text,
parse_json throws a fatal error ("dies"). If the first argument is the undefined value, an empty string, or a string containing only whitespace,
parse_json returns the undefined value."; # Prints "HASH".
If the input JSON text is a serialized array, an array reference is returned:
use JSON::Parse ':all'; my $perl = parse_json ('["a", "b", "c"]'); print ref $perl, "\n"; # Prints "ARRAY".
Otherwise a Perl scalar is returned.
The behaviour of allowing a scalar was added in version 0.32 of this module. This brings it into line with the new specification for JSON.
The function "parse_json_safe" offers a version of this function with various safety features enabled..
use JSON::Parse 'valid_json'; if (valid_json ($json)) { # do something }
valid_json returns 1 if its argument is valid JSON and 0 if not. It also returns 0 if the input is undefined or the empty string.
This is a high-speed validator which runs between roughly two and eight times faster than "parse_json". This speed gain is obtained by discarding inputs after reading them rather than storing them into Perl variables.
valid_json.
use JSON::Parse 'assert_valid_json'; eval { assert_valid_json ('["xyz":"b"]'); }; if ($@) { print "Your JSON was invalid: $@\n"; } # Prints "Unexpected character ':' parsing array"
This is the underlying function for "valid_json". It runs at the same high speed,.
This is almost the same thing as "parse_json", but has the following differences:
If the JSON is invalid, a warning is printed and the undefined value is returned, as if calling "parse_json" like
eval { parse_json ($json); }; if ($@) { warn $@; }
This switches on "detect_collisions", so that if the JSON contains non-unique names, a warning is printed and the undefined value is returned.
This switches on "copy_literals" so that JSON true, false and null values are copied. These values can be modified, but they will not be converted back into
true and
false by JSON::Create.
As the name implies, this is meant to be a "safety-first" version of "parse_json".
This function was added in version 0.38.
The following alternative function names are accepted. These are the names used for the functions in old versions of this module. These names are not deprecated and will never be removed from the module.
This is exactly the same function as "parse_json".
This is exactly the same function as "assert_valid_json".
JSON elements are mapped to Perl as follows: become Perl strings. The JSON escape characters such as
\t for the tab character (see section 2.5 of "RFC 7159") are mapped to the equivalent ASCII character."
Since every byte of input is validated as UTF-8 (see "UTF-8 only"), this hopefully will not upgrade invalid strings.', };
In the event of a key collision within the JSON object, something like
my $j = '{"a":1, "a":2}'; my $p = parse_json ($j); print $j->{a}, "\n"; # Prints 2.
.
Note that the JSON specification says "The names within an object SHOULD be unique." (see "RFC 7159", page 5), although it's not a requirement.
For performance, "valid_json" and "assert_valid_json" do not store hash keys, thus they cannot detect this variety of problem.
.
The Perl versions of literals produced by "parse_json" will be converted back to JSON literals if you use JSON::Create's
create_json.; sub l { print "\n@_:\n\n"; } sub i { print " @_\n"; } my $cream = '{"clapton":true,"hendrix":false,"bruce":true,"fripp":false}'; my $jp = JSON::Parse->new (); my $jc = JSON::Create->new (); l "First do a round-trip of our modules"; i $jc->run ($jp->run ($cream)); l "Now do a round-trip of JSON::Tiny"; i encode_json (decode_json ($cream)); l "First, incompatible mode"; i 'tiny(parse):', encode_json ($jp->run ($cream)); i 'create(tiny):', $jc->run (decode_json ($cream)); l "Compatibility with JSON::Parse"; $jp->set_true (JSON::Tiny::true); $jp->set_false (JSON::Tiny::false); i 'tiny(parse):', encode_json ($jp->run ($cream)); l "Compatibility with JSON::Create"; $jc->bool ('JSON::Tiny::_Bool'); i 'create(tiny):', $jc->run (decode_json ($cream)); l "JSON::Parse and JSON::Create are still compatible too"; i $jc->run ($jp->run ($cream)); exit;
The output looks like this:
First do a round-trip of our modules:
{"bruce":true,"clapton":true,"fripp":false,"hendrix":false}
Now do a round-trip of JSON::Tiny:
{"fripp":false,"bruce":true,"clapton":true,"hendrix":false}
First, incompatible mode:
tiny(parse): {"hendrix":"","fripp":"","bruce":1,"clapton":1} create(tiny): {"bruce":1,"clapton":1,"fripp":0,"hendrix":0}
Compatibility with JSON::Parse:
tiny(parse): {"fripp":false,"clapton":true,"bruce":true,"hendrix":false}
Compatibility with JSON::Create:
create(tiny): {"bruce":true,"clapton":true,"fripp":false,"hendrix":false}
JSON::Parse and JSON::Create are still compatible too:
{"hendrix":false,"bruce":true,"clapton":true,"fripp":false}
Most of the other CPAN modules use similar methods to JSON::Tiny, so the above example can easily be adapted. See also the documentation of JSON::Create under "Interoperability" for various examples.
".
my $jp = JSON::Parse->new ();
Create a new JSON::Parse object.
This method was added in version 0.38.
my $out = $jp->run ($json);
Exactly the same thing as "parse_json", except its behaviour can be modified using the following methods.
This method was added in version 0.38.
JSON error at line 1, byte 28/55: Name is not unique: "cat" parsing object starting from byte 12 at examples/collide.pl line 8.
The
detect_collisions (1) behaviour is the behaviour of "parse_json_safe". The
detect_collisions (0) behaviour is the behaviour of "parse_json".
This method was added in version 0.38..
$jp->delete_true ();
Delete the user-defined true value. See "set_true".
This method is "safe" in that it has absolutely no effect if no user-defined value is in place. It does not return a value.
This method was added in version 0.38.
.
$jp->delete_false ();
Delete the user-defined false value. See "set_false".
This method is "safe" in that it has absolutely no effect if no user-defined value is in place. It does not return a value.
This method was added in version 0.38.
.
$jp->delete_null ();
Delete the user-defined null value. See "set_null".
This method is "safe" in that it has absolutely no effect if no user-defined value is in place. It does not return a value.
This method was added in version 0.38.
.
This module imposes the following restrictions on its input. to be thrown.
"valid_json" does not produce error messages. "parse_json" and "assert_valid_json" die on encountering invalid input.
Error messages have the line number, and the byte number where appropriate, of the input which caused the problem. The line number is formed simply by counting the number of "\n" (linefeed, ASCII 0x0A) characters in the whitespace part of the JSON.
Parsing errors are fatal, so to continue after an error occurs, put the parsing into an
eval block:
my $p; eval { $p = parse_json ($j); }; if ($@) { # handle error }
The following error messages are produced:
An unexpected character (byte) was encountered in the input. For example, when looking at the beginning of a string supposedly containing JSON, there are six possible characters, the four JSON whitespace characters plus "[" and "{".
This error occurs for "assert_valid_json" when it's given an empty or undefined value. Given empty input, "parse_json" returns an undefined value rather than throwing an error. 101.
where the JSON object has two keys with the same name,
hocus. The terminology "name is not unique" is from the JSON specification.
Experimentally, there is a global variable
$JSON::Parse::json_diagnostics, which, if true, causes errors to be output as JSON rather than text:
$JSON::Parse::json_diagnostics = 1; assert_valid_json ("{'not':'valid'}");
This outputs the following:
{"input length":15,"bad type":"object","error":"Unexpected character","bad byte position":2,"bad byte contents":39,"start of broken component":1,"valid bytes":[0,0,0,0,0,0,0,0,0,1,1,0,0,1]}
That means that, in a string of length 15 bytes, the JSON component which looked like an object starting from byte 1 is broken at byte 2, because it has a bad character there of ascii 39 (a single quote mark), where the bytes allowed were as described in the array of valid bytes.
valid_bytes is a 256-item array whose values are "true" for allowed bytes and "false" otherwise.
This is intended for people who want to make, say, a "broken JSON repair" module, so that they can analyze errors without having to parse the above kinds of diagnostic string. The contents of the JSON diagnostics are not currently documented and are subject to change, so please view the source code (file json-common.c) or see what the errors look like by adding incorrect JSON and viewing the results.
This happens if you set JSON false to map to a true value:
$jp->set_false (1);
To switch off this warning, use "no_warn_literals".
This warning was added in version 0.38.
This happens if you set JSON true to map to a false value:
$jp->set_true (undef);
To switch off this warning, use "no_warn_literals".
This warning was added in version 0.38.
This warning is given if you set up literals with "copy_literals" then you also set up your own true, false, or null values with "set_true", "set_false", or "set_null".
This warning was added in version 0.38. pub-bench.pl runs the benchmarks and prints them out as POD.
The following benchmark tests used version 0.38 of JSON::Parse and version 3.01 of JSON::XS on Perl Version 18.2, compiled with Clang version 3.4.1 on FreeBSD 10.1. The files in the "benchmarks" directory of JSON::Parse. "short.json" and "long.json" are the benchmarks used by JSON::XS.
Repetitions: 10 x 100 = 1000 --------------+------------+------------+ module | 1/min | min | --------------|------------|------------| JP::valid | 838860.800 | 0.0000119 | JSON::Parse | 277768.477 | 0.0000360 | JSON::XS | 257319.264 | 0.0000389 | --------------+------------+------------+
Repetitions: 10 x 100 = 1000 --------------+------------+------------+ module | 1/min | min | --------------|------------|------------| JP::valid | 14009.031 | 0.0007138 | JSON::Parse | 5047.905 | 0.0019810 | JSON::XS | 5602.116 | 0.0017850 | --------------+------------+------------+
Repetitions: 10 x 100 = 1000 --------------+------------+------------+ module | 1/min | min | --------------|------------|------------| JP::valid | 287281.096 | 0.0000348 | JSON::Parse | 32488.799 | 0.0003078 | JSON::XS | 31441.559 | 0.0003181 | --------------+------------+------------+
Repetitions: 10 x 100 = 1000 --------------+------------+------------+ module | 1/min | min | --------------|------------|------------| JP::valid | 133576.561 | 0.0000749 | JSON::Parse | 52363.346 | 0.0001910 | JSON::XS | 19803.135 | 0.0005050 | --------------+------------+------------+
Repetitions: 10 x 100 = 1000 --------------+------------+------------+ module | 1/min | min | --------------|------------|------------| JP::valid | 303935.072 | 0.0000329 | JSON::Parse | 47662.545 | 0.0002098 | JSON::XS | 28493.913 | 0.0003510 | --------------+------------+------------+
Repetitions: 10 x 100 = 1000 --------------+------------+------------+ module | 1/min | min | --------------|------------|------------| JP::valid | 1401.371 | 0.0071359 | JSON::Parse | 209.319 | 0.0477741 | JSON::XS | 207.542 | 0.0481830 | --------------+------------+------------+
JSON is specified in RFC 7159 "The application/json Media Type for JavaScript Object Notation (JSON)". is the website for JSON, authored by Douglas Crockford.
JSON::Create is a companion module to JSON::Parse by the same author. As of version 0.08, I'm using it everywhere, but it should still be considered to be in a testing stage. Please feel free to try it out.
This is actually a combination module for JSON::PP and JSON::XS.
Part of the Perl core. JSON in Perl-only without the XS (C-based) parsing. This is slower but may be necessary if you cannot install modules requiring a C compiler.
All-purpose JSON module in XS (requires a C compiler to install).
Fork of JSON::XS related to a disagreement about how to report bugs. Please see the module for details.
"Does what I want" module.
Wraps a C library called yajl.
Relies on JSON::MaybeXS.
Takes advantage of a similarity between YAML (yet another markup language) and JSON to provide a JSON parser/producer using YAML::Syck.
The module is undocumented so I am not sure what it does.
Uses the JSON library from Glib, a library of C functions for the Linux GNOME desktop project.
Part of the Mojolicious standalone web framework, "pure Perl" JSON reader/writer. As of version 6.25 of Mojolicious, this actually depends on JSON::PP.
A fork of
Mojo::JSON.
JSON::MultiValueOrdered is a special-purpose module for parsing JSON objects which have key collisions (something like
{"a":1,"a":2}) within objects.
(JSON::Parse's handling of key collisions is discussed in "Key collisions" in this document.)
This offers a way to compare two different JSON strings to see if they refer to the same object.
This module offers
true and
false literals similar to JSON.
This untangles the messy Perl representation of numbers, strings, and booleans into JSON types.
These modules present a more consistent and improved interface which can rely on more than one of the above back-end modules at once. This protects the user from incompatible changes in module APIs, and by relying on more than one back-end the users are also protected from the personality clashes between various temperamental module maintainers. Many CPAN modules involving JSON now rely on a "master module" rather than using the above JSON modules directly.
A "combination module", the currently fashionable choice, which combines Cpanel::JSON::XS, JSON::XS, and the original JSON.
A now-deprecated "combination module" which combines JSON::DWIW, JSON::XS versions one and two, and JSON::Syck.
A "combination module" which supports two different interfaces of JSON::XS. However, JSON::XS is now onto version 3.
Pulls in JSON::MaybeXS instead of Mojo::JSON.
These modules extend JSON with comments and other things.
"An extension of JSON that allows for better human-readability".
"Relaxed JSON with a little bit of YAML"
"A relaxed and easy diffable JSON variant"
There are also a lot of modules in the CPAN
JSON:: namespace which use JSON as a basis for other things, but with apologies I don't try to cover those modules here, since there are so many of them.' at /home/ben/software/install/bin/validjson line 21.
If you need confirmation, use its --verbose option:
validjson -v *.json atoms.json is valid JSON. ids.json is valid JSON. kanjidic.json is valid JSON. linedecomps.json is valid JSON. radkfile-radicals.json is valid JSON.
The script uses Path::Tiny for reading files, which is not a dependency of this module, so if you want to use the script, you also need to install Path::Tiny.
The CPAN testers results are at the usual place.
The ActiveState test results are at..
Or "why did you make yet another JSON module?"
This module started out under the name JSON::Argo. It was originally a way to escape from having to use the other JSON modules on CPAN.
The reason it only parsed JSON was that when I started this I didn't know the Perl extension language XS.
Shlomi Fish (SHLOMIF) fixed some memory leaks in version 0.40.
Ben Bullock, <bkb@cpan.org>) 2013-2016 Ben Bullock.
You can use, copy, modify and redistribute this package and associated files under the Perl Artistic Licence or the GNU General Public Licence.
This defines the terminology used in this document.. | http://search.cpan.org/~bkb/JSON-Parse/lib/JSON/Parse.pod | CC-MAIN-2016-30 | refinedweb | 2,743 | 66.13 |
1 Jul 01:59 2005
Re: cfi_flash is now working with 64 bit port width
Wolfgang Denk <wd <at> denx.de>
2005-06-30 23:59:42 GMT
2005-06-30 23:59:42 GMT
In message <42C469BD.4010109 <at> orkun.us> you wrote: > > I think in this case instead of bloating the cfi_flash.c we could allow > user to define preprocessor macros in this board file for flash access > so if those macros are defined, cfi_flash.c would use them and exclude > its own built-in ones. Oh no, please don't do this! > That way, any board with custom data bus (reversed lanes for example) or > address bus (messed up address line) arrangements or specialized > handling (need floating point) as in this case would override them > easily and we would not end up blocks of #if/#elif/#else/#endif etc. in No. The whole idea of the CFI flash driver is to have standard code for all boards. If your design does not fit the standard, then provide your own non-standard driver. Don't add complexity to the CFI driver - it has just a single advantage (being "standard"), so please don't drop this. > the cfi_flash.c. The board would also enable FP unit in its board file > or within these functions if necessary as well. "enabling FP" has nothing to do with this. The FPU is never disabled or so. It's just that the compiler is told to never emit any FP instructions(Continue reading)
> I can submit a patch to do this while I am working on my other long > pending patch this weekend. I promise I will get it done this time.> I can submit a patch to do this while I am working on my other long > pending patch this weekend. I promise I will get it done this time. | http://blog.gmane.org/gmane.comp.boot-loaders.u-boot/month=20050701 | CC-MAIN-2016-26 | refinedweb | 308 | 80.92 |
If you have installed Python via anaconda () then numba is already available to you. Otherwise numba may be installed using pip (pip install numba).
Functions written in pure Python or NumPy may be speeded up by using the numba library and using the decorator @jit before a function. This is especially useful for loops where Python will normally compile to machine code (the language the CPU understands) for each iteration of the loop. Using numba the loop is compiled into machine code just once the first time it is called.
Let’s look at an example:
from numba import jit import numpy as np import timeit # Define a function normally without using numba def test_without_numba(): for i in np.arange(1000): x = i ** 0.5 x *= 0.5 # Define a function using numba jit. Using the argument nopython=True gives the # fastest possible run time, but will error if numba cannot precomplile all the # code. Using just @jit will allow the code to mix pre-compiled and normal code # but will not be as fast as possible @jit(nopython=True) def test_with_numba(): for i in np.arange(1000): x = i ** 0.5 x *= 0.5 # Run functions first time without timing (compilation included in first run) test_without_numba() test_with_numba() # Time functions with timeit (100 repeats). # Multiply by 1000 to give milliseconds timed = timeit.timeit(stmt = test_without_numba, number=100) * 1000 print ('Milliseconds without numba: %.3f' %timed) timed = timeit.timeit(stmt = test_with_numba, number=100) * 1000 print ('Milliseconds with numba: %.3f' %timed) OUTPUT: Milliseconds without numba: 183.771 Milliseconds with numba: 0.025
We have a 7,000 fold increase in speed!!
Note: not all code will be speeded up by numba. Pandas for example are not helped by numba, and using numba will actually slow panda code down a little (because it looks for what can be pre-complied which takes time). So always test numba to see which functions it can speed up (and consider breaking larger functions down into smaller ones so that blocks that can use numba may be separated out).
If the default decorator @jit is used, with no other arguments, numba will allow a mix of code that can be pre-compiled with code that can’t. For the fastest execution use @jit(nopython=True), but you may need to break your function down because this mode will error if parts of the function cannot be pre-compiled by numba.
One thought on “91. Speed up Python by 1,000 times or more using numba!” | https://pythonhealthcare.org/2018/09/22/90-speed-up-python-by-1000-times-or-more-using-numba/ | CC-MAIN-2020-29 | refinedweb | 417 | 65.83 |
Introduction
;
Introduction
Applet is java program that can be embedded into HTML pages. Java applets... and run in its sandbox.
Here is the java code of program...; message.
Here is the code for the Java Program :
Introduction to java arrays
Introduction to java arrays
... as separate objects.
Code: Java
int[][] a2 = new int[10...
of Arrays in Java Programming language. You will learn how the Array class
Introduction
Java as an Object Oriented Language
Introduction: In this section, we...
the java applications and programs.
OOP
means Object
Oriented Programming
Introduction to the JDBC
- Java Driver
Type 2 drivers are developed using native code... through C/C++.
Here a thin code of Java wrap around the native code...
Introduction to the JDBC
Introduction
JSF Introduction - An Introduction to JSF Technology
JSF Introduction - An Introduction to
JSF Technology...;
Java Server Faces or JSF for short is another new exciting technology
for developing web applications based on Java technologies. This JSF
Introduction To Application
Introduction To Application
The present application is an online test... test paper of that particular
language. For example- if he selects java the he can only see the java language
test paper. After submitting the test paper he
Introduction to JSP
to directly insert java code into jsp file, this makes the development process very...;
Java Server Pages or JSP for short is Sun's solution... driven web application.
Java is known Java
Introduction to Java
What is Java?
Java is a high-level object-oriented programming... Wide Web but it is
older than the origin of Web.
New to Java
javascript introduction for programmers
javascript introduction for programmers A brief Introduction of JavaScript(web scripting language) for Java Programmers
March 2008 Issue of Java Jazz up magazine
March 2008 Issue of Java Jazz up magazine
Ajax-an
Introduction...-Technical
Introduction
We have already discussed that Ajax uses JavaScriptDOM Introduction
JDOM Introduction
... for manipulating XML documents from within the Java programs. The JDOM api
is faster then DOM api and it is used by the Java programmers to process XML
files
Introduction to Java
Introduction to Java
This section introduces you the Java programming
language. These days Java... from Java source code.
Applet
Viewer
Applet viewer
Introduction to HTML
Introduction to HTML
... the source code of the web page, you will see the general structure of the HTML...;This is another paragraph. This will give you<br>an introduction of HTML
Java Introduction
.
The program written in Java is first compiled in byte code by Java compiler... that converts java source code into byte
code, which is then read by JVM... it into a code that is
read by the concerned operating system.
Java interpreter
Introduction to JSP
page is a web page that contains Java code embeded within the HTML tags. ...; and ends >. These tags allows to embed a huge amount of java code in the JSP...
Introduction to JSP
Introduction to Struts 2
, JSP API 2.0 and Java 5.
Video Tutorial - Introduction to Struts 2...Introduction to Struts 2
This section provides you a quick introduction to
Struts 2 framework
Introduction to POJO (Plain Old Java Object) Programming Model
Introduction to POJO (Plain Old Java Object) Programming Model... in a few seconds.
Flexible: A Java POJO code can be implemented with any type... features of added by Sun Microsystems in EJB
3.0 is POJO (Plain Old Java
Introduction to Java
environment to code in. Hence they developed Java.
The company was later overtaken... converted into machine readable code instead
Java compiler compiles the program into byte codes that can be converted into
machine code by JVM (Java Virtual
Introduction To Enterprise Java Bean(EJB). WebLogic 6.0 Tutorial.
Introduction To Enterprise Java Bean(EJB)
Enterprise Java
Bean architecture is the component... Applications with Enterprise
Java Beans)
(Online WebLogic 6.0
Introduction To Enterprise Java Bean(EJB). Developing web component.
Introduction To Java Beans...;
To download the code
for this lesson click here. To deploy this
web component download the code and then extract it in you
code
code
how to write this in java
Tomcat an Introduction
web server that implements the Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystem to provide the platform to run Java code on a web...
Tomcat an Introduction
Methods - Introduction
Java NotesMethods - Introduction
Method = Function = Procedure...
and is used in Java. Every programmer has this idea, but sometimes uses....
Why use methods?
For reusable code
If you need
Introduction to the QUnit Framework
Introduction to the QUnit Framework
Introduction to the QUnit Framework... to
test the code of projects and plugins. But it can test any general JavaScript
Loops - Introduction
Java NotesLoops - Introduction
In this section we will introduce you with the Loops in Java. Loops are very
useful in programming for executing a set of code multiple times if certain
conditions are true.
The purpose
Introduction to JSP...;
configuration and dependency management code
text utilities
custom layout
code
code hi
I need help in creating a java code that reminds user on a particular date about their festival.
i have no clue of how to do it..
am looking forward to seek help from you
Introduction to jQuery plugin
Introduction to jQuery plugin
Introduction to jQuery plugin
JQuery plugins... Code
Learn from experts! Attend
jQuery
Introduction to Interceptor
Introduction to Interceptor
Interceptors are one of the most powerful features of struts2.2.1. the
introduction of interceptors into struts2.2.1... invocations. They
provide the developer with the opportunity to define code
Introduction
Introduction
... languages like C, C++ and java are case
sensitive languages while...; The Java class Helloworld
is a completely different class from the class
code
code <
comp xlink:
how to write this in java
Quick introduction to web services
Quick introduction to web services
Introduction:
Web services... the functionality of your existing code over the network.
Once it is exposed
Introduction to XML
Introduction to XML
An xml file consists of various elements. This section presents you a brief
introduction to key terminologies used in relation to xml.
Here is a sample xml code:
.style1 {
background-color: #BFDFFF
Introduction to jQuery UI plug-in
Introduction to jQuery UI plug-in
Introduction to jQuery UI plug-in
JQuery... and
interaction library. This library is built using java script library. Using
Introduction to Java Servlets
Introduction to Java Servlets
Java Servlets are server side Java programs that require... include Java Server Pages (JSPs) and Enterprise Java Beans (EJBs
PHP Introduction
it is not compiled into binary file like Java. You can modify your code and copy... and takes less time to master.
PHP Introduction
The word PHP stands... file. So, you can make your html dynamic by using the PHP code in it. Generally
Java Training and Tutorials, Core Java Training
Java Training and Tutorials, Core Java Training
Introduction to online... with platform
independent feature. Java developers tried to write the code... and deletion of memory automatically, it
helps to make bug-free code in Java
AN INTRODUCTION TO JSTL
trace of Java code!
So, programmers who were writing their JSP using... a servlet
interposes HTML in
java code, JSP interposes java-code in HTML, as some authors correctly
observe..( in this case, we have
Introduction to JSP Declaratives Declarations
Introduction to JSP Scriptlets
JSF Introduction - An Introduction to JSF Technology
Introduction to java arrays
Introduction to java arrays
... are handled as separate objects.
Code: Java
int[][] a2 = new int... in Java Programming language. You will learn how the Array class in
java helps
Introduction to Java Arrays
Introduction to Java Arrays
... are handled as separate objects.
Code: Java
int[][] a2 = new int... in Java Programming language. You will learn how the Array class in
java helps
PHP Introduction
be developed by embedding PHP codes into HTML codes using the syntax of C, Java... Solaris.
Before scripting the code in PHP, there is a need to install the PHP
Using Beans in JSP. A brief introduction to JSP and Java Beans.
;
Java
Beans
Java
Beans are reusable components...
class = name of the java class that defines the bean.
Introduction to Hibernate 3.0
Hibernet.org.The
Hibernate 3.0 core is 68,549 lines of Java code together... Introduction to Hibernate 3.0
... in development for
well over a year. Hibernate maps the
Java classes
Introduction to the Java Persistence API
to introduce you about the Java Persistence API.
The Java Persistence API is Java standard for persisting the Java Objects
(Entity) to the relational database. It provides a way to bridge the gap between
Java model and relational
Introduction to Quartz Scheduler
Introduction to Quartz Scheduler
Introduction to Quartz Scheduler
This introductory section... in
java applications. Here, you will learn how Quartz Job Scheduler helps you
JAVA code For
JAVA code For JAVA code For "Traffic signals Identification for vehicles
Introduction to Hibernate 3.0
HTML5 <i> tag, Introduction of <i> tag in HTML5.
HTML5 <i> tag, Introduction of <i> tag in HTML5.
Introduction...;
<i >Text for italic.</i>
Example of <i> in HTML5:
Code... this code
Difference Between HTML5 and HTML4.01:
No difference. Because
INTRODUCTION TO JSP SCRIPTLETS
INTRODUCTION TO JSP SCRIPTLETS
...;%
//java codes
%>
JSP Scriptlets begins with <% and
ends %> .We can embed any amount of java
java code
java code what is the code to turn off my pc through java program
JAVA CODE
JAVA CODE JAVA SOURCE CODE TO BLOCK A PARTICULAR WEB SITES(SOCIAL WEB SITE
java code
java code write a java code to convert hindi to english using arrays
HTML5 input examples, Introduction and implementation of input tag.
HTML5 input examples, Introduction and implementation of input tag.
Introduction:In this tutorial, you will see the use of
input tag. The input tag...;<input
attributes />
Example of <input> in HTML5:
Code
java code
java code develop a banking system in java
Reflection API : A Brief Introduction
before Java 1.1. You can create
methods like event handlers, hash code etc and also...
Reflection API : A Brief Introduction
... was included in Java 1.1. The classes of
Reflection API are the part
java code
java code hi any one please tell me the java code to access any link
i mean which method of which class is used to open any link in java program
Introduction to java.sql package
Introduction to java.sql package
... database by using the java programming language. It includes a framework where we... when the code is running within a Security Manager, such as an applet. It attempts
java code
java code how to extract html tags using java
java code
java code need java code for chart or graph which compare the performance of aprior algorithm and coherent rule algorithm.plz any one help me out
java code
java code write a java code for finding a string in partiular position in a delimited text file and replace the word with the values given by user and write the file in new location
java code
java code sir how to merge the cells in excel using java code please help me and also how to make the text placed in the cell to be center
java code
java code I need the java code that would output the following:
HARDWARE ITEMS
CODE DESCRIPTION UNIT PRICE
K16 Wood screws,brass,20mm $7.75
D24 Wood glue,clear,1 liter $5.50
M93
Java code
Java code Create a washing machine class with methods as switchOn, acceptClothes, acceptDetergent, switchOff. acceptClothes accepts the noofClothes as argument & returns the noofClothes
java code
java code what is meaning bufferedreader
J2EE Tutorial - Introduction
elimination of java code anywhere in the JSP page!..something that ASP.NET
has...
J2EE Tutorial - Introduction
... is Java atall or something else. This
tutorial is a conceptual
java code
java code i want HSVcolor descriptor for color image in java coding
java code
java code I am beginer in java my question is how can i fill data from mysql database to jcombobox using netbeans
Java Code
Java Code Write a java program, which creates multiple threads. Each thread performs add/delete/update operations on an ArrayList simultaneously
INTRODUCTION TO JSP DECLARATIVES
; with .We can embed any amount of
java code in the JSP Declaratives. Variables... INTRODUCTION TO JSP DECLARATIVES
... are:
<%!
//java codes
%>
java code
java code An employee _id consist of 5 digits is stored in a string variable strEmpid. Now Mr.Deb wants to store this Id in Integer type to IntEmpid. write Java statements to do
java code
java code HOW TO PRINT 1 TO 100 WITHOUT USING CONDITIONAL,ANY LOOP AND ARRAY IN JAVA AND C.URGENT SIR PLZ Hi,
You can use following code:
class MyClass
{
public static void main(String[] args)
{
int
java code
java code Write a program to find the difference between sum of the squares and the square of the sums of n numbers
java code
java code Develop a program that accepts the area of a square and will calculate its perimeter
java code
java code Create a calculator class which will have methods add, multiply, divide & subtract
java code
java code input any word
ie risk,resul is--
r
ri
ris
risk
java code
java code Develop the program calculateCylinderVolume., which accepts radius of a cylinder's base disk and its height and computes the volume of the cylinder
java code
java code Develop the program calculateCylinderArea, which accepts radius of the cylinder's base disk and its height and computes surface area of the cylinder
java code
java code Create a washing machine class with methods as switchOn, acceptClothes, acceptDetergent, switchOff. acceptClothes accepts the noofClothes as argument & returns the noofClothes
Java code
Java code Write a program which performs to raise a number to a power and returns the value. Provide a behavior to the program so as to accept any... the following code:
import java.util.*;
import java.text.*;
class NumberProgram
java code
java code int g()
{
System.out.println("Inside method g");
int h()
{
System.out.println("Inside method h");
}
}
Find the error in the following... cannot define a method inside another method. Anyways, we have modified your Write a program which performs to raise a number to a power and returns the value. Provide a behavior to the program so as to accept any type of numeric values and returns the Develop the program calculatePipeArea. It computes the surface area of a pipe, which is an open cylinder. The program accpets three values: the pipes inner radius, its length, and the thickness of its wall
Java code
Java code Create a calculator class which will have methods add, multiply, divide & subtract
Hi Friend,
Try the following code:
class Calculation{
public int add(int a,int b){
return a+b
Java code
Java code An old-style movie theater has a simple profit program. Each customer pays $5 per ticket. Every performance costs the theater $20, plus...; Hi Friend,
Try the following code:
import java.util.*;
import
Introduction
Introduction
This Shopping Cart Application is written in Java and set up using Hibernate
and Struts. Hibernate and Struts are popular open source tools
java code
java code An old-style movie theater has a simple profit program. Each customer pays $5 per ticket. Every performance costs the theater $20, plus $.50 per attendee. Develop the program calculateTotalProfit that consumes | http://www.roseindia.net/tutorialhelp/comment/70118 | CC-MAIN-2014-10 | refinedweb | 2,548 | 56.96 |
Using QOpenGLWidget
Hello,
I'm trying to use OpenGL inside of Qt using QOpenGLWidget, but I am having a hard time finding any relevant examples. I am new to OpenGL, so I am trying to learn how to use it, but the tutorials that I find don't seem to apply particularly well in QOpenGLWidget. Right now, all I want to do is render a triangle to start with.
Here's what I have so far.
Header:
namespace Ui { class Widget; } class Widget : public QOpenGLWidget, protected QOpenGLFunctions { public: explicit Widget(QWidget *parent = 0); ~Widget(); protected: void initializeGL(); void resizeGL(int, int); void paintGL(); private: Ui::Widget *ui; };
Class:
Widget::Widget(QWidget *parent) : QOpenGLWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); } void Widget::initializeGL() { // Set up the rendering context, load shaders and other resources, etc.: initializeOpenGLFunctions(); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); } void Widget::resizeGL(int w, int h) { // Update projection matrix and other size-related settings: } void Widget::paintGL() { // Draw the scene: glClear(GL_COLOR_BUFFER_BIT); } Widget::~Widget() { delete ui; }
Is there any example I could use to just render a basic triangle? I tried the one from here:, but it threw a lot of errors that I couldn't work out.
I also don't know how OpenGL contexts work in QOpenGLWidget.
Follow thoose tutorials or at least the part 0, 1 ,2 ,3a, 3b and you will have decent basis to start.
In the tutorial he use QOpenGLWindow which isn't really far from QOpenGLWidget so I think you should be able to adapt his code a bit to suit your need but if you didn't succed to do it ask here again.
Do you look for opengl ressources to ? | https://forum.qt.io/topic/56539/using-qopenglwidget | CC-MAIN-2018-30 | refinedweb | 285 | 56.29 |
Has anyone got a script to turn a multi-file C source into a single file? Just asking, before I reinvent the wheel.
- Remove duplicate #defines
- Remove duplicate #includes
- Remove comments
Thanks.
Printable View
Has anyone got a script to turn a multi-file C source into a single file? Just asking, before I reinvent the wheel.
- Remove duplicate #defines
- Remove duplicate #includes
- Remove comments
Thanks.
Not sure what you mean by 'remove' duplicates?
gcc -E prog.c
This removes comments, expands includes and replaces #defines
gcc -MM prog.c
This outputs a list of header files which prog.c depends on.
Don't see why anyone would want to do such a thing.
I have a library, which of course, is split into multiple modules. For simplicity of use and distribution I want to make it available as a single source file.
For example, if we have:
Then I want this as the result (all in one file):Then I want this as the result (all in one file):Code:
- File 1:
#define UNICODE
#include <windows.h>
#include <stdio.h>
void function(void) {
/* Some comment */
some code;
}
- File 2:
#define UNICODE
#include <windows.h>
#include <something.h>
void function2(int i) {
while(i++) < 10000 printf("hello");
/* another comment */
}
Note: duplicate includes and defines gone, comments gone and all in one file.Note: duplicate includes and defines gone, comments gone and all in one file.Code:
#define UNICODE
#include <windows.h>
#include <stdio.h>
#include <something.h>
void function(void) {
some code;
}
void function2(int i) {
while(i++) < 10000 printf("hello");
}
Salem:
Thanks for the ideas but I don't wish to expand includes or resolve defines.
I have made some progress on a rough script.
No worries, I got a script working. It's not exactly elegant or robust but it seems to do what I need.
If anyone actually uses this:If anyone actually uses this:Code:
Option Explicit
Dim fso
Call WScript.Quit( main() )
' Returns the entire contents of a text file
'''
Function ReadFile(sFilePath)
Const ForReading = 1, AsciiFormat = 0
Dim TextStream
Set TextStream = fso.OpenTextFile(sFilePath, ForReading, False, AsciiFormat)
ReadFile = TextStream.ReadAll()
TextStream.Close
End Function
' Writes sContents to the specified file.
'''
Sub WriteFile(sFilePath, sContents)
Const ForWriting = 2, AsciiFormat = 0
Dim TextStream
Set TextStream = fso.OpenTextFile(sFilePath, ForWriting, True, AsciiFormat)
TextStream.Write sContents
TextStream.Close
End Sub
' Relocates all #includes and #defines to the beginning
' of the source and removes duplicates.
'''
Function PreProcess(sOldSource)
Dim sNewSource, sTokens, sLine
Dim i, rgsLines, rgsArray
Dim dctTokens
Set dctTokens = CreateObject("Scripting.Dictionary")
rgsLines = Split(sOldSource, vbcrlf, -1, 0)
For i = LBound(rgsLines) To UBound(rgsLines)
sLine = Replace(rgsLines(i), " ", "")
sLine = Replace(rgsLines(i), vbTab, "")
If ( Left(sLine, Len("#include")) = "#include" Or _
Left(sLine, Len("#define")) = "#define" ) Then
if (Not dctTokens.Exists(rgsLines(i))) Then dctTokens.Add rgsLines(i), 0
Else
sNewSource = sNewSource & rgsLines(i) & vbcrlf
End If
rgsArray = dctTokens.Keys
For i = LBound(rgsArray) To UBound(rgsArray)
sTokens = sTokens & rgsArray(i) & vbcrlf
PreProcess = sTokens & sNewSource
End Function
' Removes comments from the source
'''
Function RemoveComments(sOldSource)
Dim sNewSource, regEx
Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True
' Deal with /* */ comments that have a line to themselves.
regEx.Pattern = "\r\n[\t ]*/\*(.|[\r\n])*?\*/[\t ]*\r\n"
sNewSource = regEx.Replace(sOldSource, vbcrlf)
' Deal with /* */ comments that share the line.
regEx.Pattern = "/\*(.|[\r\n])*?\*/"
sNewSource = regEx.Replace(sNewSource, "")
' Deal with // comments that have a line to themselves.
regEx.Pattern = "\r\n[\t ]*//[^\r]*\r\n"
sNewSource = regEx.Replace(sNewSource, vbcrlf)
' Deal with // comments that share a line
regEx.Pattern = "//[^\r]*"
sNewSource = regEx.Replace(sNewSource, "")
' Remove double white lines
regEx.Pattern = "\r\n[\t \r\n]*\r\n"
sNewSource = regEx.Replace(sNewSource, vbcrlf & vbcrlf)
' Remove line ending white space
regEx.Pattern = "[\t ]*\r\n"
sNewSource = regEx.Replace(sNewSource, vbcrlf)
RemoveComments = sNewSource
End Function
Function main()
Const EXIT_SUCCESS = 0, EXIT_FAILURE = 1
Dim sArg, sSource, sOldSource, sNewSource
Set fso = CreateObject("Scripting.FileSystemObject")
For Each sArg In WScript.Arguments
sOldSource = sOldSource & vbCrLf & "@@@<<@@ ----- " & _
fso.GetFileName(sArg) & " ----- @@>>@@@" & _
vbCrLf & ReadFile(sArg)
sNewSource = PreProcess(sOldSource)
sNewSource = RemoveComments(sNewSource)
sNewSource = Replace(sNewSource, "@@@<<@@", "/*")
sNewSource = Replace(sNewSource, "@@>>@@@", "*/")
Call WriteFile("output.c", sNewSource)
main = EXIT_SUCCESS
End Function
- You'll probably want to specify the filenames in an array so you can decide on order.
- It is possible that the board has stuffed up some of the regular expressions.
- There are many things it doesn't handle - such as multi line defines. | http://cboard.cprogramming.com/tech-board/48057-multi-file-source-single-file-source-printable-thread.html | CC-MAIN-2015-35 | refinedweb | 734 | 60.82 |
I need some help on Arrays. Here is the project I'm working on.
Write a program to read the items into two arrays, x and y, of size 20.
Store the products of corresponding pairs of elements of x any in a third away, z, also of size 20. Print a three-column table that displays the arrays x, y, and z. Then compute and print the square root of the sum items Z.
Now I have some of the code done and what I need advice in is how to take the numbers of arrays x and y, add them, make the square root and to store them in the new array called Z.
Thanks for any future advice.
// Warren Culp // 9/27/09 // Prof. Yoa #include<iostream> #include<iomanip> using namespace std; int main() { int X[20], Y [20]; cout << "Please enter 20 numbers for row 1" << endl; for(int count = 0; count < 20; count++) { cin >> X[count]; } cout << endl; cout << "Please enter 20 numbers for row 2" << endl; for (int count = 0; count < 20; count++) { cin >> Y[count]; } cout << "The contents of both arrays are" << endl; cout << endl; cout << "Array X" << " " << "Array Y" << endl; cout << "---------------------------" << endl; for (int count = 0; count < 20; count++) { cout << X[count] << " " << Y[count]; } return 0; } | https://www.daniweb.com/programming/software-development/threads/226403/adding-array-and-printing-square-root-out | CC-MAIN-2018-30 | refinedweb | 214 | 84.81 |
The last post ended with a link to a Python game. In the talk I gave introducing Python there was a lot more delving into what the actual game did, but it was a more interactive approach were there could be more dialog on how the intro slides were actually applying to the small snake game. Blogging does not lend itself to that same sort of interactivity.
However blogging does allow me to actually break down the game in a way that would have just run out of time during the live talk. Which is what I did in this entry.
Here is another slide from the talk I gave:
This slide was not my own creation. MikeD helped me explain the actual high level architecture of a simple video game. The snake game itself mostly follows these principles. I will refer back to the diagram on the slide during most of the rest of this entry.
Again here is the full source: and the version of the code that this entry talks about specifically can be found at the ‘presentation version’ tag here:
Start
The main file for the snake program is ‘python.py’ (aside: naming your python file python.py really makes tab completion more difficult than it should be). Open that up and you will see the first thing that the Python interpreter will execute.
import pygame
from random import randint
from myobjects.snake import snake
from myobjects.food import food
# Settings
SCREENSIZE = (1024,768)
BGCOLOR = (0xff, 0xa5, 0x00)
FRAMERATE = 30
The first few statements are telling the interpreter what other libraries the program will need to use. The two recommended ways to include other libraries are using the ‘import x’ statement which will import the whole module/package and the ‘from x import y’ statement which lets you pick specific items to import and import them directly into the namespace of the module importing them.
The second block of code is defining what the program will use as constants. Note: the constants are only a convention in Python.
if __name__ == '__main__':
playGame()
The next code that will get run is at the bottom of the file. Everything in between the imports/constants and the block of code above is a function definition. The functions are loaded into the namespace, but they are not executed. One thing to notice in the above code are ‘__name__’ and ‘__main__’. Identifiers that start and end in double underscores is a convention that says they are special Python symbols. In this case all we are checking to see is if the current file is the file that was passed directly to the interpreter (not imported from anywhere else) then if it is we will execute the playGame() function.
Load Assets
Next let’s look at the playGame function.
def playGame():
# define the arrow keys
arrow_keys = (pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT)
# init pygame
pygame.init()
game_surface = pygame.display.set_mode(SCREENSIZE)
# set the key repeat speed
pygame.key.set_repeat(10, 25)
# set the caption
pygame.display.set_caption('SNAKES!!!! - Press <Esc> to Quit, <R> to Restart')
The code above is the first part of the playGame function. The first thing playGame does is initialize everything needed to play the game. Most of the hardware assets get loaded/initialized during the pygame.init() call. There is a game surface that is being created. By default pygame disables key repeating so pressing a key and holding it gets counted as 1 key press. This functionality is not desirable for the snake game as the controls for moving the snake will be the arrow keys. Most people will be used to just pressing and holding the arrow keys to create motion. The last bit if initialization is setting a caption for our game window.
Game Loops(s)
In the snake game there are 2 nested loops. The outer loop is a ‘replay’ loop. This allows for the game to be played multiple times (the game does not allow the user to actually win, so allowing a replay at least makes losing more fun). The inner loop is what is more like a typical ‘main game loop’.
replay = True
while replay:
replay = False
# ... snip ...
# objects that need to be instantiated
# ... end snip ...
game_clock = pygame.time.Clock()
playing = True
while playing:
game_clock.tick(FRAMERATE)
That is the main outline of the game structure. Nothing too fancy there you can see the main playing loop nested inside a replay loop. There is some extra initialization that goes on between the two loops. If you go to the game on bitbucket the objects that are instantiated are the 2 snakes that are playing against each other [the ‘good’ snake is the python (obviously) the ‘bad’ snake is a rattle snake].
There is also some clock logic going on in there. This is the game clock. Its not strictly necessary to use it, but the human brain/eyes are limited to seeing things 30 times per second (generally). Rather than chew up CPU and other resources displaying things that nobody will see we just tick the clock 30 times a second.
Artificial Intelligence
Artificial Intelligence in terms of gaming is where the computer figured out what it needs to do. The simple snake game using the word ‘intelligence’ is a stretch.
# always move the bad snake
rattle_num_frames_in_dir = rattle_num_frames_in_dir + 1
moved_rattle = rattle_num_frames_in_dir % 2 == 0
while not moved_rattle:
if rattle_num_frames_in_dir > rattle_max_frames_in_dir:
curr_dir = rattle_dir
while curr_dir == rattle_dir:
rattle_dir = arrow_keys[randint(0,3)]
rattle_max_frames_in_dir = randint(25,50)
rattle_num_frames_in_dir = 0
moved_rattle = rattle.move(rattle_dir,game_surface)
if not moved_rattle:
rattle_num_frames_in_dir = rattle_max_frames_in_dir+1
The rattle snake in the snake game is the snake that is controlled by the computer. Every frame we want to move the the rattle snake just a little bit. The rattle snake has very simple rules. It must move in the same direction for 25-50 frames, then change to a random direction. The rattle.move call will return false if the snake could not move for some reason (like it is trying to move off screen). Pretty basic. An interesting modification to the snake program would be adding some more logic that feels more like AI to the rattle snake (have the rattle snake actively try and eat the food, or actively try to hunt the other snake would be cool, however I leave this as a later exercise).
Physics
Here is where things get pretty interesting from the point of view of making the video game feel like a video game. In the snake program there are 2 kinds of physics going on. The first is moving all the objects where the need to be moved in the frame. The second form of physics is the collision detection.
# detect collisions with the bad snake
for r1,r2 in ((r1,r2)
for r1 in python.get_rects()
for r2 in rattle.get_rects()):
if r1.colliderect(r2):
playing = False
replay = gameOver(game_surface)
break
This piece of code is demonstrating how to use generator expressions in Python. Which is closely related to list comprehension with Python. In Python syntax like this: [x for x in range(10)] will return a list. Replace the outer square brackets with parentheses and you get a generator object. Looking at the piece of code above there is a call to get_rects (which returns a generator object) for the python and a call to get_rects for the rattle. The calls are being used inside a generator expressions that will return a new generator object. That new generator object is what is being looped over. This allows us to check each rectangle of the python with each rectangle of the rattle for a collision.
If the concepts of list generation/generator expressions are new to you I recommend looking over that piece of collision detection code again. There is a lot going on there, but once you ‘get it’ there are some powerful things that you can do. In an earlier version of the code this piece of code was a complex nested loop. The new version I find must more readable.
# detect collisions with ourself
if python.head_hit_body():
playing = False
replay = gameOver(game_surface)
break
# eat
python.try_eat(food_items)
rattle.try_eat(food_items)
# replace food
create_food()
The next set of collision detections are mostly encapsulated inside head_hit_body and try_eat. Those calls are simple collisions detections that iterating over the objects and detect of there was a collision on each iteration.
The call to create_food is a stretch to call physics. It creates objects if needed. The interesting piece to note in terms of Python development is that create_food is technically a closure. The other thing I would like to call out is if you pull down the snake game, trying to replace the hard coded ‘2’ in the create_food function with something large (like 50) creates a very different game play. Trust me, try it!
Draw Frame
Here is where we get more into the technical aspects of a game. Everything we did above with moving objects, deleting objects and creating objects were done in the background. At this point in the frame the objects are all updated to the new state for the frame, but are not yet visible to the user. In order to do that we need to blit the objects onto the game surface. Then we need to update the display.
# update display & objects
python.update(game_surface)
rattle.update(game_surface)
for f in food_items:
f.update(game_surface)
pygame.display.update()
Every object we have has an update method that take the surface in as an argument. Those functions know what rectangles they used and can blit them onto the surface. Take a look at the food update() function.
def update(self, game_surface):
""" Updates the food """
rect = self.surface.get_rect().move(self.pos)
game_surface.blit(self.surface, rect)
All the update function does is make sure the rectangles are in position and blits them. The update function in snake is slightly more invoked, but not by much. While the code for this looks pretty simplistic, it is actually very important to get this right. Most times when developing your game (at least in pygame) when the objects aren’t moving, or aren’t behaving properly it is prudent to make sure that this steps is being done correctly.
Once the game surface is updated a call to pygame.display.update() will actually update the display that the user sees
Detect and handle user input
The snake game actually does all its event processing at the beginning of the main game loop.
# handle events
for e in pygame.event.get():
if e.type == pygame.QUIT:
playing = False
elif e.type == pygame.KEYDOWN:
if e.key == pygame.K_ESCAPE:
playing = False
replay = False
if e.key == pygame.K_r:
playing = False
replay = True
if e.key in arrow_keys:
python.move(e.key,game_surface)
The snake game handles a quit event (i.e. the user closed the game by using the ‘X’ on the game window) and a few keyboard events. If the escape key was his the game will exit. If the ‘R’ key was hit the game will replay. If any arrow keys were hit the python snake will be asked to move. The move function was already touched upon above during the AI. All it does is move the snake in a direction as long as it doesn’t go off screen.
Closing
That the end of the brief tour of game development with Python. I encourage you to download the snake game a play with it a bit. Once you are comfortable with the basic concepts pygame has much more to offer. | http://www.sirchristian.net/blog/category/python/ | CC-MAIN-2017-51 | refinedweb | 1,933 | 73.47 |
Sid Meier's Alpha Centauri: War Guide by Death 2000
Version: 1.0 | Updated: 2001-11-02 | Original File
E-mail: doggeru@hotmail.com Name: Death 2000 (a.k.a "Doggeru") Version: 1.0 E-mail comments and errors please. Topic: Alpha Centauri War Guide Chapter 1: Picking Your Faction I. What I Said Up There. Chapter 2: Deciding War I. What I Said Up There. Chapter 3: War I. Early War II. Middle War III. Late War IV. Planet Busters (And Extra War Tips!) Chapter 4: Thanx, Legal Stuff... I. What I said up there! THERE'S MORE INSIDE! (The Cootees) -----------------------(Picking Your Faction)----------------------- (Note From Death 2000: Use The FIND Feature if you have it to find what you are looking for because the Extra War Tips (BIG) is in no order and will take a while to go through so just FIND the word you want K) One of the most important things of Alpha Centauri is to pick the right faction. If you want war dont be Morgan or Deidre. Here's A Faction List to help you pick. The Lord's Believers: Sister Miriam Godwinson PROS: +1 Probe +25% Bonus To Attacking Due To Fanatics. CONS: -2 Research -1 Planet Accumulates No Research Points Till 2110 (10 Turns) Cannot Use Research Values. Ect: Best War Faction but is almost impossible to become a Morgan or a University. With its Probe Bonus you can steal tech easier from your enemies. But with your horrible research back-downs you wont be getting your Weapon's upgraded for a long time without the use of probe teams, Your 25% Bonus does nothing when your up against the wall and your enemy has unleashed its new Singularity Hovertank at your Capitol since its for ATTACKING only! Just remember that so you dont think your Scout Is the best Defense during 2180! War Rating: **** (Out Of 5) Gaia's Stepdaughters: Lady Deidre Skye PROS: +1 Planet +2 Efficeincy +1 Nutrients in Fungus Squares CONS: -1 Morale -1 Police Cannot Use Free Market Economics Ect: The Worst Faction to use for war. The Morale & Police Downgrades are bad to use for an army, They're Mind Worms do get a bonus due to the Planet upgrade but that doesnt mean you can go on a full scale war with those critters. Your Mind Worms Wont Do ANYTHING to a Hypnotic Tranced Scout Trooper! So PSI can be avoided rather easy with that. Just dont use this faction for world dominance UNLESS you have about 30 Planet Busters in stock... War Rating: * (Out Of 5) Human Hive: Chairman Sheng-Ji Yang (Yang as in Yong) PROS: +1 Growth +1 Industry Perimeter Defense At Each Base for free "With The Alpha Centauri Upgrade On The SMAC Web Site" Police State Has NO Minuses for The Hive CONS: -2 Economy Cannot Use Democratic Politics Ect: This is a all around good War Faction. It's Growth & Industry allow many units but its horrible economy can hinder its budget severly. Their Police State give good bonuses for Support & Police, The Support bonus allows a huge army & the police allow totalitarian control over your faction. Build Many Bases & A Huge Army to suceed. War Rating: ***1/2 (Out of 5) Morgan Industries: CEO Nwabudike Morgan (Or Just Morgan) PROS: +1 Economy Starts With 100 Energy Credits Other than 10 Extra Commerce With Treaty/Pact & Loans CONS: -1 Support Need A Hab Complex To Exceed Size 4 Cannot Use Planned Economics Ect: Very Bad War Faction. They're Support is bad and you'll be very tempted to go after Democracy & Wealth which will obliterate any war building you can think of. Dont Go to war, Just buy them off. War Rating: *1/2 (Out of 5) The Peacekeeping Forces: Commissioner Pravin Lal PROS: Extra Talent For Every 4 citizens 2x Votes for Govenor and Supreme Leader Can Exceed Hab complex population by 2 CONS: -1 Efficiency Cannot Use Police State Politics Ect: This Faction has NO Cons! that -1 is nothing when you go to democracy or something! But this faction isnt a war faction as you may think. Democracy lowers support by 2 which will lower your unit budget and even though erratic Brother Lal doesnt usually win wars with big factions. Your Better Of With The Hive or Spartans with a war. War Rating: ** (Out of 5) Spartan Federation: Colonal Corazon Santiago (Weird Name) PROS: +2 Morale +1 Police No Extra Cost for Prototypes CONS: -1 Industry Cannot Use Wealth Values Ect: Good War Faction with great moral bonuses. They're Industry Slows down construction of your army and Wealth cannot be choson so there goes any industry bonuses untill later. But with no prototype costs and great morale and police you can build that army you want. War Rating: ***1/2 (Out of 5) University Of Planet: Academician Prokhor Zakharov (Weird Name also, Russian) PROS: +2 Research Extra Tech at beginning of the game Free Network Node at each base CONS: -2 Probe Extra drone for every 4 citizens Cannot use Fundamentalist Politics Ect: Ugh... The Horrible Cons... The Probe and the opposite of the peacekeepers pro... That seems bad but do you see any -Support or - Morale? No. And that HUGE research bonus you can get high tech weaponry and build an army but you'll have to deal with drone riots alot. War Rating: ***1/2 (Out of 5) -------------------------------(Deciding War)---------------------- Yeah you need to have a good reason to start war most of the time. Here's your choices. Great Idea: They Have Started war With you (Which is unavoidable) You have NO territory due to your enemy has took up all of it around you Conquer* Good Idea: Your Enemy Has Opposite Social Choices Your Enemy is your opposite Your Enemy Has Been Harrasing You Your Enemy has been Probe Teaming you alot Ok Idea: You Know You can win Planet Buster Bad Idea: Just For Fun Your Not ready and you started war because you wanted to Your Enemy Is Your Pact Brother Your Enemy Is Has Surrenderd to You *If you are playing for conquest only. DO NOT DO ANY OF THE BAD IDEAS! Those will really hinder any friendships you have made and will lower your rep & is a waste of resources. ----------------------------(WAR)----------------------------- So Your At War, Im gonna tell you how to win in the 3 time zones. Early War: Ok. First off make sure your Army can use Rovers, Laser & The Lowest Armor. (Synthmetal) And have at least 3 bases with one of those with a high mineral output. With your highest mineral base building Laser Rovers with no armor for scouting terrain and use your Synthmetal Laser Soldiers for your main attack force. Once you found your enemy make (Censor) sure you dont goto war right now. First check your enemies base amount and know every little thing about your enemy (Lets Say Now your enemy is The Believers) Know your enemies weakness. Make sure you know how big they're army is (Lets say they got 2 Scouts in each base & they have 4 Bases) Well if they're that big we're gonna need to be bigger. Lets make about 4 SLS's & 2 Laser Rovers and attack they're first base with a SLS. You should easily defeat they're scouts and be able to take they're first base and now that you have they're territory load this base you took with your army and prepare to attack New Jerusalem (They're Capitol) Let's say they have 2 SS's (Sythmetal Soldiers Hand Guns) and they got a Observer Tower (+25% Defense). Now your gonna want to attack them in one turn due to the fact that they'll reinforce the capitol if its attacked so move ALL your forces next to the Capitol and begin your attack. You might lose a few units due to the Tower but here's the thing. Befor the attack send a rover out and pillage the Tower and other useful terrain enhancments that'll starve them and ruin they're bonus which will save you units. Afterwards the capitol should be yours and that leaves 2 bases remaining for the believers which they WONT probably ask you for a surrender pact due to they're overwhelming beliefs... Finish Them... If you have Restart Opponets your screwed... Since they'll blast off in a colony pod and re-build they're faction over and over and over ect... TURN THAT OFF! Now My Example is very unlikely due to the enemy will build an army as well but thats why you MUST use sneakyness to your advantage. Did Germany have control of europe by telling everyone "Hey im starting a war! PREPARE!" NO! Even though Hitler lost and Germany is now practicaly a third world nation thats not the point Germany Did The "Lighting War" attack on Poland and other countries which they were unprepared for and Germany was victorious exept that they were fighting the world (Hence World War) and they were outnumbered and outgunned. You better not make the same mistake Germany did in WW2 or your faction will be but a mermory. Thats A Good Example. War is a Pro and Con. If Victorious you will have complete control of any bases stolen and any tech you found but the resources you wasted on war that you could have used on Building Infrastructure and Building Bases which will have you win in the long run. War is good if your "Powerful" and if you "Know Your Enemy". Look in the Datalinks or an your Book and look up the opposing faction (Lets Say Spartans). The Spartans seem to be a powerful faction BUT they're -1 industry in the beginning is only worsenned by "Power Values" which lowers it by 2! USE THAT TO YOUR ADVANTAGE! Out Number The Spartans! They will take longer to build and they wont go changing over to wealth or planned econmics to fix it either! Outnumber them by 4 to 1 and you'll easily eliminate they're moral bonus. But if You Lose or surrendered to your enemy your basicaly screwed. You lost the game and your just a pawn of a now greater faction. Thats why your listening to me. Lets Start With A War With... Boats... Chaos Guns... Plasma Steel Armor & 2 opposing factions. Middle War: Well If You Read The Last 2 Paragraphs then you'll know what To Do & What not to do. First lets set up a few calculations. Your Lets say the Spartans & Your Enemy Is The Morganites. Spartan Data: Bases: 8 (1 in water) Cash: 100 Energy Credits Units: 1 Plasma Armored Hand gun wielding Soldier in each base. 4 Synthmetal Chaos Rovers. 5 Plasma-Chaos Soldiers & 4 Plasma-Chaos Foil Ships. Morgan Data: Bases: 12 (1 in water) Cash: 300 Energy Credits Units: 1 No Armor-Chaos Soldier in each base. 2 SC rovers & 3 PC Foils. Well As you see in my data that you outnumber Morgan but he has more bases and cash. Cash plays a useful role in war. You Must rush buy as many soldiers as possible due to war is about "How Fast You Can Make Them & How Fast You Can Use Them" First of all lets begin a stratagy. First of all lets say You both are on the same island as each other but are divided by an other faction inbetween or around the are of you 2. Diplomacy plays a good role in war. You need allies in order to win or the world will go against you. Lets Try to get them under are control First of all lets go off and butter up are little 3rd person shall we? Give the person (Lets Say University) a little cash (25 Credits Should do) and give them a tech if they dont got one. Now lets ask for a pact of brotherhood and if they say no then butter them up some more and try again. If yes ask them to declare war on the Morganites and give them a tech or cash in return (IF you have something or enough dont blow all your cash on this) lets say the do so. Now that Zakharov is on your side you should be able to begin your attack. Now lets build a probe team and probe morgans smallest base (Which will be the nearest) and get some credits. Dont bother about framing people since your at war, WHO CARES? Lets say you drain a good 20 credits from them which will lower them to about 280. Now send the same harden probe team at them again and knock out a structure. It doesnt matter which one lets just cause a little ruckus there. Lets say you destroyed they're Energy bank which will lower they're cash flow. Now lets begin by sending 2 SC Rovers at the smallest base. First Destroy all terrain enhancments around the base to ensure your victory. Now attack. You shouldnt lose any units and have control of this base. Spartan Data: Bases: 9 (1 in water) Cash: 130 (Due to end of turns) Energy Credits Same amount of units. Morgan Data: Bases: 11 (1 in water) Cash: 295 (Due to end of turns) Energy Credits 1 less defensive unit. Didnt Think that made an impact? Wrong. You have Morgan territory which mean you can reload and build right on the enemy grounds. now lets move are mobile forces to this base and prepare for an attack against the second largest city. Now before we attack pillage. Now lets think about the attack. They will have defense with other bases of course but we must "Surround" the base we are attacking so we can destroy any in-coming retaliation. now lets attack. We will probably lose a unit due to this base is large and it probably has a perimeter defense on it. Spartan Data: Bases: 10 (1 in water) Cash: 140 Energy Credits 1 less PC Soldier. Morgan Data: Bases: 10 (1 in water) Cash: 310 Energy Credits 1 less defensive unit. Now before the attack of Morgan Industries (They're Capitol) lets knock that water base out to be able to bombard the capitol. Water War is different due to you cant use Infantry or Rovers in it unless you happen to have Amphibious Pods Ability that'll allow you to attack from a boat. Now lets send are whole fleet towards the enemy water base. They should begin to retaliate with some PC Foils which your 4 Highly trained PC Foils should have no match with. Lets say you sunk all the boats and they sunk 1 and really damaged an other. Lets take the base. Your PC Foil is no match for a wussy infantry. Now repair your boat and rush over to the nearest shore to Morgan Industries. First Lets Bombard them with your 3 boats and hurt they're base units (Which are Plasma-Handgun units... About 4) Lets say they have a Perimeter Defense and have a Observatory Tower. Lets Pillage the enhancments. Once the pillaging is completed lets attack. Use Your PC Soldiers to soften them, Make sure not to lose many units since you got massive drawback in industry being Spartans. then use a Probe Team and wipe out a structure hopeing its they're perimeter defense and then launch an other probe team and this time infect the population. If your caught who cares your a war faction. By now you should have control of the capitol now. Zakharov should be conquering the now weakened morganites & You should be bombarding them for your ships untill they surrender or die. Have You Learned anything yet? Lets Recap. 1.DONT ever attack before your ready. 2.Use Sneakyness to your advantage. 3.Pillage Enemy Enhancments. 4.Bombard From Afar to weaken. 5.Outnumber Your Enemy. 6.Use Diplomacy to your advantage. 7.Use Advantages to the Most and Use your enemy's Disadvantages to the most. 8.Bribe Factions to help you. 9.Out Tech your enemies. 10.Have A good Reason to go into war. Those are some of the important ones. Middle War is harder than Early but easier than Late. Try to win during that time or earlier. I Am A Fair War Guru Arnt I? Even Though My Favorite Faction Is The Morganites! I Aint Black Or Anything But His Free Market And His Cash Rulz. I never goto war with Morgan. I Have Played War With Most faction and won each time (How Can I Lose If I Know This Much! :P) Anyways i have been playing these games since Civilization I. Late War: Here You Got Most Techs and you got a bunch of bases as do your multiple enemies. Your The Hive Here. I wont use any stats here since doing that will take WAY too long and im not getting paid am i? if you guys gave me a good $20 i'd do it (Not 20 yen! AMERICAN!) but untill the year 12000 i aint gonna do that. Well First... Let's Say You Are All on different islands within a Delta Shape. You Are The Hive in the up'est island and your enemies the Believer's on the left island and the university on the right side. Now this is a 3 Way Battle in which everyone is at war with everyone. Now I Should give you a list of avalible Unit Types. Infantry: PROS: +25% At Attacking Bases. CONS: 1 Move Per Turn. Rover: PROS: +25% In Open Terrain, 2 Moves Per Turn. CONS: Infantry Attack Bases Better Than this. Foil: PROS: Sea Movement, 3 Moves Per Turn (?). CONS: Only Sea, Cruiser Breakfast, Can only take Sea Bases Cruiser: PROS: Sea Movement, 5 Moves Per Turn (?). CONS: Only Sea, Can Only Take Sea Bases. Needlejet: PROS: Air Movment, 12 moves per turn (2 turns before crash) (?). CONS: Can Be Shot Down By SAM & ECM Units. Cannot Take Base. Hovertank: PROS: Heavytank, 2 Moves Per Turn (?). CONS: Kinda Slow for a future tank, Can't hover over water. Gravship: PROS: Can Go Anywhere without Fuel, 12 moves per turn (?). CONS: Can be shot down by SAM & ECM Units. Missle's: See Planet Buster. Mind Worm: PROS: +25% PSI on any unit, Fungus Movement. CONS: Many different ways of keeping these at bay. Isle Of the Deep: PROS: +25% PSI on any unit, Carries units depending on morale level. CONS: Cannot take land base, Many ways of keeping these at bay. Locust Of Chiron: PROS: +25% PSI on any unit, 6 moves per turn (?), No Fuel. CONS: Many ways of keeping these at bay. Ok now you should be able to understand what im talking about now. Now lets say you got like 4 Cruiser's with Probility Sheath & Fusion Gun on all 4, And 14 Foils with the same equipment. First send them in seperate platoons (2 Cruiser's, 7 Foil's) to each The Believers and The University, You shouldn't have that much to deal with, Once you gain control over all their sea bases use them as Repair Depo's and repair your ships. Now Develop some Infantry with drop pods, probility sheath & fusion gun. Now to cripple them, first make 2 transports and fill them with 5 probe teams in each one (Or the max which evers right) and send them to drain energy tokens and steal techs (If any) then knock out the infrastructure on capitol and the nearest bases around it for each faction, Then you should drop your soldiers in (After Bombarding) and then take the Capitol of each faction and with any surviving units try to take a few other bases around the Capitol (You did probe them right?) afterwards check if they wanna sign a blood-truce (Cease-Fire) if they do say NO if you know you can handle them say YES if your a sorry little wimp (Which if your reading this you aint) if they ask now say NO and if they wanna surrender say YES they become a under-state to you and they will most of the time give you ANYTHING (Tech, Cash, Maybe Even Bases!) they will become your personal lackey and thats what its all about... The Capitol is the mainstay of their empire, Where would America be without The White House? Russia Without The Kremlin? British Without Their Capitol Building? Thing im saying is that you take Washington D.C. or Moscow or London and you got a huge advantage and that'll pay handsomely. Well that raps up The Late Game and everything in between, You should be able to attack your enemy nicely, Also when moving your troops DO NOT MOVE THEM ON THE SAME TILE! Then if the leader dies usually the rest do and thats a major loss since this aint Civilization Call To Power isit!? -----------------------------(Planet Busters)-------------------------- Now for a weapon that deserves it's own section the Planet Buster. O.k this isnt just for it, This is for other such stuff so read on! The Planet Buster is the only weapon with that alone can eliminate a empire to a huge crater. Exept with it's major flaw... It really really really really really really hurts planet! Once i tried to do a HUGE Rush buy of planet busters with all my bases (Which equaled about 35) and tried to hurt them but the worst thing happened... The Mind Worms began a revelution, They destroyed everything with their swarms... Reminded me of StarCraft... Damn Zerg... Well to use these right you only use these on Bases FAR FAR FAR AWAY from you... The Worst thing that can happen is that your own planet buster kills off your capitol just because your neighbors with your enemy. Also lets talk a little about formation and such. You should never place your units on the same tile unless your in a base or a bunker. When attacking a base swarm around it to block off any reinforcements and to hit them hard since they will have a hard time hurting eight different units in the same turn. Use Mind Worms, They always get a advatage against non-psi units (unless they got hypnotic transe) and can grow huge quick and are very cheap. Normal Missiles are best in HUGE groups targeted at a incoming force and a base that just wont give up, one alone will do jack... Planet Busters also have a bad flaw, The Bigger the reactor the bigger the explosion which can REALLY hurt the planet and maybe even hit you (It aint funny when you got your HQ that holds all your Secret Projects in it blown to nothingness!) Rovers are best in the open, Use them to hit a incoming infantry force cause they'll get a good 25% bonus AND if they're higher than them an extra bonus! Artillery even though it doesnt hurt that bad is great at hurts an incoming force and a base, Would The brotherhood of Nod (TS) be anything without it? NO! (C&C gave them a better advantage, NUKE) Dont think the Morganites, University, Peacekeepers, Gaians are easy to beat just cause they got flaws, They got one thing the Hive, Believers, Spartans dont got and thats Cash & Production, They can outnumeber you very fast and even though their pacifists they can still outnumeber you and thats what counts most. Morgan has a bad flaw, -Support, To get out of that bad curse is to mind control an enemy base (THEY GOT CASH!) and send a force to that base and then switch the soldiers to that bases upkeep (Homebase) and then attack the nearest towns doing the same over and over, That usually does work and goes around that lowering of production and due to you probably got free market economics that'll take care of that pacifist problem. Gaians got a bad flaw, Pacifist, Horrible Morale & Police is not the way to win a war, To get out of that use mindworms, They require Planet for their morale and that'll usually be a big number (Green Economics) and if you have alot of doctors (Or your equalvent) you should be able to have a huge army of psi warriors. Try to own a island or continent for having no neighbors is better than having any, And Terraform the ground to your likeing (THERMAL BOREHOLE!) and always use Sensor Arrays in Forests (Once you got Hybrid Forest Structure BUILD IT and grow ALOT of Forests! It brings in alot of Food, Energy & Minerals!) Probe Teams are the spy's of the future, They can check up on an enemy base and poisen them (Lowers Population, Atrocity), Steal tech (If any) steal cash (If any) Mind Control (If enough cash) and Thought Control (If enough cash). Use them wisely. Many people wonder whats the difference between Mind Control & Thought Control, Mind control hurts your rep as the latter doesnt but costs more, If you're a Pacifist then use Thought Control, if not the latter. Your Choice. Needlejet's are best for quick air strikes against other forces and bases, They can be shot down by a SAM-ECM Soldier but they have great power. Gravships are the mother of war, They can move anywhere and without any fuel, Once you get these obsolete EVERY Needlejet you got and replace them with this, The only thing that stands in the way of a Sigularity Laser, Sigularity Reactor, Stasis generator Gravship is a Mind Worms and that can be dealt with even with this thing since it would have what 40 HP? HAH! Kill everything with 4 of these! 'Chopper's are very good, put a strong weapon on this with a good reactor and send it over to a base and attack attack attack then send some weak unit in for the takeover, These things got fuel and if their not in a base when they run out of fuel they'll be dealt damage and will sooner or later break all by itself. You've been warned. Upgrade Units when you get new technology, You Dont Want To Forget and then end up having only Scout Infantry Guarding your Capitol! It's Happend to me way to often (I Am An Aristocrat... "Acts All Snobby") Also Upgrade Your Reactor Everytime you get a new one DONT FORGET, A Reactor add's to movement and HP! A Singularity Reactor is 4x better than a Fission! This'll be updated every now and then like when i discover a good stratagy to put in here... Just remember look here for new stuff the other stuff probably wont be updated... (Im a very busy man!) ----------------------------(Thanx)------------------------------------ Myself for doing this of course! My "family" for food and love i guess...? Jesus for being my God and such. My Personal Friend Jeff Rash who i share not only my time but my own internet with! The Nice People On IRC who either dont annoy me or end up getting virtualy killed! Sid Meier for starting Civilization I and a legacy. Firaxis Games' Brian Reynolds for designing Alpha Centauri. Firaxis Games itself for creating this game. And You For Reading This! --------------------------------(Legal Stuff)-------------------------- I am very protective of my stuff (All my stuff has "0wned By Death 2000" on it) and i do not want anyone useing my faq for themselves. I will not allow any illegal post of my faq, My Faq is to be used on Gamefaqs.com or anyone else who follow's my rule. If you don't tell me of your using of my faq and i find it on your site i will sue you for up to $250,000,000,000 in cash and i cannot lose do to this being stated. You Must Tell me of your posting and tell me of the site you own and give me the address and the location of this faq if you fail even one of these you wont be getting it. (C)Death 2000 Copyrighted, 2000 to Infinity-Forever. ----------------------------------(War Document Ended)----------------- | http://www.gamefaqs.com/pc/96102-sid-meiers-alpha-centauri/faqs/14516 | CC-MAIN-2015-06 | refinedweb | 4,728 | 79.5 |
.
Create the project
The first step for building the application, as usual, is to create a JSF project in Exadel. For that matter, you have to select Exadel Studio > JSF > JSF Project (Figure 2).
The next step should be to create the required JSP files that composed the application. In this line of work, we need to create the following files: login.jsp, success.jsp and error.jsp in the project. Using the New File JSP Wizard, displayed in Figure 3, we can easily create those files by selecting New > JSP File in the Package Explorer .
Defining the Navegation
At this point, it is reasonable to define the navigations of the site. This task is very straightforward with the Exadel’s Visual Editor for the JSF configuration file ( faces-config.xml) .
To open the Visual Editor we only need to double-click the faces-config.xml and the proper editor will pop-up. At first, an empty diagram should be displayed as we didn’t define anything at this point. First thing we got to do is to drag and drop our JSP files (login.jsp, success.jsp and error.jsp) to the diagram, so we will be able to define the navigation from one file to another. After we drag-and-drop those files, we should see some visualization like the one is presented in Figure 4.
Suppose we want to define one path of execution from login.jsp to success.jsp. The first thing we do is select the Arrow icon of the vertical toolbar of the Visual Editor. Then we got to select the login.jsp icon (the source page), after that we click on the success.jsp (the target page). In the same manner we define the navigation flow from login.jsp to error.jsp.
Notice that, the outcome expected from the login.jsp, to navigate to success.jsp (or error.jsp), is inferred by Exadel as the name of the target file. The final display should be exactly the same as the one that is shown in Figure 1.
Model: JavaBeans.
As the MVC architecture mandates we got to implement our business logic and data model in separated layers composed of different JavaBean components. The easiest way to define a JSF managed bean is to select the Tree tab of Visual Editor of the faces-config.xml’s file and then click con the Add button. When the New Managed Bean wizard appears we fill it with the appropriate data as shown in Figure 5.
In this example, we define a JavaBean with the following characteristics:
- Scope: request
- Class: javabeat.net.examples.User
- Name: User
Make sure to check the Generate Source Code option; this way Exadel will generate the appropriate file for us (if it doesn’t exist). After you click the Finish button the managed bean were already included into the project.
Then we add the following properties for the JavaBean, by means of the Add button of the Property panel shown for the bean in the Visual Editor:
The code should look like this:
package javabeat.net.examples; /** * @author marcelo.giorgi * */ public class User { private java.lang.String login; private java.lang.String password; public User() { } public java.lang.String getLogin() { return login; } public void setLogin(java.lang.String login) { this.login = login; } public java.lang.String getPassword() { return password; } public void setPassword(java.lang.String password) { this.password = password; } }
Action of the command
In JSF there are two principal ways for defining the navigation as a result of an user click on a given link (commandLink’s JSF component) or button (commandButton):
- Static outcome . When the navigation is known in compilation time (don’t depends on runtime values) we can simple hard coded the outcome of the action property of a commandLink or commandButton components.
- By means of a bean’s method . Other scenarios, require dynamic information, which may depend on variable factors, the user’s input for example, for these cases we need to implement a method that defines which way to go with the given input.
In our example we based our decision based on the user’s name in the checkLogin method of the User’s bean as we illustrate here:
public String checkLogin(String login, String password) { String result = "error"; if (userExists(login, password) && userPermission(login, ‘LOGIN_USER’)) { result = "success"; } return result; }
Notice the correspondence between the return values of this method and the navigation rules defined in faces-config.xml. In the next section, we bind this method with the commandButton that whether accept or reject the user’s login.
View: JSP’s edition.
In this section we will focus on the presentation’s component of the application. The main presentation component of this application is the login.jsp page, which we bring into picture by double-clicking in the Navegator View on the login.jsp file. This immediately produces the Visual Editor to be displayed (Figure 6).
Exadel provides a WYSIWYG Editor for the view components of a JSF application. That means, that we can drag and drop almost any JSF component to our view and configure each of them using wizards. This facility reduces enormously TTM (Time To Market) of our projects because it reduces the coding time and the probability of syntax errors.
In our example, we are going to construct the Login Page display for the login.jsp. We can accomplish this by doing the following:
- Insert a JSF form component to our view . Click on the form item of the JSF HTML panel shown in the Figure 6, and drop it inside the editor. When the wizard of the form appears (Figure 7), change the id attribute of the form with the loginForm value.
- Introduce the Name label in the form . We are going to implement this label with an outputText component from the JSF HTML panel , which can be done by means of the drag and drop feature. Enter the text ‘Login’ as the value of the outputText component when the wizard of the component shows up.
- Insert an inputText component for the login . This can be done in an analogous way as step 2, the slightly difference is that we drag and drop an inputText instead of an outputText. We change the id attribute of the component with the ‘inputLogin’ value, we can do that by selecting the Attribute ‘s tab of the Wizard. It is important to associate the value attribute to the login property of the managed bean we defined earlier, by doing this we would be able to use this value in any page of the application for the time the request lives. To define this correlation we select the button on the right of the value’s attribute name with label ‘ … ‘. This would bring up the Wizard illustrated in the Figure 8. In this wizard we select the login item that is a sub-element of the Managed Bean called ‘user’. As you might expect we can associate any Bean property using this dialog with the selected outputText, as well as any JSF Variable (like cookies, session attributes, etc.).
Figure 8.
- Introduce the Password label in the form . This component can be inserted in an analogous way as step 2. Enter the text ‘Password’ as the value of the outputText component.
- Introduce an inputSecret component from the JSF HTML panel . When we have to handle some kind of secret input from the user, usually a user’s password, we got to use the inputSecret component. To include such a component into the view, we drag it to the editor in the same way we did for the previous components. We change the id attribute of the component with this value: ‘inputPassword’.
- Using commandButton component . At this point the only thing that is left is some kind of button that enable us to either validate or not the login action of a given user. The commandButton is the JSF component that we are requiring for this functionality, so we drag it into the editor as we did in the previous steps. This time, we set the value of the component to ‘Log in!’. Remember, that we implement the business logic for the user’s login action in the checkLogin method of the user managed bean, so we can bind it to the button by setting the action attribute with the following value: #{user.checkLogin}.
At the end of the day, the final jsp code should look like this:
<table> <tbody> <tr> <td></td> </tr> <tr> <td></td> </tr> </tbody> </table>
This is it for our main page!. Now, we got to modify the success.jsp and error.jsp. In this article we will show the implementation of the former of those pages, the latter is almost identical from a technical point of view so we leave it to you for give your own implementation ;).
Follow these steps to implement the success.jsp page, which is displayed after the user successfully logs in:
- First of all we double-click the success.jsp file.
- Then we drag and drop an outputText as we had been doing, and set the value attribute to ‘#{user.login}’. As we explained above, this associates the outputText component to the login property of the user’s managed bean.
Then, the finished implementation of this view should look like this:
are successfully logged in!!
Up and running!
One requirement that we must fulfill is to include an index.jsp page that redirects our non-Faces request to our login.jsp page as a Faces request, in this way we make sure that all the JSF objects are correctly initialized. To achieve this we can use the New > JSP File wizard in a similar manner as we already did for the other jsp’s files, but this time using the JSPRedirect template (Figure 10).
Then we got to complete the page attribute of the jsp:forward element in the index.jsp with the value of ‘login.jsf’. Those, the code should look like this:
To see the results of what we were being doing in this article, we have to configure web.xml file so that the index.jsp file belongs to the welcome-file-list.
Figure 11.
This can be done manually, as you probably had done many times, or using the Web XML Editor that Exadel provides, as shown in Figure 11.
After that we can right click in the project and select Run on Server and the application would be executed within the Exadel virtual machine. Figure 12 illustrates the login’s form (on the left) and how the application should look like when the user successfully completes the login process (the right image).
Conclusion
This article shows how easy is to implement a JSF application using Exadel IDE. The release of this development tool as open source represents excellent news for the Java community. It is very important because JSF is not just another way of implementing the MVC pattern in our projects; rather it is a Java standard that influences the way IDEs evolves. Exadel’s implementation of JSF currently supports Ajax development as a clear example of the adoption of the emerging technologies. Building our applications based on standards guarantees that we keep our solutions on the leading wave of technology. | http://javabeat.net/building-jsf-application-with-exadel-ide/2/ | CC-MAIN-2017-34 | refinedweb | 1,881 | 64 |
getn_wstr, get_wstr, mvgetn_wstr, mvget_wstr, mvwgetn_wstr, mvwget_wstr, wgetn_wstr, wget_wstr - get an array of wide characters and function key codes from a terminal
#include <curses.h> int getn_wstr(wchar_t *wstr, int n); int get_wstr(wchar_t *wstr); int mvgetn_wstr(int y, int x, wchar_t *wstr, int n); int mvget_wstr(int y, int x, wchar_t *wstr); int mvwgetn_wstr(WINDOW *win, int y, int x, wchar_t *wstr, int n); int mvwget_wstr(WINDOW *win, int y, int x, wchar_t *wstr); int wgetn_wstr(WINDOW *win, wchar_t *wstr, int n); int wget_wstr(WINDOW *win, wchar_t *wstr);
The effect of get_wstr() is as though a series of calls to get_wch() were made, until a newline character, end-of-line character, or end-of-file character is processed. An end-of-file character is represented by WEOF, as defined in <wchar.h>. A newline or end-of-line is represented as its wchar_t value. In all instances, the end of the string is terminated by a null wchar_t. The resulting values are placed in the area pointed to by wstr.
The user's erase and kill characters are interpreted and affect the sequence of characters returned. effect of mvgetn_wstr() is as though a call to move() and then a series of calls to get_wch() were made. The effect of mvwgetn_wstr() is as though a call to wmove() and then a series of calls to wget_wch() were made.
The getn_wstr(), mvgetn_wstr(), mvwgetn_wstr() and wgetn_wstr() functions read at most n characters, letting the application prevent overflow of the input buffer.
Upon successful completion, these functions return OK. Otherwise, they return ERR.
No errors are defined.
Reading a line that overflows the array pointed to by wstr with get_wstr(), mvget_wstr(), mvwget_wstr() or wget_wstr() causes undefined results. The use of getn_wstr(), mvgetn_wstr(), mvwgetn_wstr() or wgetn_wstr(), respectively, is recommended.
These functions cannot return KEY_ values as there is no way to distinguish a KEY_ value from a valid wchar_t value.
get_wch(), getstr(), <curses.h>, <wchar.h> (in the XSH specification), XBD specification, General Terminal Interface . | http://pubs.opengroup.org/onlinepubs/007908775/xcurses/mvgetn_wstr.html | CC-MAIN-2013-20 | refinedweb | 330 | 54.02 |
In the gradient descent method of optimization, a hypothesis function, $h_\boldsymbol{\theta}(x)$, is fitted to a data set, $(x^{(i)}, y^{(i)})$ ($i=1,2,\cdots,m$) by minimizing an associated cost function, $J(\boldsymbol{\theta})$ in terms of the parameters $\boldsymbol\theta = \theta_0, \theta_1, \cdots$. The cost function describes how closely the hypothesis fits the data for a given choice of $\boldsymbol \theta$.
For example, one might wish to fit a given data set to a straight line, $$ h_\boldsymbol{\theta}(x) = \theta_0 + \theta_1 x. $$ An appropriate cost function might be the sum of the squared difference between the data and the hypothesis: $$ J(\boldsymbol{\theta}) = \frac{1}{2m} \sum_i^{m} \left[h_\theta(x^{(i)}) - y^{(i)}\right]^2. $$ The gradient descent method starts with a set of initial parameter values of $\boldsymbol\theta$ (say, $\theta_0 = 0, \theta_1 = 0$), and then follows an iterative procedure, changing the values of $\theta_j$ so that $J(\boldsymbol{\theta})$ decreases: $$ \theta_j \rightarrow \theta_j - \alpha \frac{\partial}{\partial \theta_j}J(\boldsymbol{\theta}). $$
To simplify things, consider fitting a data set to a straight line through the origin: $h_\theta(x) = \theta_1 x$. In this one-dimensional problem, we can plot a simple graph for $J(\theta_1)$ and follow the iterative procedure which trys to converge on its minimum.
Fitting a general straight line to a data set requires two parameters, and so $J(\theta_0, \theta_1)$ can be visualized as a contour plot. The same iterative procedure over these two parameters can also be followed as points on this plot.
Here's the code for the one-parameter plot:
import numpy as np import matplotlib.pyplot as plt # The data to fit m = 20 theta1_true = 0.5 x = np.linspace(-1,1,m) y =1): """The cost function, J(theta1) describing the goodness of fit.""" theta1 = np.atleast_2d(np.asarray(theta1)) return np.average((y-hypothesis(x, theta1))**2, axis=1)/2 def hypothesis(x, theta1): """Our "hypothesis function", a straight line through the origin.""" return theta1*x # First construct a grid of theta1 parameter pairs and their corresponding # cost function values. theta1_grid = np.linspace(-0.2,1,50) J_grid = cost_func(theta1_grid[:,np.newaxis]) # The cost function as a function of its single parameter, theta1. ax[1].plot(theta1_grid, J_grid, 'k') # Take N steps with learning rate alpha down the steepest gradient, # starting at theta1 = 0. N = 5 alpha = 1 theta1 = [0] J = [cost_func(theta1[0])[0]] for j in range(N-1): last_theta1 = theta1[-1] this_theta1 = last_theta1 - alpha / m * np.sum( (hypothesis(x, last_theta1) - y) * x) theta1.append(this_theta1) J.append(cost_func(this_theta1)) #1[0]), color=colors[0], lw=2, label=r'$\theta_1 = {:.3f}$'.format(theta1[0])) for j in range(1,N): ax[1].annotate('', xy=(theta1[j], J[j]), xytext=(theta1[j-1], J[j-1]), arrowprops={'arrowstyle': '->', 'color': 'r', 'lw': 1}, va='center', ha='center') ax[0].plot(x, hypothesis(x, theta1[j]), color=colors[j], lw=2, label=r'$\theta_1 = {:.3f}$'.format(theta1[j])) # Labels, titles and a legend. ax[1].scatter(theta1, J, c=colors, s=40, lw=0) ax[1].set_xlim(-0.2,1) ax[1].set_xlabel(r'$\theta_1$') ax[1].set_ylabel(r'$J(\theta_1)$') ax[1].set_title('Cost function') ax[0].set_xlabel(r'$x$') ax[0].set_ylabel(r'$y$') ax[0].set_title('Data and fit') ax[0].legend(loc='upper left', fontsize='small') plt.tight_layout() plt.show()
The following program produces the two-dimensional plot:
import numpy as np import matplotlib.pyplot as plt # The data to fit m = 20 theta0_true = 2 theta1_true = 0.5 x = np.linspace(-1,1,m) y = theta0_true +0, theta1): """The cost function, J(theta0, theta1) describing the goodness of fit.""" theta0 = np.atleast_3d(np.asarray(theta0)) theta1 = np.atleast_3d(np.asarray(theta1)) return np.average((y-hypothesis(x, theta0, theta1))**2, axis=2)/2 def hypothesis(x, theta0, theta1): """Our "hypothesis function", a straight line.""" return theta0 + theta1*x # First construct a grid of (theta0, theta1) parameter pairs and their # corresponding cost function values. theta0_grid = np.linspace(-1,4,101) theta1_grid = np.linspace(-5,5,101) J_grid = cost_func(theta0_grid[np.newaxis,:,np.newaxis], theta1_grid[:,np.newaxis,np.newaxis]) # A labeled contour plot for the RHS cost function X, Y = np.meshgrid(theta0_grid, theta1_grid) contours = ax[1].contour(X, Y, J_grid, 30) ax[1].clabel(contours) # The target parameter values indicated on the cost function contour plot ax[1].scatter([theta0_true]*2,[theta1_true]*2,s=[50,10], color=['k','w']) # Take N steps with learning rate alpha down the steepest gradient, # starting at (theta0, theta1) = (0, 0). N = 5 alpha = 0.7 theta = [np.array((0,0))] J = [cost_func(*theta[0])[0]] for j in range(N-1): last_theta = theta[-1] this_theta = np.empty((2,)) this_theta[0] = last_theta[0] - alpha / m * np.sum( (hypothesis(x, *last_theta) - y)) this_theta[1] = last_theta[1] - alpha / m * np.sum( (hypothesis(x, *last_theta) - y) * x) theta.append(this_theta) J.append(cost_func(*this_theta)) #[0]), color=colors[0], lw=2, label=r'$\theta_0 = {:.3f}, \theta_1 = {:.3f}$'.format(*theta[0])) for j in range(1,N): ax[1].annotate('', xy=theta[j], xytext=theta[j-1], arrowprops={'arrowstyle': '->', 'color': 'r', 'lw': 1}, va='center', ha='center') ax[0].plot(x, hypothesis(x, *theta[j]), color=colors[j], lw=2, label=r'$\theta_0 = {:.3f}, \theta_1 = {:.3f}$'.format(*theta[j])) ax[1].scatter(*zip(*theta), c=colors, s=40, lw=0) # Labels, titles and a legend. ax[1].set_xlabel(r'$\theta_0$') ax[1].set_ylabel(r'$\theta_1$') ax[1].set_title('Cost function') ax[0].set_xlabel(r'$x$') ax[0].set_ylabel(r'$y$') ax[0].set_title('Data and fit') axbox = ax[0].get_position() # Position the legend by hand so that it doesn't cover up any of the lines. ax[0].legend(loc=(axbox.x0+0.5*axbox.width, axbox.y0+0.1*axbox.height), fontsize='small') plt.show()
Comments are pre-moderated. Please be patient and your comment will appear soon.
Student 3 years ago
Very good, this is what I've been looking for!Link | Reply
Trustin 2 years, 3 months ago
Thanks pro. Very easy to understand and useful, but I think it's better if you can use FuncAnimation to show above example.Link | Reply
christian 2 years, 3 months ago
Thanks. Might do this, but will try to find an example that converges at a rate that looks good in an animation to show what's going on.Link | Reply
Jeremy 2 years, 3 months ago
Hi, I'm playing around with the x = np.linspace(min_x,max_x,m) values and I realize when I use huge numbers, I don't get a nice round contours. They look quite straight..Link | Reply
Was wondering if you know why this is happening?
christian 2 years, 3 months ago
If you increase the value of range of x but keep theta1_grid (corresponding to the gradient) the same, then the contours become very tall and narrow, so across the plotted range you're probably just seeing their edges and not the rounded ends. Try setting e.g. max_x = -min_x = 3 to see this. Note that the values chosen for the x-range will determine how well the fit performs (not well for the chosen starting point when the x-range is too large).Link | Reply
primef 2 years ago
Hi,Link | Reply
I was using your code to create a similar plot to yours. However after analyzing your code and the plots you get, I noticed that the results are wrong.
For Theta = [0,0], the cost J should be 2.04605263. When I print the J out of your code, I get the right value for J when thet is [0,0]. However in the contour plot this is not the case, as for theta [0,0] the corresponding J is 2.400. I assume the error is in the J_grid or in one of the theta grids, but unfortunately even after some hours of error search, I couldn't fix it.
Could you please check that, maybe I am seeing it even wrong.
Thank you in advance
christian 2 years ago
Thanks, primef – this was a bug in the way I constructed my J_grid array, as you supposed. I've fixed it now and the image has been corrected.Link | Reply
primef 2 years ago
Hi Christian,Link | Reply
happy to hear that you have fixed the bug so fast.
Thank you!
New Comment | https://scipython.com/blog/visualizing-the-gradient-descent-method/ | CC-MAIN-2020-29 | refinedweb | 1,397 | 59.09 |
import a form from one of my accounts that is password protectedAsked by everycontractor on January 09, 2017 at 05:41 PM
Can you I import the form that is password protected so I do not have to rebuild the full form? I have the username and password
- JotForm Support
Do you meant to transfer one form to another account? If that is the case, please note the following:
1) You need to open a thread from the account.
However, if you simply want to clone one form from an account to another, just grab your forms link, and follow this guide:
Let us know if you need more help. | https://www.jotform.com/answers/1029814-I-want-to-import-a-form-from-one-of-my-accounts-that-is-password-protected | CC-MAIN-2017-22 | refinedweb | 110 | 69.15 |
Terraform vs. Helm for Kubernetes
Terraform vs. Helm for Kubernetes
Time for a competition! When it comes to Helm, Terraform, and K8s, which infrastructure provisioning tool beats the other out and why? Let's take both for a test drive.
Join the DZone community and get the full member experience.Join For Free
I have been an avid user of Terraform and use it to do many things in my and command line, and Terraform additionally supports environment variables.
- Both support modularity (Helm has sub-charts while Terraform has modules).
- Both provide a curated list of packages (Helm has stable and incubator charts, while Terraform has recently started the Terraform Module Registry, though there are no Terraform modules in the registry that work on Kubernetes as of this post).
- Both allow installation from multiple sources such as local directories and git repositories.
- Both allow dry runs of actions before actually running them (helm has a –dry-run flag, while Terraform has the plan subcommand).
With this premise in mind, I set out to try and understand the differences between the two. I took a simple use case with following objectives:
- Install a Kubernetes cluster (Possible with Terraform only)
- Install GuestBook
- Upgrade GuestBook
- Roll back the upgrade
Setup: Provisioning the Kubernetes Cluster
In this step, we will create a Kubernetes cluster via Terraform using these steps:
- Clone this git repo
- The kubectl, Terraform, ssh, and Helm binaries should be available in the shell you are working with.
- Create a file called `terraform.tfvars` withso Terraform picks up all modules
terraform initso Terraform will pull all required plugins
terraform planto validate whether the Kubernetes provider in Terraform does not support beta resources. More discussion on this can be found here. Under the hood, we are using simple declaration files and mainly rc.tf and services.tf files in the gb-module directory, which should be self-explanatory.
Update GuestBook
Since the application is deployed via Replication Controllers, changing the image is not enough. We would need to scale down old pods and scale up new pods. So we will scale down the RC to 0 pods and then scale it up again with the new image. Run:
terraform apply -var 'fe_replicas=0' && terraform apply -var 'fe_image=harshals/gb-frontend:1.0' -var 'fe_replicas=3'
Verify the updated application at node port 31080.
Roll Back the Application
Again, without deployments, rolling back RC the correct cluster by running `export KUBECONFIG=${PWD}/admin.conf`
Since we are running Kubernetes 1.8.2 with RBAC, run the following commands to give tiller the required privileges and initialize Helm:
kubectl -n kube-system create sa tiller kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller helm init --service-account tiller --upgrade
(Courtesy: )
Run the following command to install GuestBook on namespace “helm-gb”:
helm install --name helm-gb-chart --namespace helm-gb ./helm_chart_guestbook
Verify that. To view the upgrade taking place and old pods being replaced with new ones, run:
helm status helm-gb-chart
Rollback
The revision history of the chart can be viewed via
helm history helm-gb-chart
Run the following command to perform the rollback:
helm rollback helm-gb-chart 1
Run
helm history helm-gb-chart to get rollback confirmation as shown below:
Cleanup
Be sure to clean up the same tool and code base for infrastructure as well as cluster management, including the Kubernetes resources. So a team already comfortable, and StatefulSet, not having these available via Terraform reduces the incentive for working with it.
- In case of a scenario where there is a dependency between two providers (Module do-k8s-cluster creates admin.conf and that could have provider-based dependencies. This is still an open issue within Terraform, and more details can be found here.
- Terraform's, running tiller inside the cluster managed the runtime resources effectively.
- The Helm charts repository has a lot of useful charts for various applications.
Helm Cons
- Helm becomes an additional tool to be maintained, apart from existing tools for infrastructure creation and configuration management.
Conclusion
In terms of sheer capabilities, Helm is far more mature as of today and makes it really simple for the end user to adopt and use it. A great variety of charts also give you a head start, and you don’t have to re-invent the wheel. Helm’s tiller component provides a lot of capabilities at runtime that aren't present in Terraform due to inherent nature of the way it is used.
On the other hand, Terraform can provision machines, clusters, and seamlessly manage resources, making it a single tool to learn and manage all of your infrastructure. That being said, for managing the applications/resources inside a clusters.
Published at DZone with permission of Harshal Shah , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/terraform-vs-helm-for-kubernetes | CC-MAIN-2019-47 | refinedweb | 822 | 53.41 |
Object-Oriented Programming or OOP has been an integral part of the software world for a while now. It is an excellent programming paradigm that offers a certain level of freedom and enhances the programming accomplishments for the developer.
There are certain basic concepts and principles that every developer should know. They drive the premise for developing an application using this model.
Here, we are going to take a look at some of the crucial yet basic OOPs concepts in Python. These concepts drive the programmers towards achieving better results as well as to model their apps in an enriching fashion.
What Is Object-Oriented Programming?
For the uninitiated, this is where we are going to begin our induction. Let’s understand OOPs as a layman would, to get a deeper understanding of how we can work it out.
In this programming structure, you can easily combine things with similar properties or behaviors into a single object. If you are talking about demographics, then that becomes a single object for this programming model. Similarly, if you are talking about actions to be taken, then that becomes another object.
They are all objects that contain raw data. Your software solution will program these objects in a way that they fulfill the end goal together. These objects will perform a few actions together, as programmed by you, and deliver the result.
An excellent example to help understand this would be an email program.
Let’s say you have one object that contains the email contents, such as the recipient’s name and the subject. There is a second object that details the attachment and sending the email. You will design a program that will automatically combine these objects, ensure that a fully-written email is ready with the desired attachments, and sent it to the recipient.
This is how OOP works. However, some concepts drive this into action. Let’s take a quick look at these concepts and how they function.
Read: Is Python an Object-Oriented Language?
How to Define a Class?
The class is what defines every object, and is an important aspect of OOPs concepts in Python. Let’s say you have four objects, such as eyes, ears, mouth, and nose. These are parts of a face, which is the class.
Let’s get started with how to define a class.
Let’s say you are talking about a class called email.
Class Email:
pass
This is how the class is defined. Use the “pass” so that when you run the code in a compiler, there are no bugs issued.
Only defining the class may not help you much. You need to add some properties to make it attractive and the code helpful. So, you need to add objects to your class.
The ._init_() method is what would prove to be useful when defining the properties within a class.
This will ensure that every single time you create a new object for the class, this method will set the parameters to the initial state, thus, initializing a new object every single time.
The first parameter for this method would always be self, even when you assign multiple parameters to it.
So, what happens in this case? Let’s say you created a new class. The instance is transferred to the self parameter. As a result, the ._init_() can assign fresh properties to the defined object.
If you are still pondering on how to use it, let’s understand it via an example.
Class Email:
def ._init_(self, name, recipient, address):
self.name = name
self.recipient = recipient
self.address = address
Let’s break this code down for better understanding.
The indentation expressed in the code above is critical. You should match the same when writing your program using OOPs in Python. Let’s understand the self variable in the above code.
The self.name produces an attribute that is called name. The value of the name parameter is assigned to this attribute. Similarly, attributes and values are assigned for the other-self variables too.
These attributes are known as instance. You will need to specify the value of every attribute mentioned within a particular instance. Let’s say that there are two types of emails – welcome and nurture. The email recipient would differ for both instances (welcome emails and nurture emails).
Class attributes, on the other hand, are different; they will contain the same value for all class instances. For instance, these are all inbound emails. This is the class attribute that you can define for them.
Class Email:
#Class Attribute
def ._init_(self, name, recipient, address):
self.name = name
self.recipient = recipient
self.address = address
Understanding Class and Instance Variables
Let’s take the above example where we have created a class attribute as well as two instance variables to understand OOPs in Python better.
Class Email:
def ._init_(self, name, recipient, address):
self.name = name
self.recipient = recipient
self.address = address
Let’s talk about instantiating the objects within this class. You need to set values for each of these objects. This will be the initial value for every object, as discussed in the earlier part of the guide. In case you don’t assign values to these objects, then you will receive a TypeError.
Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
TypeError: __init__() missing 4 positional arguments: ‘name’, ‘recipient’, and ‘address’
We can add value immediately after the class name.
Nurture Email = Email (Nurture, David, david@xyz.com)
Welcome Email = Email (Welcome, Daisy, daisy@abc.com)
With the above code, we have generated two instances, for a nurture email and a welcome email. Let’s check the __init__() defined after the class instance for the above code. We see four parameters, including self. However, no variable has been mentioned for self. Let’s understand why?
So, whenever you create a new object within a class, you are instantiating the class. You will be assigning a memory address while doing this, where the variable will be stored. As soon as you instantiate a new object, Python will automatically create an instance, and it will be passed to the first variable in the .__init__() method. As a result, the self is removed in this method.
With the class variable, you can ensure that every instance you have created has a variable or value associated with it. This will ensure quicker and easier results, and thus, safer conclusions for your programming.
Also Read: Must Read 47 OOPS Interview Questions & Answers For Freshers & Experienced
Summing Up
We have understood the various aspects of creating a class, object, and method using the Python OOPs programming model here. Apart from this, we have also understood concepts such as instances and instantiating, which are core to OOPs programming in Python. Next, you will need to understand the principles that govern these instances and classes such as inheritance, polymorphism, abstraction, and encapsulation. They are core OOPs concepts in Python that drive your application and its results.
To move further in the Python funnel, you need to have your basics clear and rooted. So, dive into classes and understand how it works. Play around a bit with these variables, and understand their outcomes before you can set-up your application.
If you are curious about learning data science to be in the front of fast-paced technological advancements, check out upGrad & IIIT-B’s PG Diploma in Data Science and upskill yourself for the future. | https://www.upgrad.com/blog/a-complete-guide-on-oops-concepts-in-python/ | CC-MAIN-2021-39 | refinedweb | 1,244 | 67.25 |
daftpython
Sunday, 13 April 2014
pyvideo.org - Introduction to game programming
pyvideo.org - Introduction to game programming
Monday, 7 April 2014
Capturing Code Snippets - Part One
Long time no blog!
I've been spending more time with Dart so something had to get out of the way. However I have been revising my Python in time for the PyWeek game jam next month. I thought I would break radio silence on the blog and record a few snippets so 1. I can find them 2. On the off chance they are a handy copy paste for someone else especially beginners! Some of this is from my abandoned (due to illness) previous PyWeek so it never got off my laptop. Care to blog anything yourself? :-)
This first post will cover MISC. Some runnable GFX stuff to come in a follow up post.
Two very simple snippets mainly for moving through colour indexes for graphics primitives but could easily be used for position e.g. a bad guy or obstacle going back and forth.
def keepWithinRange(i,l,u): if i<l: i=l elif i>u: i=u return i def loopWithinRange(i,l,u): if i<l: i=l elif i>u: i=l return iMaybe better to rewrite those with Min/Max at some point!
Misc code from various PyGame experiments and Pyweeks!
import random import pygame from pygame.locals import * def CreateBackground(screen): bg = pygame.Surface(screen.get_size()) bg = bg.convert() return bg def DrawText(bg, x, y, text, size=24, color=(255, 255, 255)): inst1_font = pygame.font.Font(None, size) inst1_surf = inst1_font.render(text, 1, color) bg.blit(inst1_surf, [x, y]) def RND(num): return random.randint(1,num) def randomPlusMinus1(): return random.randint(0,2) -1 def returnTrue(): return True
Sunday, 23 December 2012
Bouncy Text and Christmas Trees
First!!
Thursday, 20 December 2012
Simple Starfield in PyGlet
How about more stars?
Whilst stuck in bed unwell, I stumbled upon a fun video tutorial on how to write an asteroid game in pyglet. Pyglet is available for Python 2 and 3 (in alpha form) and provides a pure Python wrapper to OpenGL. Whilst not been as extensive a library as say PyGame, it does offer some interesting capabilities such as sprite rotation and scaling plus a route into the OpenGL world. The example code was very clean and readable. I do miss the lack of built in primitives but you can get round that.
I thought it would be fun to revisit the star field program and convert it to pyglet. At first I was disappointed with the speed. Cutting down the number of stars worked but what made a real difference was drawing each layer as a single batch/OpenGL command. That put things back at warp speed with the regular numbers!
I highly recommend the asteroid tutorial video. My Starfield demo code is available here.
Having several starfields on top of each other running at different speeds in order to give the idea of depth. This required no changes to the starfield code (though I did tweak it not to use tuples anymore - more to avoid confusion). A screenshot doesn't do it justice - run the demo to see the movement!
All examples from this blog will appear on the new DaftPython Google Code site. The latest star code is here. | http://daftpython.blogspot.com/ | CC-MAIN-2014-42 | refinedweb | 557 | 76.01 |
Hi,. -V -------------- next part -------------- Index: libavutil/mem.c =================================================================== --- libavutil/mem.c (revision 5808) +++ libavutil/mem.c (working copy) @@ -101,8 +101,9 @@ */ void *av_realloc(void *ptr, unsigned int size) { + void *old_ptr; #ifdef MEMALIGN_HACK - int diff; + long diff; #endif /* let's disallow possible ambiguous cases */ @@ -110,11 +111,54 @@ return NULL; #ifdef MEMALIGN_HACK - //FIXME this isn't aligned correctly, though it probably isn't needed + /* this should now be aligned correctly to 16 */ if(!ptr) return av_malloc(size); diff= ((char*)ptr)[-1]; - return realloc(ptr - diff, size + diff) + diff; -#else +); // realloc, so that ptr points to allocated + if(!ptr) // memory of the desired size, if realloc + { // is possible + ptr = old_ptr; + return NULL; + } + if( !(((long)ptr)&15) ) // if lucky, it's already aligned + return (ptr); + + old_ptr = ptr; // if it isn't aligned + ptr = memalign(16,size); // allocate a new aligned block of memory + if(!ptr) // if possible + { + ptr = old_ptr; + return NULL; + } + memcpy(ptr, old_ptr, size); // and move the memory there + + av_free(old_ptr); + return ptr; +#else /* the memalign hack isn't needed, nor is memalign, therefore malloc is + aligned on 16 (or does not need to be?) and, presumably, + the same applies to realloc */ return realloc(ptr, size); #endif } | http://ffmpeg.org/pipermail/ffmpeg-devel/2006-July/012513.html | CC-MAIN-2017-17 | refinedweb | 196 | 50.57 |
Paperspace Gradient consists of three major parts: Notebooks, Workflows, and (soon) Deployments. While Notebooks are designed primarily for exploratory work, Workflows are designed for more a more rigorous approach that leads directly to production.
Here we demonstrate an example of using Workflows in production by using them to update our Gradient Public Datasets.
In other words, we trust our Workflows enough to use them in real production on our own product, and you can too!
Note: This blog entry is about using Workflows to update our datasets. For more details on the datasets themselves, and Workflows, see here and here.
What are Gradient Public Datasets?
Gradient is designed to get people up and running quickly and easily with AI and machine learning, including deep learning and GPUs. While we want to remove the obstacles to enabling a hardware and software environment for AI, we want to make it easier to access your data too.
We achieve this by providing integrated connectivity to online data sources such as Amazon S3, the ability to run arbitrary code such as
curl or
wget for other data locations, and by our public datasets. Deep learning and GPUs often need large amounts of data to perform at their best, and so by making examples of this data conveniently available we lessen the barrier to users who want to get going without having to find their data, or perform a huge download.
Public datasets are accessed in the same way as your other Gradient Datasets, by pointing to their location in your code and including the Gradient namespace, so, for example, our dataset
openslr is at
gradient/openslr.
The datasets available in our curated public datasets collection are described in our documentation, and will be showcased here in a future blog entry.
The collection of data is constantly evolving, but at the time of writing they include StyleGAN, LSUN, Open SLR, Self Driving Demo, COCO, fast.ai, and some smaller ones such as Tiny-imagenet-200, Sentiment140, and MNIST.
See details about our public datasets and more in our docs.
What are Workflows?
As an end-to-end machine learning and MLOps platform, Workflows are Gradient's pathway for moving from exploratory data science into production.
Workflows are contained within Projects, a workspace for you or your team to run Notebooks and Workflows, store Models, and manage Deployments. Each Workflow consists of a set of jobs that are run in sequence. Jobs can be related to each other in a graph-like fashion, and can in turn call other scripts such as a Python
.py. This lets you create a pipeline of processing steps that is 100% specified, portable, and reproducible.
In the example, from a different project to this one, the
cloneStyleGAN2Repo and
getPretrainedModel jobs feed into the train, evaluate, and generate jobs. Each job that feeds into another is required to finish before the subsequent jobs can start, but jobs such as, e.g.,
trainOurModel and
evaluatePretrainedModel can run in parallel, provided (in this case)
cloneStyleGAN2Repo succeeds.
We can also view the same Workflow with Datasets included:
The Workflow itself is specified using YAML, which gives the required level of rigor for a production system. Some users may be less familiar with YAML, and so we provide some help with it to get you where you need to be.
To run a Workflow, you can run the YAML with the Gradient CLI, and it will show up in the GUI as above. The YAML itself is in a file, and consists of information to specify what compute resources to run the Workflow on, the jobs and their interrelationship, and the sort of operation that each job is performing.
This latter step is achieved by using Gradient Actions. These are similar to GitHub Actions, but Gradient Actions support running jobs in parallel and using large data. There are several actions, but for our purposes here the most important is
script@v1, which allows us to execute a set of commands within a job, as in a script.
For more details on Gradient Actions in a Workflow, go to the Workflows section of the docs.
Bring this project to life
Using Workflows to update our Public Datasets
So why do we need to update our public datasets? Previously, rather than Workflows, Gradient supported Notebooks and Experiments. The latter were designed for model training, are now deprecated, and have been superseded by Workflows. This previous setup, however, accessed datasets by pointing to the common
/datasets directory that is on Gradient's managed storage. So now we need to be able to access them in the Gradient dataset namespace that Workflows can see, as in the
gradient/openslr example above.
Why not just copy them over? Well, in principle we could by connecting the right filesystems, but using Workflows to update them provides several advantages:
- Using Workflows establishes provenance and reproducibility for where our public datasets came from
- It's easy to rerun and update them in future
- New public datasets can be added by adding new Workflows
- Workflows are in Projects, and Projects can be linked to GitHub repositories, so we can easily maintain versioning, and ancillary information such as dataset licensing
- Since the resulting created datasets are part of our product, it shows an example of our Workflows being used for an enterprise production purpose
Therefore, to update a public dataset, we run Workflows that look like this:
defaults: resources: instance-type: C7 jobs: downloadData: outputs: openslr: type: dataset with: ref: gradient/openslr uses: script@v1 with: script: |- ... curl -o /outputs/openslr/original-mp3.tar.gz \ '' ... cd /outputs/openslr ... md5sum original-mp3.tar.gz ... tar -zxf original-mp3.tar.gz ... image: ubuntu:18.04
The Workflow is downloading the data from the original source, and placing it in the Gradient Public Dataset, in this case,
gradient/openslr. Each Workflow run produces an explicit version of the dataset, whose ID is available, but the overall Datasets can be referred to by name.
Several details about our Workflows are visible in the code shown:
- The compute resource to use is specified by
resources, here being a C7 CPU instance on the Gradient Cloud. GPU instances, e.g. P4000 or V100, can be accessed in the same way.
- There is one job,
downloadData, which is listed under the main part of the Workflow,
jobs. Specifications such as
resourcescan be job-specific as well as the global example we use here, meaning that you can specify, say, a GPU only for the jobs that need it. A Workflow can contain several jobs.
- The job output, referred to as
openslrin this case, is of type
dataset, and its location (
ref) is
gradient/openslr. Gradient has several types of inputs and outputs that can be specified by types or actions, including mounted volumes, Git repositories, machine learning models, and Amazon S3 buckets.
- The Gradient Action
script@v1allows us to issue arbitrary commands as would be done at the terminal, in the form of a script. They are given after the
script: |-line.
- The data here is hosted online at a website under openslr.org, so we download them using curl. If the connection were unreliable, a loop plus the -C option can be used to resume a partially completed download. This can come in handy for large files (the one in the example is 82 gigabytes, and our largest so far is 206 gigabytes).
- The downloaded data are placed in the
/outputs/openslrdirectory. When the directory under
/outputshas the same name as the name given under
outputs:, the contents of the directory are placed in the job output, in this case the public dataset.
- Since any code is allowed, we can perform other useful steps related to obtaining large datasets, such as
md5sum, and file extraction, in this case
tar -zxf.
- The
image: ubuntu:18.04line tells us that we are running the Workflow in a Docker container, in this case, the Ubuntu 18.04 image. In general, like Notebooks, Workflows are run on a given Docker image, orchestrated by Kubernetes, giving an environment that is convenient (many installs and setups not needed), secure, and reproducible.
Once the Workflow run is completed, because the Dataset
gradient/openslr is public, it becomes available to our users.
The example shown has been for the
openslr dataset. In general, we have a single Workflow for each public dataset, each one containing the exact steps needed for the data at hand. This means that each dataset can be maintained independently, and the maintenance and provenance of the data seen.
Real data have many locations that require various connection methods. Some examples encountered when updating our public datasets here included Amazon S3 (use Gradient
s3-download@v1 action), Google Drive (use
gdown utility), and Academic Torrents (use
at-get tool). Similarly, there are many data formats and compression methods that were seen, including CSV flat files, LMDB image databases, TFRecords binary files, and
.zip and
tar.gz compression.
The combination of containers with installed software, ability to handle large data plus many files, and Gradient's flexible support for tools and interfaces, make it easy to build up an appropriate set of tools for what you need to do.
Our public datasets are now updated and available. We have therefore used Workflows in production to improve our enterprise business product!
Summary
We have shown Gradient Workflows being used to update our Gradient Public Datasets, showing an example of Workflows being used in production in the enterprise.
Using Workflows establishes provenance and reproducibility for where our public datasets came from, and enables the collection to be easily maintained and added to in the future.
Users can run Workflows similarly for their needs, from use of jobs for a more rigorous approach to end-to-end data science, through to a full enterprise production system.
Next steps
For more detailed information, see the documentation on Workflows and Gradient Public Datasets.
To get started with Gradient, including Notebooks, Workflows, Models, and more, see our tutorials, ML Showcase, or GitHub repository.
Thanks to Tom, Ben, Erika, and everyone else at Paperspace for making this project possible.
And thanks for reading!
Add speed and simplicity to your Machine Learning workflow today | https://blog.paperspace.com/using-gradient-workflows-in-production-updating-our-public-datasets/ | CC-MAIN-2022-27 | refinedweb | 1,699 | 59.74 |
Source: own resources, Authors: Agnieszka and Michał Komorowscy
The majority, if not all, of mocking frameworks provides 2 types of mocks i.e. strict & loose. The difference between them is that the strict mocks will throw an exception if an unexpected (not configured /set up) method was called. I prefer to use loose mocks because with strict ones unit tests are fragile. Even the small change in the code can cause that unit tests will start failing. Secondly, if you need to set up many methods a test becomes less readable. Now, I can see one more reason.
Today, my colleague showed me a bug in my tests that were using strict mocks. He started investigation because we observed the following strange erros occuring during builds on the server:
System.Runtime.Serialization.SerializationException: Unable to find assembly 'Moq, Version=4.5.22.0, Culture=neutral, PublicKeyToken=69f491c39445e920'.
It was not easy to find a root cause because he couldn't reproduce a problem locally. However, finally he found what was wrong. The problem laid in the fact that some of classes being mocked were implementing IDisposable interface. It means that at some point of time the garbage colector was trying to dispose them. However, the strict mocks were not expecting calls to Dispose method so they were throwing exceptions.
If you want to reproduce a problem try the following simplified code.
using System; using Moq; using Moq.Protected; namespace Sandbox { class Program { static void Main(string[] args) { var mock = new Mock<BaseClass>(MockBehavior.Strict); //To fix a problem uncomment this line //mock.Protected().Setup("Dispose", ItExpr.IsAny<bool>()); //If you call Dispose method directly in your code, then you also must setup the public Dispose method. //However, in this case the public Dispose method must be virtual because Moq can work only with virtual methods. //mock.Setup(x => x.Dispose()); var obj = mock.Object; } } /// <summary> /// A model implementation of IDisposable interface /// /// </summary> public class BaseClass : IDisposable { private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { /* ... */ } disposed = true; } ~BaseClass() { Dispose(false); } } }To sum up. The 3rd reason why I prefer loose mocks over strict ones is that sometimes it may be difficult to figure out which methods are actually used.
3 comments:
I cannot agree with You. When adding new method to class breaks Your tests, it's obviously a design issue. Broken tests may tell You, that You are violating Open-Closed principle. So You want to rethink Your solution..
Thrid reason You provided - when You cannot tell when method is used - something is wrong. If Your code is nondeterministic - how You can assure that it works?
"When adding new method to class breaks Your tests, it's obviously a design issue.".
"That exception You provided - main problem is calling Dispose in destructor...."
You are right that it's not guaranteed when a destructor will be called. However, it is how Dispose pattern should be implemented according to my knowledge. Of course, it's better to explicitly call Dispose method or use using clause and not to wait for GC.
"Thrid reason You provided - when You cannot tell when method is used - something is wrong.".
Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
Software testing course in chennai | https://www.michalkomorowski.com/2016/11/3-reasons-why-i-dont-use-strict-mocks.html | CC-MAIN-2019-13 | refinedweb | 562 | 58.08 |
Has anyone seen a DRASTIC change in speed after upgrading to 5.7? Just the simple task of copying photos now takes FOREVER. Importing iphoto for just two years of photos (my smallest iphoto library by far) took A WEEK. I did not have access to Lightroom for a week. I thought it was just going to be the iphoto import, but now my regular import is taking almost 1/2 an hour and only 22 photos into the import.
Oh no! I think I might be experiencing the same problem, oddly with almost exactly the same time to import from iPhoto, just shy of 7 days...
I also posted this problem to the form and am actually on the phone with Adobe support right now. I have an iPhoto library of ~15,000 photos and I didn't expect it to be very fast, but it's taking an average of at least 40 seconds per photo to import, and it has kept complete focus of LR so I can't even confirm that it isn't importing duplicates. By my calculations it should take over 166 hours to complete the import! Something has to be wrong here. I've been going for over 48 hours and am scared to stop the import if this really is normal performance.
Are normal import tasks also slow for you now? Can you share any more details? I can't test myself yet since the iPhoto import is still churning, but it could help troubleshooting with support. I'll let you know if they come back with anything, I'm on hold now.
In my case there was an issue with the hard drive. I haven't tried to
import any more iphoto photos yet, but will try overnight tonight and
report back what I find. I can now import into lightroom onto a different
hard drive so my lightroom is finally functional again. (although my drives
is giving me i/o error on some files, my backup of the drive lets me open
the files without issues, so I'm hoping that my problem has been resolved.
Good luck! Mine literally took over a week and that was my smallest file. I
would go to bed and wake up and it wouldn't have moved but 10% at times! It
was super frustrating.
On Tue, Dec 16, 2014 at 7:48 PM, washertruck <forums_noreply@adobe.com>
Yeah, the support guys on the phone didn't know what was up but after confirming that the iPhoto import was not checking for duplicates (at least they thought) I canceled it and restarted my box. I've started a new import, still on my NAS, but this time to a fresh LR Catalog. It seems to be chugging along at a rate I would expect is closer to normal, about 2 photos per second (instead of 40 seconds per photo). I'll have to keep an eye on it to see if it slows down as it progresses. If it does I'd suspect a pretty nasty memory leak somewhere and will report these two forum posts to feedback.photoshop.com.
But hopefully a reboot and importing to a fresh Catalog fixes it for now. And hopefully I'll be able to import one catalog into the other and detect duplicates that way... | https://forums.adobe.com/thread/1658082 | CC-MAIN-2017-34 | refinedweb | 559 | 70.33 |
SpellChecker
Since: BlackBerry 10.0.0
#include <bb/utility/SpellChecker>
To link against this class, add the following line to your .pro file: LIBS += -lbbutility
Verifies the spelling of words and offers spelling suggestions.
The SpellChecker class uses the system spell check and the current system locale to verify spelling and providing suggestions.
Here's an example of how to implement functions that use SpellChecker to check the spelling of a word and return a list of spelling suggestions:
bool checkSpelling(QStringList const & words) { bool res = true; bb::utility::SpellChecker spellChecker; Q_FOREACH(QString const & word, words) { res = res && spellChecker.checkWord(word); } return res; } QStringList getSomeSuggestions(QString const & word) { bb::utility::SpellChecker spellChecker; return spellChecker.suggestions(word, 5); }
When using a TextArea or TextField, spell check can be enabled by default on text that's provided by the user, depending on the input mode that's used. The input modes for a TextArea and TextField are specified using the TextAreaInputMode and TextFieldInputMode classes, respectively.
Overview
Public Functions Index
Public Functions
Creates a new instance of the SpellChecker class.
BlackBerry 10.0.0
virtual
Destructor.
BlackBerry 10.0.0
Q_INVOKABLE bool
Checks whether the specified word is spelled correctly.
The check is performed based on the current system locale.
true if the word is spelled correctly, false otherwise. This function also returns false if an error occurred. You can use the ok parameter to check for errors.
BlackBerry 10.0.0
Q_INVOKABLE QStringList
Retrieves spelling suggestions for the specified word.
The number of results can be limited by specifying a limit.
The check is performed based on the current system locale.
A list of spelling suggestions for the specified word. Returns an empty list if an error occurred. You can use the ok parameter to check for errors.
BlackBerry 10.0.0
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/cascades/bb__utility__spellchecker.html | CC-MAIN-2016-07 | refinedweb | 316 | 59.3 |
Learn more about Scribd Membership
Discover everything Scribd has to offer, including books and audiobooks from major publishers.
Accounting rate of return (ARR) and payback period (PP) Net present value (NPV) and internal rate of return (IRR) Appraisal methods in practice Dealing with risk Managing investment projects
IntroductionThis week you will be introduced to various methods for evaluating projects and investments. You will examine the accounting rate of return and the payback period, two traditional methods for analysing the profitability of investment decisions. You will also learn about two contemporary methods: net present value and internal rate of return. These two methods are more widely used and accepted, as they overcome the limitations inherent in traditional methods. Finally, you will explore how managers analyse risk and manage investment projects. The recorded lecture begins by examining the accounting rate of return and payback period. The week concludes with a discussion of managing investment projects. You can play each section as many times as you like and also read the text version. The textbook readings and journal article cover the key learning objectives at a reasonably challenging level. The PowerPoint slides at the end provide useful diagrams and summaries to help you review the main points you have covered during the week. For the Assessment, you will discuss a question online. There is no Hand-in Assignment this week, but you should begin working on an outline in preparation for writing your Final Project.
ReadingThe journal article prescribed for this week is required reading and can be found in the online library at the University of Liverpool: Langfield-Smith, K. (2008) Strategic management accounting: how far have we come in 25 years?, Accounting, Auditing and Accountability Journal, 21 (2), pp. 204228, Emerald Management Xtra 95 [Online]. DOI: 10.1108/09513570810854400 (Accessed 30 June 2009). Textbook Atrill, P. & McLaney, E. (2009) Management accounting for decision makers. 6th ed. Harlow, England: Financial Times/Prentice Hall. (Please note that the references to these readings can be found in the Lecture Notes text under the headings of the topics to which they relate.) Accounting rate of return (ARR) and payback period (PP)
Pages 257269 in Chapter 8 analyse the use of the accounting rate of return and the payback period methods for evaluating investment projects. These traditional methods are simple in nature; however, they have limitations that must be properly understood and addressed. Net present value (NPV) and internal rate of return (IRR)
Pages 269283 in Chapter 8 describe how to compute and use net present value as a capital investment decision criteria. This method incorporates important elementssuch as timing of cash flows, interest rate, and inflationthat have significant impact on the decisions regarding the viability of projects. This reading also explores how to compute the internal rate of return (IRR) and describes how this rate can be used to make investment decisions. Appraisal methods in practice
Pages 283291 in Chapter 8 explore the trends in use of capital investment decision methods. You will find that contemporary methods, such as NPV and IRR, are more widely used; however, many organisations still use the traditional methodsnamely, ARR and PPbecause of their simplicity. Dealing with risk
Pages 291303 in Chapter 8 examine how managers evaluate the risk involved with projects by using sensitivity analysis and the concept of expected NPV. Managing investment projects
Pages 303308 in Chapter 9 discuss the stages involved with managing projects. Evaluating the profitability of projects is only one step, but it is also vital to further screen projects for quality and monitor them throughout their useful life.
Individual Project For this module, you are required to complete a course project that reveals mastery in application of the management accounting concepts and finance. This week you will continue to work on your Final Project for this module. Prepare an annotated outline of your Final Project, briefly indicating the content you plan to include in each section of the report and the concepts and techniques you plan to apply for analysing any data and developing your argument. This is due to be handed in next week. The outline should not include detailed sections of the Final Project. Instead, it should be a specific and crisp overview of the contents that will comprise the final report, which will provide a detailed account of the five tasks listed below. Remember that the tasks required for the Final Project are to: 1. Assess the budgeting process and procedures for the organisation with regards to preparation techniques, uses for evaluation, differences between business units/divisions, etc. 2. Analyse how the organisation collects, stores, and prepares management accounting information, particularly the use of a management accounting system (MAS) and how information is disseminated throughout the organisation. 3. Evaluate the costing process and procedures of the organisation with respect to method or approach utilised. 4. Assess the capital decision making process within the organisation with regards to what methods are utilised, how such methods are chosen, how projects are selected and managed, and what measures are employed to evaluate performance. 5. Evaluate the criteria or mechanisms used by the organisation for deciding how best to acquire capital and analyse the capital structure of the company. The annotated outline should address each of the tasks listed above. You need to briefly describe what information you will include in each section of the report that will satisfy these requirements. The work that will be carried out in the outline should
represent a higher-level view than the contents of the Final Project. As such, you must remain at this level to avoid reusing the same wording in the final document. There is NO submission this week.
Accounting rate of return (ARR) and payback period (PP) Textbook reading (Atrill & McLaney: Ch. 8, pp. 257269) With the goal of maximising wealth to shareholders, management in general and financial managers in particular have a substantial responsibility in determining what courses of action an organisation will undertake. Compounding the complexity of this responsibility is the likelihood that companies will be faced with various options and decisions in terms of the projects that may be pursued. The focus for this week is the examination of techniques that help financial managers analyse and evaluate such possibilities, allowing them to discern which projects will increase wealth and which will not, as well as the priority that each project should receive. In order to properly address these investment appraisal decisions, you will focus on two traditional evaluation methods: the accounting rate of return (ARR) and the payback period (PP). One of the more traditional methods of evaluating capital investment decisions is the ARR, which expresses the average accounting profit generated by an investment as a percentage of the average investment made to earn that profit over the life of the project. To better understand how the ARR is computed and utilised, carefully examine the formula (p. 248) and example (Activity 8.2) that are provided in your reading. While the computation for the ARR is rather straightforward, it is important to understand what the final percentage provides for the financial manager. The percentage derived indicates how much the potential investment will increase or return to the organisation in terms of accounting profit. For example, in Activity 8.2, the investment decision in question would have an ARR of 11.1%, meaning that the accounting profit expected is approximately 11% more than it costs to invest in the project. Does this mean the company should pursue the project? It is impossible to tell from the information provided, because each organisation will have different percentage thresholds with regards to ARR that will support any decision to pursue the investment. The target ARR set by an organisation is the minimum rate that an investment must return before it can be deemed as acceptable, and this rate will vary depending on the specific requirements for each organisation. While the ARR is rather simple to use, it has some serious shortcomings that may hinder its widespread use. First, when expressing values in percentage form, the total amounts are ignored. So a project with a higher ARR than another may seem like the better choice, but such a project may actually create a substantially lower amount of wealth for the organisation. Also, using the ARR to compare projects falls short with regards to the timing of profits because it is only based on the accounting profit rather than cash flows. Two projects may be comparable with regards to the ARR, yet one project may return more profit in early years while the other returns a larger amount in later years. Another traditionaland rather simplemethod for evaluating capital investment decisions is the payback period (PP). By determining the length of time that it will
take the original investment to be repaid, use of the PP helps to make up for one of the limitations of the ARR. Two projects that have comparable ARRs can be further examined by the PP method to determine which one will repay its investment sooner. The project with a smaller payback period would be deemed to be more attractive, as the costs will be recouped more quickly. This tool helps to incorporate the timing of cash flows between projects. As with the ARR, an organisation must have an acceptable threshold against which to compare the calculated PP. Although the PP method helps to account for some timing of cash flows, it still ignores the overall profitability of projects, thus limiting its use. Simply using the PP as the sole criterion could possibly eliminate projects that would create more wealth than others or those that would return a higher percentage. As you make your way through this section, you will become better acquainted with the limitations of both ARR and PP and find that these two methods are best used in tandem. However, even when using both methods, there are still limitations, as neither accounts for risk, interest, or inflation. In the next topic, you will examine two contemporary methods for analysing capital investment decisions.
Net present value (NPV) and internal rate of return (IRR) Textbook reading (Atrill & McLaney: Ch. 8, pp. 269283) While the ARR is helpful, it stops short of fully evaluating the profitability and suitability of a project from a financial perspective. Financial managers are not only concerned with accounting profits, as the ARR utilises, but also cash flows that result from projects. It is these cash flows that are used to cover costs and pay back investors. The two evaluation methods discussed in the previous section fail to incorporate the time value of money; as you well know, money received today is worth more than the same amount received at some time in the future. The use of net present value (NPV) incorporates the dimensions and timing of cash flow, as well as inflation and risk, and has become one of the most widely used and acceptable techniques for evaluating capital investment decisions. To best understand the concept of NPV, you should pay careful attention to the methods of calculating the present values of cash flows and examples provided in the reading. As you will see, this technique reduces, or discounts, the cash flows for each time period based on some rate of interest, known as the opportunity investment rate. This calculation is necessary to perform because it is possible to invest a certain amount of money with a financial institution and receive a return in subsequent time periods. By discounting the cash flows for each time period, it is possible to determine the amount of investment that would be presently required to achieve a future return. Once a present value for each time period has been determined, these amounts are then summed and compared to the total investment required for the project. To be acceptable, the project must show that the sum of the amounts is greater than amount of initial investment. The difference that is thus
calculated is the NPV of the investment. A positive NPV means that the project returns are better than those of the financial institution for the same investment, and, as such, the decision to undertake the project is the correct decision. A negative NPV depicts the opposite scenario. An important variable within the NPV evaluation method is the rate of interest used to discount the cash flows. (Note: Discounting tables are available in your text in Appendix E that can be used to calculate the present values of cash flows, for a series of different interest rates.) We can deduce that when the NPV of a project is positive, the rate of return for the project is higher than the interest rate used in the calculation. What interest rate to use in the calculation is an important consideration for the organisation, as this rate sets a minimum value that projects must return. As noted above, it is possible to place an investment with a financial institution and receive a return on the investment. So, it is important that the interest rate used in the NPV calculation at least incorporates the interest rate that can be achieved through safer investments, such as banks or government securities. However, organisations would desire a higher rate of return than those just mentioned, in part to account for the risk involved with undertaking projects and also to account for inflation. Therefore, the interest rate used to discount the cash flows generated by the project would most likely incorporate a premium for risk and inflation, known as the risk premium. Organisations are also able to adjust this risk premium for different projects based on the amount of risk perceived. The rate most often used in NPV computation is the cost of capital for the organisation. This represents the average cost of acquiring funds, either through issuing bonds or stock. While you will examine the cost of capital later in this module, it is important to realise that it is this cost, represented as a rate of interest, which must be considered when evaluating projects. In determining the interest rate to be used when calculating the NPV, you may begin to see how this rate is being developed as the minimum rate of return that is acceptable for a project. For example, if a company uses 20% as the interest rate for its NPV calculations and the NPV of the project is exactly 0.00, we are able to determine that the rate of return for the project is also 20%. Thus, the project meets the threshold and can be considered acceptable. However, the organisation may desire that projects not only have a positive NPV, but also meet a predetermined rate of return, such as the internal rate of return (IRR). More specifically, IRR is the interest rate that would create indifference between making an investment or not; this metric is calculated for a value of the NPV equal to zero.The IRR is determined by backing into it through an examination of NPV. As you will see, and as the authors state, this process can be very time consuming if completed by hand, so the use of computer software is often employed. This process is accomplished by calculating the NPV of projects using different rates and eliminating them until one gives an NPV equal to zero. For evaluation purposes, the IRR serves both as a threshold rate for individual projects and as a comparison rate
between projects. However, IRR does very little for evaluating wealth generation, making NPV a superior measure. The examples provided throughout this reading will help to illustrate how each method is computed as well as how each is used for evaluation. Appraisal methods in practice Textbook reading (Atrill & McLaney: Ch. 8, pp. 283291) Now that you have examined some of the techniques used for analysing capital investment decisions, it is important to consider their actual use in the current business environment. After reviewing the advantages and disadvantages of each method, it would be easy to assume that most organisations would choose to utilise the NPV and IRR methods as their primary evaluators of projects. However, as the statistics show, many organisations still rely on the traditional ARR and PP methods. Quite simply, these methods are less complex in terms of calculating, but that does not make them less useful. The PP method, even in spite of its limitations, is still very popular due to its simplicity. The trends also show that organisations are utilising combinations of these techniques more often, rather than relying on one entirely. Nevertheless, the NPV and IRR methods have become the most popular ones utilised by many CFOs, as these techniques provide a greater amount of useful information for making investment decisions, and they account for such variables as the timing of cash flows, risk, and inflation. The reading examines the real-world use of the methods covered as well as some practical considerations that must be recalled when evaluating investment decisions. Dealing with risk Textbook reading (Atrill & McLaney: Ch. 8, pp. 291303) In computing NPV, organisations are able to account for some risk by adding a risk premium onto the interest rate used to discount the cash flows. As projects differ, different risk premiums can be used. However, this method still falls short of accounting for and dealing with the risk involved with projects. NPV is still based on projections of cash flows, sales revenues, cost savings, etc., which are likely to vary to some degree. Also, projects often span a considerable amount of time, which increases the likelihood of inaccurate cash flows (especially those closer to long term) as well as adverse conditions that might impact the project as a whole. One method that financial managers use to help analyse the risk involved with a project is sensitivity analysis. This technique requires a careful examination of the key variables affecting the project, such as sales volume, sales price, operating costs, initial outlay, financing costs, and project life. Each variable is examined to see how changes to it might ultimately affect the viability of the project. Example 8.3 in your reading demonstrates how such analysis is conducted. While this technique is
insightful, it does have its limitations. It takes advanced methods, such as linear programmingwhich are beyond the scope of this moduleto permit a simultaneous sensitivity analysis to be performed. Also, it leaves decision making subjective, as no clear decision rules are present. Another method for analysing risk is to develop an expected NPV of a project with the use of probabilities, which act as weights. Cash flows for each period are adjusted by the probability of that amount actually occurring; expected present value for each period is discounted using the chosen discount rate. The sum of the discounted expected values of cash flows will be the expected NPV. While the decision-making criteria are the same, a positive expected NPV indicates a viable project. This alternative method, which includes the notion of uncertainty associated with each option or alternativeand as such uses probabilities to gauge the value of the expected cash flowsmust be used with caution. The calculation risk involved with the use of this method stems from the determination of the probabilities. These are, for most cases, subjective assessments of the likelihood that each of the options will occur. The assessments, albeit subjective, are functions of the experience level of the managers involved in the investment decision. Carefully review the examples provided in the reading to better understand how expected NPV is derived as well as its limitations. Managing investment projects Textbook reading (Atrill & McLaney: Ch. 9, pp. 303308) Even with the use of appropriate evaluation methods, such as NPV and IRR, organisations and financial managers still have much to consider with regards to choosing and managing investment projects. Managers must consider the amount of investment funds that are available to them as well as the source of these funds. Determining the most viable projects is an exercise in futility if the amount of funds available is unknown. Managers will know how best to allocate the funds once the most profitable projects have been identified. The reading for this topic outlines the five stages of managing investment projects and discusses important considerations at each stage. We have already mentioned two of these stages, determination of investment funds available and identification of profitable projects. After these stages comes a more thorough evaluation of the selected projects that helps to determine the quality of each proposal and the ability of the managers who will be in charge. After projects have been approved, it is vital that they be continually monitored through consistent and timely reporting, which will help managers to detect any variations. This enables the project to be better controlled while providing managers the opportunity to develop corrective courses of action if needed.
Much more than documents.
Discover everything Scribd has to offer, including books and audiobooks from major publishers.Cancel anytime. | https://www.scribd.com/document/84967501/Lecture-Notes-Wk6 | CC-MAIN-2019-51 | refinedweb | 3,484 | 50.16 |
WIEN2k An Augmented Plane Wave Plus Local Orbitals Program for Calculating Crystal Properties
- Ethelbert Morgan
- 3 years ago
- Views:
Transcription
1 WIEN2k An Augmented Plane Wave Plus Local Orbitals Program for Calculating Crystal Properties User s Guide, WIEN2k 14.2 (Release 10/15/2014) Peter Blaha Karlheinz Schwarz Georg Madsen Dieter Kvasnicka Joachim Luitz Vienna University of Technology Inst. of Physical and Theoretical Chemistry Getreidemarkt 9/156, A-1060 Vienna/Austria
2 Peter Blaha, Karlheinz Schwarz, Georg K. H. Madsen, Dieter Kvasnicka, Joachim Luitz: WIEN2k An Augmented Plane Wave + Local Orbitals Program for Calculating Crystal Properties revised edition WIEN2k 14.2 (Release 10/15/2014) Univ. Prof. Dr. Karlheinz Schwarz Techn. Universität Wien Institut für Physikalische und Theoretische Chemie Getreidemarkt 9/156 A-1060 Wien/Austria ISBN ISBN
3 Contents I Introduction to the WIEN2k package 1 1 Introduction 3 2 Basic concepts Density Functional Theory The APW Methods The LAPW Method The APW+lo Method General considerations Quick Start Naming conventions Starting the server Connecting to the w2web server Creating a new session Creating a new case Creating the struct file Initialization The SCF calculation The case.scf file Saving a calculation Calculating properties Electron density plots Density of States (DOS) X-ray spectra Bandstructure Bandstructure with band character plotting / full lines Volume Optimization Setting up a new case Manual setup Setting up a new case using w2web
4 II Detailed description of the files and programs of the WIEN2k package 31 4 Files and Program Flow Flow of input and output files Input/Output files The case.struct.file The case.scf file Flow of programs Core, semi-core and valence states Spin-polarized calculation Fixed-spin-moment (FSM) calculations Antiferromagnetic (AFM) calculations Spin-orbit interaction Orbital potentials Onsite-exact-exchange and hybrid functionals for correlated electrons Unscreened and screened hybrid functionals ( hf -module) modified Becke-Johnson potential (mbj) for band gaps DFT-D3 for dispersion energy Shell scripts Job control Main execution script (x lapw) Create the master input file case.struct (makestruct lapw) Job control for initialization (init lapw) Job control for iteration (run lapw or runsp lapw) Utility scripts Save a calculation (save lapw) Restoring a calculation (restore lapw) Reduce atomic spheres and interpolate density (reduce rmt lapw) Remove unnecessary files (clean lapw) Migrate a case to/from a remote computer (migrate lapw) Generate case.inst (instgen lapw) Set R-MT values in your case.struct file (setrmt lapw) create add atom clmsum lapw Create case.int file (for DOS) (configure int lapw) Check for running WIEN jobs (check lapw) Cancel (kill) running WIEN jobs (cancel lapw) Extract critical points from a Bader analysis (extractaim lapw) scfmonitor lapw
5 analyse lapw Check parallel execution (testpara lapw) Check parallel execution of lapw1 (testpara1 lapw) Check parallel execution of lapw2 (testpara2 lapw) grepline lapw initso lapw init hf lapw init mbj lapw vec2old lapw clmextrapol lapw makescratch lapw Structure optimization Lattice parameters (Volume, c/a, lattice parameters) Minimization of internal parameters (min lapw) Phonon calculations init phonon lapw analyse phonon lapw Parallel Execution k-point Parallelization MPI parallelization How to use WIEN2k as a parallel program The.machines file How the list of k-points is split Flow chart of the parallel scripts On the fine grained parallelization Chemical shift NMR calculations Introduction Options Additional notes Wannier functions (wien2wannier) Usage Help and FAQ Spontaneous Polarization, Piezoelectricity and Born Charges (BerryPI) Options Spontaneous Polarization Born effective charges Piezoelectric constants Getting on-line help
6 5.10 Interface scripts eplot lapw gibbs lapw parabolfit lapw dosplot lapw dosplot2 lapw Curve lapw specplot lapw rhoplot lapw prepare xsf lapw opticplot lapw addjoint-updn lapw Initialization NN Execution SGROUP Execution SYMMETRY Execution LSTART Execution Dimensioning parameters Input KGEN Execution Dimensioning parameters DSTART Execution Dimensioning parameters SCF cycle LAPW Execution Dimensioning parameters Input DFTD Execution Input
7 7.3 ORB Execution Dimensioning parameters Input HF Execution Input LAPW Execution Dimensioning parameters Input LAPWSO Execution Dimensioning parameters Input LAPW Execution Dimensioning parameters Input SUMPARA Execution Dimensioning parameters LAPWDM Execution Dimensioning parameters Input LCORE Execution Dimensioning parameters Input MIXER Execution Dimensioning parameters Input
8 8 Analysis, Properties and Optimization AIM Execution Dimensioning parameters Input BerryPI BROADENING Execution Input DIPAN Execution Dimensioning parameters Input ELAST Execution Input FILTVEC Execution Dimensioning parameters Input FSGEN IRelast IRREP Execution Dimensioning parameters JOINT Execution Dimensioning parameters Input KRAM Execution Dimensioning parameters Input LAPW Execution Dimensioning parameters LAPW Execution
9 Dimensioning parameters Input LAPW Execution Dimensioning parameters Input MINI Execution Dimensioning parameters Input NMR OPTIC Execution Dimensioning parameters Input OPTIMIZE Execution Input QTL Execution Input Output SPAGHETTI Execution Input TELNES Execution Input Practical considerations Files TETRA Execution Dimensioning parameters Input XSPEC Execution Dimensioning parameters Input
10 9 Utility Programs symmetso Execution pairhess Execution Dimensioning parameters Input eigenhess patchsymm Execution afminput Execution Dimensioning parameters clmcopy Execution Dimensioning parameters Input Execution structeditor
11 Execution Visualization BALSAC XCrysDen Unsupported software Examples TiC FCC Nickel Rutile supercell calc Further examples III Installation of the WIEN2k package and Dimensioning of programs Installation and Dimensioning Requirements Installation tips for mpich and fftw (either version or 3.3) Installation of WIEN2k Expanding the WIEN2k distribution Site configuration for WIEN2k User configuration Performance and special considerations Global dimensioning parameters w2web General issues How does w2web work? w2web-files in you home directory The configuration file conf/w2web.conf The password file conf/w2web.users Using the https-protocol with w2web Environment Variables Trouble shooting Ghost bands References 225
12 IV Appendix 231 A Local rotation matrices 233 A.1 Rutile (T io 2 ) A.2 Si Γ-phonon A.3 Trigonal Selenium B Periodic Table 237
13 List of Tables 4.1 Input and output files of init programs Input and output files of utility programs Input and output files of main programs in an SCF cycle Lattice type, description and bravais matrix used in WIEN2k. The angle γ is defined via cos(γ) = cos(γ ) sin(α) sin(β) + cos(β) cos(α) Relativistic quantum numbers XC shortcut-switches LM combinations of Cubic groups (3 (111)) direction, requires positive atomic index in case.struct. Terms that should be combined (Kara and Kurki-Suonio 81) must follow one another LM combination and local coordinate system of non-cubic groups (requires negative atomic index in case.struct) Possible values of QSPLIT and their interpretation Quantum numbers of the core state involved in the x-ray spectra
14
15 List of Figures 2.1 Partitioning of the unit cell into atomic spheres (I) and an interstitial region (II) TiC in the sodium chloride structure. This plot was generated using BALSAC (see ). Interface programs between WIEN2k and BALSAC are available Startup screen of w2web Main window of w2web StructGen of w2web List of input files Task Electron Density Plots Electron density of TiC in (100) plane using Xcrysden Electron density of TiC in (100) plane Density of states of TiC Density of states of TiC Ti L III spectrum of TiC Bandstructure of TiC Bandstructure of TiC, showing t2g-character bands of Ti in character plotting mode Energy vs. volume curve for TiC Data flow during a SCF cycle (programx.def, case.struct, case.inx, case.outputx and optional files are omitted) Program flow in WIEN2k Flow chart of lapw1para Flow chart of lapw2para Schematic dependence of DOS and u l (r, E l ) on the energy D electron density in TiC generated with XCrysDen
16
17 Licence conditions of WIEN2k P. Blaha, K. Schwarz, G. K. H. Madsen, D. Kvasnicka and J. Luitz Prof. Dr. Karlheinz Schwarz Vienna University of Technology Inst. of Physical and Theoretical Chemistry A-1060 Vienna, Getreidemarkt 9/156 AUSTRIA Fax: DEFINITIONS: In the following, the term the authors, refers to P. Blaha, K. Schwarz, G. K. H. Madsen, D. Kvasnicka and J. Luitz at the above address. Program shall mean that copyrighted APW+LO code (in source and object form) comprising the computer programs known as WIEN2k or the graphical user interface w2web. MANDATORY TERMS AND CONDITIONS: I will adhere to the following conditions upon receipt of the program: 1. All title, ownership and rights to the program or to copies of it remain with the authors, irrespective of the ownership of the media on which the program resides. 2. authors. 3. I will not incorporate any part of WIEN2k or w2web into any other program system, without prior written permission of the authors. 4. I will keep intact all copyright notices. 5. I understand that the authors supply WIEN2k and w2web and its documentation on an as is basis without any warranty, and thus with no additional responsibility or liability. I agree to report any difficulties encountered in the use of WIEN2k or w2web to the authors. 6. In any publication in the scientific literature I will reference the program as follows:ät Wien, Austria), ISBN Please enter your publications with WIEN2k on our web-page for papers, so that we can easily include them in the list of WIEN-publications. In addition we like to receive a copy (ps-, pdf-file or reprint), especially for less common journals. Please send it to the second author, K. Schwarz. 7. It is understood that modifications of the WIEN2k or the w2web code can lead to problems where the authors may not be able to help. Please report useful modifications or major extensions to the authors. 8. I understand that support for running the program can not be provided in general, except on the basis of a joint project between the authors and the research partner. i
18 ii
19 Part I Introduction to the WIEN2k package 1
20
21 1 Introduction The Linearized Augmented Plane Wave (LAPW) method has proven to be one of the most accurate methods for the computation of the electronic structure of solids within density functional theory. A full-potential LAPW-code for crystalline solids has been developed over a period of more than twenty years. A first copyrighted version was called WIEN and it was published by P. Blaha, K. Schwarz, P. Sorantin, and S. B. Trickey, in Comput. Phys. Commun. 59, 399 (1990). In the following years significantly improved and updated UNIX versions of the original WIENcode were developed, which were called WIEN93, WIEN95 and WIEN97. Now a new version, WIEN2k, is available, which is based on an alternative basis set. This allows a significant improvement, especially in terms of speed, universality, user-friendliness and new features. WIEN2k is written in FORTRAN 90 and requires a UNIX operating system since the programs are linked together via C-shell scripts. It has been implemented successfully on the following computer systems: Pentium systems running under Linux, IBM RS6000, HP, SGI, Compac DEC Alpha, and SUN. It is expected to run on any modern UNIX (LINUX) system. Hardware requirements will change from case to case (small cases with 10 atoms per unit cell can be run on any Pentium PC with 128 Mb under Linux), but generally we recommend a powerful PC or workstation with at least 256 Mb (better 512 Mb or more) memory and 1 Gb (better a few Gb) of disk space. For coarse grain parallization on the k-point level, a cluster of PCs with a 100 Mb/s network is sufficient. Faster communication is recommended for the fine grain (single k-point) parallel version.,...) MPI+SCALAPACK (on parallel computers only) Usually these packages should be available on modern systems. If one of these packages is not available, it can either be installed from public domain sources (see Chapt. 11) or the corresponding configuration may be changed (e.g. using vi instead of emacs). None of the principal components of WIEN2k requires these packages, only for advanced features or w2web they are needed. WIEN2k has the following features that are new with respect to WIEN97: 3
22 4 CHAPTER 1. INTRODUCTION due to the new APW+lo basis set it is significantly faster (up to an order of magnitude). Optimizations in the most time consuming parts of LAPW1 and LAPW2 have been made. iterative diagonalization (for cases with large matrices and few eigenvalues) beside the k-point parallelization (including heterogeneous workstation clusters) a fine grain parallelization based on MPI is also available. A new web-based graphical user interface w2web has been developed. It does NOT require an X-environment and thus WIEN2k can be controlled from (but not run on!) any Windows- PC. This should particularly help the novice to get acquainted with WIEN2k but it should be useful for the regular user as well. support for AFM and FSM calculations spin-orbit coupling, including a new p 1/2 -LO for higher accuracy wavefunction plotting determination of irreducible representations elastic constants (cubic cases only) Topological analysis based on Bader s atoms in molecules concept LDA+U, orbital polarization (OP), magnetic and electric fields Exact-exchange and Hybrid functionals inside spheres new PKZB and TPSS meta-gga functionals The development of WIEN2k was made possible by support from many sources. We try to give credit to all who have contributed. We hope not to have forgotten anyone who made an important contribution for the development or the improvement of the WIEN2k code. If we did, please let us know (we apologize and will correct it). The main developers in addition to the authors are the following groups: C. Ambrosch-Draxl (Univ. Graz, Austria) and her group, optics T. Charpin (Paris), elastic constants H. Hofstaetter and O.Koch (Vienna) iterative diagonalization M. Jamal (Iran) scripts, 2D-optimize K. Jorissen (Univ.Antwerp), C.Hebert (TU Wien), telnes3 R. Laskowski (TU Vienna), structeditor, main developer of mpi-parallelization, new dstart version, NMR module E. Kabliman (TU Vienna), arrows F. Karsai (TU Vienna), elast, lapwso D. Koller (TU Vienna), prepare xsf lapw L. Marks (Northwestern Univ.): speed-up, various optimizations, geometry optimization (PORT) and new mixer (MSEC1, MSR1, MSR1a) R. Luke (Univ. Delaware): new mixer (MSEC1) P. Novák and J. Kuneš (Prague), LDA+U, SO, lapwdm, qtl, dipan C. Persson (Uppsala), irreducible representations M. Scheffler (Fritz Haber Inst., Berlin) and his group, forces, dstart, geometry optimization E. Sjöstedt and L Nordström (Uppsala, Sweden), APW+lo J. Sofo and J. Fuhr (Barriloche), Bader analysis F. Tran (Vienna), various xc-functionals, Forces for orbital potential, Hybrid-Functionals P. Wissgott (TU Vienna) join vectorfiles B. Yanchitsky and A. Timoshevskii (Kiev), sgroup We want to thank those WIEN97 users, who reported bugs or made suggestions and thus contributed to new versions as well as persons who have made major contributions in the development of previous versions of the code: R. Augustyn (Vienna), U. Birkenheuer (Munich, wavefunction plotting), P. Blöchl (IBM Zürich), F. Boucher (Nantes), A. Chizmeshsya (Arizona), R.Dohmen and J.Pichlmeier (RZG Garching, parallelization) P. Dufek (Vienna), H. Ebert (Munich), E. Engel (Frankfurt), H.
23 Enkisch (Dortmund), M. Fähnle (MPI Stuttgart), B. Harmon (Ames, Iowa), S. Kohlhammer (Stuttgart), T. Kokalj (Ljubljana), H. Krimmel (Stuttgart), P. Louf (Vienna), I. Mazin (Washington), M. Nelhiebel (Vienna), V. Petricek (Prague), C. Rodrigues (La Plata, Argentina), P. Schattschneider (Vienna), R. Schmid (Frankfurt), D. Singh (Washington), H. Smolinski (Dortmund), T. Soldner (Leipzig), P. Sorantin (Vienna), S. Trickey (Gainesville), S. Wilke (Exxon, USA), B. Winkler (Kiel) 5
24 6 CHAPTER 1. INTRODUCTION This work was supported by the following institutions: Austrian Science Foundation (FWF-Projects P5939, P7063, P8176, SFB08-11) Siemens Nixdorf (WIEN93) IBM (WIEN) We take this opportunity to thank for all contributions. For suggestions or bug reports please contact the authors by
25 2 The basic concepts of the present band theory approach 2.1 The density functional theory An efficient and accurate scheme for solving the many-electron problem of a crystal (with nuclei at fixed positions) is the local spin density approximation (LSDA) within density functional theory (Hohenberg and Kohn 64, Kohn and Sham 65). Therein the key quantities are the spin densities ρ σ (r) in terms of which the total energy is E tot (ρ, ρ ) = T s (ρ, ρ ) + E ee (ρ, ρ )+ E Ne (ρ, ρ ) + E xc (ρ, ρ ) + E NN with E NN the repulsive Coulomb energy of the fixed nuclei and the electronic contributions, labelled conventionally as, respectively, the kinetic energy (of the non-interacting particles), the electron-electron repulsion, nuclear-electron attraction, and exchange-correlation energies. Two approximations comprise the LSDA, i), the assumption that E xc can be written in terms of a local exchange-correlation energy density µ xc times the total (spin-up plus spin-down) electron density as E xc = µ xc (ρ, ρ ) [ρ + ρ ]dr (2.1) and ii), the particular form chosen for that µ xc. Several forms exist in literature, we use the most recent and accurate fit to the Monte-Carlo simulations of Ceperly and Alder by Perdew and Wang 92. E tot has a variational equivalent with the familiar Rayleigh-Ritz principle. The most effective way known to minimize E tot by means of the variational principle is to introduce orbitals χ σ ik constrained to construct the spin densities as ρ σ (r) = i,k ρ σ ik χ σ ik(r) 2 (2.2) Here, the ρ σ ik are occupation numbers such that 0 ρσ ik 1/w k, where w k is the symmetry-required weight of point k. Then variation of E tot gives the Kohn-Sham equations (in Ry atomic units), [ 2 + V Ne + V ee + V σ xc]χ σ ik(r) = ɛ σ ikχ σ ik(r) (2.3) which must be solved and thus constitute the primary computational task. This Kohn-Sham equations must be solved self-consistently in an iterative process, since finding the Kohn-Sham orbitals requires the knowledge of the potentials which themselves depend on the (spin-) density and thus on the orbitals again. 7
26 8 CHAPTER 2. BASIC CONCEPTS Recent progress has been made going beyond the LSDA by adding gradient terms of the electron density to the exchange-correlation energy or its corresponding potential. This has led to the generalized gradient approximation (GGA) in various parameterizations, e.g. the one by Perdew et al 92 or Perdew, Burke and Ernzerhof (PBE) 96, which is the recommended option. A recent version called meta-gga by Perdew et al (1999) and Tao et al. (2003) employes for the evaluation of the exchange-correlation energy not only the gradient of the density, but also the kinetic energy density τ(r). Unfortunately, such schemes are not yet self-consistent. 2.2 The Full Potential APW methods Recently, the development of the Augmented Plane Wave (APW) methods from Slater s APW, to LAPW and the new APW+lo was described by Schwarz et al The LAPW method (see sec. 2.1).. Figure 2.1: Partitioning of the unit cell into atomic spheres (I) and an interstitial region (II) This adaptation is achieved by dividing the unit cell into (I) non-overlapping atomic spheres (centered at the atomic sites) and (II) an interstitial region. In the two types of regions different basis sets are used:
27 2.2. THE APW METHODS 9 1. (I) inside atomic sphere t, of radius R t, a linear combination of radial functions times spherical harmonics Y lm (r) is used (we omit the index t when it is clear from the context) φ kn = [A lm,kn u l (r, E l ) + B lm,kn u l (r, E l )]Y lm (ˆr) (2.4) lm where u l (r, E l ) is the (at the origin) regular solution of the radial Schroedinger equation for energy E l (chosen normally at the center of the corresponding band with l-like character) and the spherical part of the potential inside sphere t; u l (r, E l ) is the energy derivative of u l evaluated at the same energy E l. A linear combination of these two functions constitute the linearization of the radial function; the coefficients A lm and B lm are functions of k n (see below) determined by requiring that this basis function matches (in value and slope) each plane wave (PW) the corresponding basis function of the interstitial region; u l and u l are obtained by numerical integration of the radial Schroedinger equation on a radial mesh inside the sphere. 2. (II) in the interstitial region a plane wave expansion is used φ kn = 1 ω e ikn r (2.5) where k n = k + K n ; K n ψ k = n c n φ kn (2.6) and the coefficients c n are determined by the Rayleigh-Ritz variational principle. The convergence of this basis set is controlled by a cutoff parameter R mt K max = 6-9, where R mt is the smallest atomic sphere radius in the unit cell and K max is the magnitude of the largest K vector in equation (2.6). In order to improve upon the linearization (i.e. to increase the flexibility of the basis) and to make possible a consistent treatment of semicore and valence states in one energy window (to ensure orthogonality) additional (k n independent) basis functions can be added. They are called local orbitals (LO) (Singh 91) and consist of a linear combination of 2 radial functions at 2 different energies (e.g. at the 3s and 4s energy) and one energy derivative (at one of these energies): φ LO lm = [A lm u l (r, E 1,l ) + B lm u l (r, E 1,l ) + C lm u l (r, E 2,l )]Y lm (ˆr) (2.7) The coefficients A lm, B lm and C lm are determined by the requirements that φ LO should be normalized and has zero value and slope at the sphere boundary The APW+lo method u l (r, E l ) at a fixed energy E l in order to keep the linear eigenvalue problem. One then adds a new local orbital (lo) to have enough variational flexibility in the radial basisfunctions: φ kn = [A lm,kn u l (r, E l )]Y lm (ˆr) (2.8) lm
28 10 CHAPTER 2. BASIC CONCEPTS φ lo lm = [A lm u l (r, E 1,l ) + B lm u l (r, E 1,l )]Y lm (ˆr) (2.9) This new lo (denoted with lower case to distinguish it from the LO given in equ. 2.7) looks almost like the old LAPW -basis set, but here the A lm and B lm do not depend on k n and are determined by the requirement that the lo is zero at the sphere boundary and normalized. General considerations In its general form the LAPW (APW+lo) method expands the potential in the following form V LM (r)y LM (ˆr) LM V (r) = V K e ik r K inside sphere outside sphere (2.10) and the charge densities analogously. Thus no shape approximations are made, a procedure frequently called a full-potential method. The muffin-tin approximation used in early band calculations corresponds to retaining only the l = 0 component in the first expression of equ (96) and Madsen et al An alternative formulation by Soler and Williams (89) has also been tested and found to be equivalent, both in computationally efficiency and numerical accuracy (Krimmel et al 94). The Fermi energy and the weights of each band state can be calculated using a modified tetrahedron method (Blöch 1/2 radial basis function in the scalar-relativistic basis (which corresponds to p 3/2 ), we have recently extended the standard LAPW basis by an additional p 1/2 -local orbital, i.e. a LO with a p 1/2 basis function, which is added in the second-variational SO calculation (Kuneš et al. 2001).
29 2.2. THE APW METHODS 11). In addition you can also calculate exact-exchange inside the spheres and apply various hybrid functionals (see Tran et al for details)., Schwarz et al 79,80) X-ray structure factors are obtained by Fourier Transformation of the charge density. Optical properties are obtained using the Joint density of states modified with the respective dipole matrix elements according to Ambrosch et al. 95, Abt et al. 94, Abt 97. and in particular Ambrosch 06. A Kramers-Kronig transformation is also possible. An analysis of the electron density according to Bader s atoms in molecules theory can be made using a program by J. Sofo and J. Fuhr (2001)
30 12 CHAPTER 2. BASIC CONCEPTS
31 3 Quick Start Contents 3.1 Naming conventions Starting the server Connecting to the w2web server Creating a new session Creating a new case Creating the struct file Initialization The SCF calculation The case.scf file Saving a calculation Calculating properties Setting up a new case We assume that WIEN2k is properly installed and configured for your site and that you ran userconfig lapw to adjust your path and environment. (For a detailed description of the installation see chapter 11. This chapter is intended to guide the novice user in the handling of the program package. We will use the example of TiC in the sodium chloride structure to show which steps are necessary to initialize a calculation and run a self consistent field cycle. We also demonstrate how to calculate various physical properties from these SCF data. Along the way we will give all important information in a very abridged form, so that the novice user is not flooded with information, and the experienced user will be directed to more complete information. In this chapter we will also show, how the new graphical user interface w2web can be utilized to setup and run the calculations. 3.1 Naming conventions Before we begin with our introductory example, we describe the naming conventions, to which we will adhere throughout this user s guide. On UNIX systems the files are specified by case.type and it is required that all files reside in a subdirectory./case. Here and in the following sections and in the shell scripts which run the package themselves, we follow a simple, systematic convention for file labeling. For the general discussion (when no specific crystal is involved), we use case, while for a specific case, e.g. TiC, we use the following notation: 13
32 14 CHAPTER 3. QUICK START Figure 3.1: TiC in the sodium chloride structure. This plot was generated using BALSAC (see ). Interface programs between WIEN2k and BALSAC are available. case=tic The filetype type always describes the content of the file (e.g., type=inm is input for mixer). Thus the input to MIXER for TiC is found in the file TiC.inm which should be in subdirectory./tic. 3.2 Starting the w2web server Start the user interface w2web on the computer where you want to execute WIEN2k(you may have to telnet, ssh,.. to this machine) with the command w2web [-p xxxx] If the default port (7890) used to serve the interface is already in use by some other process, you will get the error message w2web failed to bind port port already in use!. Then you will have to choose a different port number (between 1024 and 65536). Please remember this port number, you need it when connecting to the w2web server. Note: Only user root can specify port numbers below 1024! At the first startup of this server, you will also be asked to setup a username and password, which is required to connect to this server.
33 3.3. CONNECTING TO THE W2WEB SERVER Connecting to the w2web server Use your favorite WWW-browser to connect to w2web, specifying the correct portnumber, e.g. netscape where w2web runs:7890 (If you do not remember the portnumber, you can find it by using ps -ef grep w2web on the computer where w2web is running.) You should see a screen as in Fig Creating a new session The user interface w2web uses sessions to distinguish between different working environments and to quickly change between different calculations. First you have to create a new session (or select an old one). Enter TiC and click the Create button. Note: Creating a session does not automatically create a new directory! You will be placed in your home directory if no working directory was designated to this session previously (or if the directory does not exist any more). Figure 3.2: Startup screen of w2web
34 16 CHAPTER 3. QUICK START 3.5 Creating a new case-directory Using Session Mgmt. change directory you can select an existing directory or create a new one. For this example create a new directory lapw and than TiC using the Create button. After the directory has been created, you have to click on select current directory to assign this newly created directory to the current session. After clicking on Click to restart session the main window of w2web will appear (Fig.3.3. Figure 3.3: Main window of w2web 3.6 Creating the master input file case.struct To create the file TiC.struct start the struct-file generator using Execution StructGen (see figure 3.4). For a new case w2web creates an empty structure template in which you can specify structural data. Later on this information is used to generate the TiC.struct file. As a first step specify the number of atoms (2 for TiC) and fill in the data given below into the corresponding fields (white boxes): Title TiC Lattice F (for face centered) a Å(make sure the Ang button is selected) b Å c Å α, β, γ 90 Atom Ti, enter position (0,0,0) Atom C, enter position (.5,.5,.5) Click Save Structure (Z will be updated automatically) and set automatically RMT and continue editing :
35 3.6. CREATING THE STRUCT FILE 17 This will compute the nearest neigbor distances using the program nn and setrmt lapw will then determine the optimal RMT values (muffin-tin radius, atomic sphere radius). To learn more about the philosophy of setting RMTs see Since it is essential to keep RMTs constant within a series of calculations (eg. when you do a Volumeoptimization, see ), you should already now decide whether you want to do just one single calculation with fixed structural parameters, or whether you intend a relaxation of internal parameters (using forces and min lapw) or a volume optimization, which would required reduced RMT values. Choose a reduction of 3 % so that we can later optimize the lattice parameter. Figure 3.4: StructGen of w2web When you are done, exit the StructGen with save file and clean up. This will generate the file TiC.struct (shown now in view-only mode with a different background color), which is the master input file for all subsequent programs. A few other hints on StructGen: You have to click on Save Structure after every modifications you make in the white fields.
36 18 CHAPTER 3. QUICK START Add/remove a position/atom only if you have made no other changes before. In a face-centered (body-centered) spacegroup you have to enter just one atom (not the ones in (.5,.5,0),... ). StructGen offers a built in calculator:). When you now choose Files show all files, you will see, that tic.struct has been created. For a detailed description of these files consult sections 4.3 and Initialization of the calculation (init lapw) After the basic input file has been created, initalization of the calculation is done by Execution initialize calc.. For structures given by experiment (not man-made supercells,...) you would usually run in Fast mode, just specify a few most important imput parameters (or use the defaults). However, this introduction will guide you through all individual steps necessary to initialite the calculation. Simply follow the steps that are highlighted in green and follow the instructions. The initialization process is described in detail in section Alternatively you could run the script init lapw [-b] from the command line. All actions of this script are logged in short in :log and in detail in the file case.dayfile, which can easily be accessed by Utils. show dayfile. Initializing the calculation will run several steps automatically, where x is the script to start WIEN2k programs (see section: 5.1.1). x nn calculates the nearest neighbors up to a specified distance and thus helps to determine the atomic sphere radii (you must specify a distance factor f, e.g. 2, and all distances up to f * NN-dist. are calculated) view TiC.outputnn : check for overlapping spheres, coordination numbers and nearest neighbor distances, (e.g. in the sodium chloride structure there must 6 nearest and 12 next nearest neighbors). Using these distances and coordinations you can check whether you put the proper positions into your struct file or if you made a mistake. nn also checks whether your equivalent atoms are really crystallographically equivalent and eventually writes a new struct-file which you may or may not accept. If you have not done so at the very beginning, go back to StructGen and choose proper RMT values. You can save a lot of CPU-time by changing RMT to almost touching spheres. See Sec.4.3 x sgroup calculates the point and spacegroups for the given structure view TiC.outputsgroup : Now you can either accept the TiC.struct file generated by sgroup (if you want to use the spacegroup information or a different cell has been found by sgroup) or keep your original file (default). x symmetry generates from a raw case.struct file the space group symmetry operations, determines the point group of the individual atomic sites, generates the LM expansion for the lattice harmonics (in case.in2 st) and local rotation matrices (in case.struct st). view TiC.outputs : check the symmetry operations (they have been written to or compared with already available ones in TiC.struct by the program symmetry) and the point group symmetry of the atoms (You may compare them with the International Tables for X-Ray Crystallography ). If the output does not match your expectations from the Tables, you might have made an error in specifying the positions. The TiC.struct file will be updated with symmetry operations, positive or negativ atomic counter (for cubic point group symmetries) and the local rotation matrix.
37 3.7. INITIALIZATION 19 instgen lapw : You are requested to generate an input file TiC.inst and can define the spinpolarization of each atom. While this is not important for TiC, it is very important for spinpolarized calculations and in particular for anti-ferromagnetic cases, where you should flip the spin of the AFM atoms and/or set the spin of the non-magnetic atoms (eg. oxygen in NiO) to zero. x lstart generates atomic densities (see section 6.4) and determines how the orbitals are treated in the band structure calculations (i.e. as core or band states, with or without local orbitals,... ). You are requested to specify the desired exchange correlation potential and an energy that separates valence from core states. For TiC select the recommended potential option GGA of Perdew-Burke-Ernzerhof 96 and a separation energy of -6.0 Ry. edit TiC.outputst : check the output (did you specify a proper atomic configuration, did lstart converge, are the core electrons confined to the atomic sphere?). Warnings for the radial mesh can usually be neglected since it affects only the atomic total energy. lstart generates TiC.in0 st, in1 st, in2 st, inc st and inm st. For Ti it selects automatically 1s, 2s, and 2p as core states, 3s and 3p will be treated with local orbitals together with 3d, 4s and 4p valence states. edit TiC.in1 st : As mentioned, the input files are generated automatically with some default values which should be a reasonable choice for most cases. Nevertheless we highly recommend that you go through these inputs and become familiar with them. The most important parameter here is RKMAX, which determines the number of basis functions (size of the matrices). Values between 5-9 (3 if you have small H-spheres) are usually reasonable. Eventually you could change here the usage of APW or LAPW (set 1 or 0 after the CONT/STOP switch), since often APW is necessary only for orbitals more difficult to converge (3d, 4f). Here we will just change EMAX of the energy window from 1.5 to 2.0 Ry in order to be able to calculate the unoccupied DOS to higher energies. edit TiC.in2 st : Here you may limit(increase the LM expansion, increasse the value of GMAX (in cases with small spheres (e.g. systems with H-atoms) it will be automatically increased anyway) or specify a different BZ-integration method to determine the Fermi energy. For this example you should not change anything so that you can compare your results with the test run. Copy all generated inputs (from case.in st to case.in*). In cases without inversion symmetry the files case.in1c, in2c are produced. x kgen generates a k-mesh in the Brillouin zone (BZ). You must specify the number of k-points in the whole BZ (use 1000 for comparison with the provided output, a good calculation needs 10 times as much). For details see section 6.5. view TiC.klist : check the number of k-points in the irreducible wedge of the BZ (IBZ) and the energy interval specified for the first k-point. You can now either rerun kgen (and generate a different k-mesh) or continue. x dstart generates a starting density for the SCF cycle by superposition of atomic densities generated in lstart. For details see section 6.6. view TiC.outputd (check if gmax >gmin) Now you are asked, whether or not you want to run a spin-polarized calculation (in such a case case dstart is re-run to generate spin-densities). For TiC say No. Alternatively, w2web provides a Fast-mode, which is the recommended default and where the most imortant inputs can be specified right at the beginning and then the whole initialization runs at once. Please check carefully the STDOUT-listing and some output-files for possible errors or warnings!!. Only for hand-made case.struct files (eg. using supercells,...) one should run the first steps (from nn to symmetry step by step, since in such cases these programs may rewrite case.struct and specify different multiplicities or even change the unit cell. Initialization of a calculation (running init lapw) will create all inputs for the subsequent SCF calculation choosing some default options and values. You can find a list of input files using Files input files ( 3.5).
38 20 CHAPTER 3. QUICK START Figure 3.5: List of input files 3.8 The SCF calculation After the case has been set up, a link to run SCF is added, ( Run Programs run SCF and you should invoke the self-consistency cycle (SCF). This runs the script run lapw with the desired options. The SCF cycle After selecting run SCF from the Execution menu, the SCF-window will open, and you can now specify additional parameters. For this example we select charge convergence to : Specify charge to be used as convergence criterion, and select a value of (-cc ). To run the SCF cycle, click on Run! Since this might take a long time for larger systems; you can specify the Execution type to be batch or submit (if your system is configured with a queuing system and w2web has been properly set up, see section 11.3). While the calculation is running (as indicated by the status frame in the top right corner of the window), you can monitor several quantities (see section 3.9). Once the calculation is finished (11 iterations), view case.dayfile for timing and errors and compare your results with the files in the provided example (TiC/case scf).
39 3.9. THE CASE.SCF FILE 21 For magnetic systems you would run a spin-polarized calculation with the script runsp lapw. The program flow of such a calculation is described in section and the script itself in section The history file case.scf During the SCF cycle the essential data of each iteration are appended to the file case.scf, in our example TiC.scf. For an easier retrieval of certain quantities, the essential lines carry a label of the form :LABEL: which can be used to monitor these quantities during a SCF run. The information is retrieved using the UNIX grep command or using the Utils. analyze menu. While the SCF cycle of TiC is running try to monitor e.g. the total energy (label :ENE) or the charge distance (label :DIS). The calculation has converged, when the convergence criterion is met for three subsequent iterations (compare the charge distance in the example). For a detailed description of the various labels consult section Saving a calculation Before you proceed to another calculation, you should save the results of the SCF-cycle with the save lapw command, which is also described in detail in section This can also be done from the graphical user interface by choosing the Utils. save lapw menu. Save the result to this example under the name TiC scf. You can now improve your calculation and check the convergence of the most important parameters: increase RKMAX and GMAX in case.in1 and case.in2 increase the k-mesh with x kgen choose a different exchange-correlation potential in case.in0 Then just execute another run lapw using Execution run SCF Calculating properties Once the SCF cycle has converged one can calculate various properties like Density of States (DOS), band structure, Optical properties or X-ray spectra. For the calculation of properties (which from now on will be called Tasks ). We strongly encourage the user to utilize the user interface, w2web. This user interface automatically supplies input file templates and shows how to calculate the named properties on a step by step basis Electron density plots Select El. Dens. from the Tasks menu and click on the buttons one by one (see figure 3.6): The total charge density includes the Ti 3s and 3p states and the resulting density around Ti would be very large and dominated by these semicore states. To get a meaningful picture of the chemical bonding effects one must remove these states. Inspection of TiC.scf1 and TiC.scf2 should allow you to select an EMIN value to eliminate the Ti 3s and 3p semicore states.
40 22 CHAPTER 3. QUICK START Figure 3.6: Task Electron Density Plots Recalculate the valence density with EMIN=-1.0 to truncate Ti 3s and 3p (x lapw2). This is only possible, when you still have a valid TiC.vector file on a tetrahedral mesh. Select a plane and plot the density in the (100) plane of TiC. When XCRYSDEN is installed (for details see it will be offered automatically and provides a convenient way to specify a plane and create a colorful plot 3.7. Select 2D-plot Specify a resolution of 100 points (first line) Select a plane by selecting 3 atoms and define these 3 atoms by clicking on them. Choose rectangular parallelogram and enlarge the rectangular selection by 0.5 (for all 4 margins, then update the display) calculate the density and produce a nice contour plot: choose rainbow -colors, activate all display-option buttens, and choose in Ranges a smaller highest rendered value. Finally, use smaller spheres (pipe+ball display model) and thinner bonds (Modify/Ball-Stick-ratio). Alternatively, without XCRYSDEN, edit TiC.in5 and choose the offered template input file. To select the (100) plane for plotting specify the following input: # origin of plot (x,y,z,denominator) # x-end of plot # y-end of plot # x,y,z number of shells # x, y plotting mesh, choose ratio similar to x,y length RHO ANG VAL NODEBUG
41 3.11. CALCULATING PROPERTIES 23 ORTHO For a detailed description of input options consult section Calculate electron density (x lapw5) Plot output (using rhoplot), after the first preview select a range zmin=-0.5 to zmax=2 Figure 3.7: Electron density of TiC in (100) plane using Xcrysden Compare the result with the electron density plotted in the (100) plane (see figure 3.8). The program gnuplot (public domain) must be installed on your computer. For more advanced graphics use your favorite plotting package or specify other options in gnuplot (see rhoplot lapw how gnuplot is called).
42 24 CHAPTER 3. QUICK START Figure 3.8: Electron density of TiC in (100) plane Density of States (DOS) Select Density of States (DOS) from the Tasks menu and click on the buttons one by one: Calculate partial charges (x lapw2 -qtl). (This is only possible, when you still have a valid TiC.vector file on a tetrahedral mesh.) Create TiC.int, either using configure TiC.int or/and by editing the offered template input file. Select: total DOS, Ti-d, Ti-d eg, Ti-d t2g, C-s and C-p-like DOS. TiC EMIN, DE, EMAX, Gauss-broadening 6 NUMBER OF DOS-CASES 0 1 tot (atom,case,description) 1 4 Ti d 1 5 Ti eg 1 6 Ti t2g 2 2 C s 2 3 C p For a detailed description of input options consult section Calculate DOS (x tetra). Preview output using dosplot If you want to use the supplied plotting interface dosplot2 to preview the results, the program gnuplot (public domain) must be installed on your computer. The calculated DOS can be compared with figures 3.9 and Together with the electron density the partial DOS allows you to analyse the chemical bonding (covalency between T i d eg and C p, non-bonding T i d t2g, charge transfer estimates,...)
43 3.11. CALCULATING PROPERTIES 25 Figure 3.9: Density of states of TiC Figure 3.10: Density of states of TiC
44 26 CHAPTER 3. QUICK START X-ray spectra Select X-Ray Spectra from the Tasks menu and click on the buttons one by one: Calculate partial charges (x lapw2 -qtl). This is only possible, when you still have a valid TiC.vector file on a tetrahedral mesh. To reproduce this figure you will have to increase the EMAX value in your TiC.in1 to 2.5 Ry and rerun x lapw1 Edit TiC.inxs; choose the offered template. This template will calculate the L III - spectrum of the first atom (Ti in this example) in the energy range between -2 and 15 ev. For a detailed description of the contents of this input file refer to section Calculate spectra Preview spectra If you want to use the supplied plotting interface specplot to preview the results, the public domain program gnuplot must be installed on your computer. The calculated TiC Ti-L III -spectrum can be compared with figure Figure 3.11: Ti L III spectrum of TiC Bandstructure Select Bandstructure from the Tasks menu and click on the buttons one by one: Create the file TiC.klist band from the template in $WIENROOT/SRC templates/fcc.klist. (To calculate a bandstructure a special k-mesh along high symmetry directions is necessary. For a few crystal structures template files are supplied in the SRC-directory, you can also use XCRYSDEN (save it as xcrysden.klist) to generate a k-mesh or type in your own mesh. Calculate Eigenvalues using the -band switch (which changes lapw1.def such that the k-mesh is read from TiC.klist band and not from TiC.klist) Note: When you want to calculate DOS, charge densities or spectra after this bandstructure, you must first recalculate the TiC.vector file using the tetrahedral k-mesh, because the k-mesh for the band structure plots is not suitable for calculations of such properties.
45 3.11. CALCULATING PROPERTIES 27 Edit TiC.insp: insert the correct Fermi energy (which can be found in the saved scf-file) and specify plotting parameters. For comparison with figure 3.12 select an energy-range from -13 to 8 ev. Calculate Bandstructure (x spaghetti). Preview Bandstructure (needs ghostscript installed). If you want to preview the bandstructure, the program ghostview (public domain) must be installed on your computer. You can compare your calculated bandstructure with figure Figure 3.12: Bandstructure of TiC Bandstructure with band character plotting / full lines Select again Bandstructure from the Tasks menu. We assume that you have already done the steps described in the previous section (generate TiC.klist band and x lapw1 -band). Calculate partial charges (x lapw2 -qtl -band) Note: You have to calculate the partial charges for the new special k-mesh specified above and cannot use the partial charges from the DOS calculation. Edit TiC.insp: insert the correct Fermi energy (same as before) and specify plotting parameters. For band character plotting (see figure 3.13) select line type = dots and jatom=1, jtype=6 and jsize=0.2 (in the last input line) to produce a character plot of the Ti t2g-like character bands. Calculate Bandstructure (x spaghetti) Preview Bandstructure To plot the bandstructure with full lines, calculate the irreducible representations with x irrep and select lines in case.insp. If you have case.irrep* or case.qtl* files from previous runs which do not fit to the present case.output1 file, you may get errors while running spaghetti. In this case remove all case.irrep or case.qtl files. You can compare your results with figure 3.13.
46 28 CHAPTER 3. QUICK START Figure 3.13: Bandstructure of TiC, showing t2g-character bands of Ti in character plotting mode Volume Optimization Select Optimize (V,c/a) from the Execution menu. Setup the shell script optimize.job script using x optimize and volume variations of -10, -5, 0, +5 and +10%. Then run the optimize.job. When the job has finished, you should click on Plot and then preview the energy curve. You should get an energy curve as in figure On the screen you will find the fitting parameters for the equation of states (Murnaghan, Birch-Murnaghan and the EOS2 equation, see sec. 9.12). This information is also written to TiC.outputeos. Figure 3.14: Energy vs. volume curve for TiC
47 3.12. SETTING UP A NEW CASE Setting up a new case In order to setup a new case you need at least the following information: The lattice parameters (in Bohr or Ångstroms) and angles, the lattice type (primitive, face-centered, hexagonal,...) or spacegroup, the position of all equivalent and inequivalent atoms in fractions of the unit cell. Alternatively with the new StructGen you can specify the spacegroup and only the inequivalent positions. The equivalent ones will be generated automatically. Usually this information can be collected from the International Tables of Crystallography once you know the space group, the Wyckoff position and the internal free coordinates Manually setting up a new case Usually for a new case the input is not created by hand, but using some utilities. We recommend the script makestruct lapw which will ask for the required input and create init.struct, which you should copy to case.struct. Alternatively, you can use cif2struct or xyz2struct to convert a cif, txt or xyz file into the WIEN2k case.struct file. Check page 196 for more info on the specific file formats. You can also use the struct file from a similar case as pattern, but note, that the automatic setting of proper R0-values is not guaranteed by that procedure and you should use it only for VERY SIMILAR cases (elements). Change into the lapw subdirectory and proceed as follows: mkdir case new cd case new cp../case old/case old.struct case new.struct Now edit case new.struct (see section 4.3) as necessary (Note: this is a fixed formatted file, so all values must remain at their proper columns). Afterwards generate case new.inst using instgen lapw Setting up a new case using w2web Use the menu Session Mgmt. change session of w2web to create a new session (enter the name of the new session and click on Create ). Then you should also create a new directory and select it.. When you select Execution StructGen, you have several choices: You can just specify the number of non-equivalent atoms and a template file will be created. In StructGen you simply specify the lattice (type or spacegroup), cell parameters and name and positions of atoms. When you save file and clean up the new case.struct file and the case.inst file are created automatically. Alternatively, you can use cif2struct or xyz2struct to convert a cif, txt or xyz file into the WIEN2k case.struct file. Check page 196 for more info on the specific file formats. For more information on the StructGen refer to page 198.
48 30 CHAPTER 3. QUICK START
49 Part II Detailed description of the files and programs of the WIEN2k package 31
50
51 4 File structure and program flow Contents 4.1 Flow of input and output files Input/Output files The case.struct.file The case.scf file Flow of programs (for naming conventions see section 3.1) 4.1 Flow of input and output files Each program is started with (at least) one command line argument, e.g. programx programx.def in which the arguments specifies a filename, in which FORTRAN I/O units are connected to unix filenames. (See examples at specific programs). These def -files are generated automatically when the standard WIEN2k scripts x, init lapw or run lapw are used, but may be tailored by hand for special applications. Using the option x program -d a def-file can be created without running the program. In addition each program reads/writes the following files: case.struct a master input file, which is described below (Section 4.3) case.inx a specific input file, where X labels the program (see def-files for each program in chapter 6). case.outputx an output file The programs of the SCF cycle (see figure 4.1) write the following files: case.scfx a file containing only the most significant output (see description below). program.error error report file, should be empty after successful completion of a program (see chapter 6) 33
52 34 CHAPTER 4. FILES AND PROGRAM FLOW Figure 4.1: Data flow during a SCF cycle (programx.def, case.struct, case.inx, case.outputx and optional files are omitted)
53 4.1. FLOW OF INPUT AND OUTPUT FILES 35 The following tables describe input and output files for the initialization programs nn, sgroup, symmetry, lstart, kgen, dstart (table 4.1), the utility programs tetra, irrep, spaghetti, aim, lapw7, elnes, lapw3, lapw5, xspec, optic, joint, kram, optimize and mini (table 4.2) as well as for a SCF cycle of a non-spin-polarized case (table 4.2). Optional input and output files are used only if present in the respective case subdirectory or requested/generated by an input switch. The connection between FORTRAN units and filenames are defined in the respective programx.def files. The data flow is illustrated in Fig program needs generates necessary optional necessary optional NN nn.def case.outputnn case.struct nn case.struct SGROUP case.struct case.outputsgroup case.struct sgroup SYMMETRY symmetry.def case.outputs case.struct st case.struct case.in2 st case.in2 st LSTART lstart.def case.outputst case.rspup case.struct case.rsp case.rspdn case.inst case.in0 st case.vsp st case.in1 st case.vspdn st case.in2 st case.sigma case.inc st case.inm st case.inm restart KGEN kgen.def case.outputkgen case.struct case.klist case.kgen DSTART dstart.def case.outputd case.struct case.clmsum(up) case.rsp(up) dstart.error case.in0 case.in0 std case.in1 case.in2 Table 4.1: Input and output files of init programs program needs generates necessary optional necessary optional SPAGHETTI spaghetti.def case.qtl case.spaghetti ps case.spaghetti ene case.insp case.outputso case.outputsp case.struct case.irrep case.band.agr case.output1 TETRA tetra.def case.outputt case.int case.qtl case.dos1(2,3) case.kgen case.energy case.dos1ev(1,2,3) case.scf2 LAPW3 lapw3.def case.output3 case.struct case.rho case.in2 case.clmsum case.clmsum LAPW5 lapw5.def case.sigma case.output5 case.rho.oned case.struct case.rho case.in5 case.clmval XSPEC xspec.def case.outputx case.coredens case.inc case.dos1ev case.int case.xspec case.vsp case.txspec case.struct case.m1 case.qtl case.m2 OPTIC optic.def case.outputop case.symmat1 case.struct case.symmat case.symmat2 case.mat diag case.inop case.vsp case.vector JOINT joint.def case.outputjoint case.sigma intra case.injoint case.joint case.intra continued on next page
54 36 CHAPTER 4. FILES AND PROGRAM FLOW case.struct case.kgen case.weight case.symmat case.mat diag KRAM kram.def case.epsilon case.eloss case.inkram case.sigmak case.sumrules case.joint OPTIMIZE case.struct case initial.struct optimize.job case vol xxxxx.struct case c/a xxxxx.struct MINI mini.def case.scf mini case.outputm case.clmsum inter case.inm case.tmpm case.tmpm1 case.finm case.constraint case.struct1 case.scf case.clmhist case.scf mini1 case.struct.min hess.minrestart IRREP case.struct case.outputirrep case.vector case.irrep AIM case.struct case.outputaim case.crit case.clmsum case.surf case.inaim LAPW7 case.struct case.output7 case.abc case.vector case.grid case.in7 case.psink case.vsp QTL case.struct case.outputq case.vector case.qtl case.inq case.vsp Table 4.2: Input and output files of utility programs program needs generates necessary optional necessary optional LAPW0 lapw0.def case.clmup/dn case.output0 case.r2v case.struct case.vrespsum/up/dn case.scf0 case.vcoul case.in0 case.inm case.vsp(up/dn) case.vtotal case.clmsum case.vns(up/dn) ORB orb.def case.energy case.outputorb case.br1orb case.struct case.vorb old case.scforb case.br2orb case.inorb case.vorb case.dmat orb.error case.vsp LAPW1 lapw1.def case.vns case.output1 case.nsh(s) case.struct case.vorb case.scf1 case.nmat only case.in1 case.vector.old case.vector case.vsp case.energy case.klist LAPWSO lapwso.def case.vorb case.vectorso case.struct case.outputso case.inso case.scfso case.in1 case.energyso case.vector case.normso case.vsp case.vns case.energy LAPW2 lapw2.def case.kgen case.output2 case.qtl case.struct case.nsh case.scf2 case.weight case.in2 case.weight case.clmval case.weigh case.vector case.weigh case.help03* case.vsp case.recprlist case.vrespval case.energy case.almblm case.radwf case.dmat LAPWDM lapwdm.def case.inso case.outputdm case.struct case.scfdm case.indm case.dmat case.vector lapwdm.error case.vsp case.weigh case.energy continued on next page
55 4.2. INPUT/OUTPUT FILES 37 SUMPARA case.struct case.scf2p case.outputsum case.clmval case.clmval case.scf2 LCORE lcore.def case.vns case.outputc case.corewf case.struct case.scfc case.inc case.clmcor case.vsp lcore.error After LCORE the case.scfx files are appended to case.scf and the case.clmsum file is renamed to case.clmsum old (see run lapw) MIXER mixer.def case.clmsum old case.outputm case.broyd* case.struct case.clmsc case.scfm case.inm case.clmcor case.clmsum case.clmval case.scf mixer.error case.broyd1 case.broyd2 case.dmat After MIXER the file case.scfm is appended to case.scf, so that after an iteration is completed, the two essential files are case.clmsum and case.scf. Table 4.3: Input and output files of main programs in an SCF cycle 4.2 Description of general input/output files In the following section the content of the (non-trivial) output files is described: case.almblm Contains the A lm, B lm, C lm coefficients of the wavefunctions (generated optional by lapw2). case.band.agr A xmgrace file with the energy bandstructure plot generated by spaghetti. case.broydx Contains the charge density of previous iterations if you use Broyden s method for mixing. They are removed when using save lapw. They should be removed by hand when calculational parameters (RKMAX, kmesh,... ) have been changed, or the calculation crashed due to a too large mixing and are restarted by using a new density generated by dstart. case.clmcor Contains the core charge density (as σ(r) = 4πr 2 ρ(r) and has only a spherical part). In spin-polarized calculations two files case.clmcorup and case.clmcordn are used instead. case.clmsc Contains the semi-core charge density in a 2-window calculation, which is no longer recommended. In spin-polarized calculations two files are used instead: case.clmscup and case.clmscdn. case.clmsum Contains the total charge density in the lattice harmonics representation and as Fourier coefficients. (The LM=0,0 term is given as σ(r) = 4πr 2 ρ(r), the others as r 2 ρ LM (r); suitable for generating electron density plots using lapw5 when the TOT-switch is set, (see section 8.13). In spin-polarized calculations two additional files case.clmup and case.clmdn contain the spin densities. Generated by dstart or mixer. case.clmval Contains the valence charge density as r 2 ρ LM (r); suitable for generating valence electron density plots using lapw5 when the VAL-switch is set, (see 8.13). In spin-polarized calculations two files case.clmvalup and case.clmvaldn are used instead. case.dmatup/dn Contains the density matrix generated by lapw2or lapwdm for LDA+U, OP or onsite-hybrid-dft calculations. case.dosx Contains the density of states (states/ry) and corresponding energy (in Ry at the internal energy scale) generated by tetra. X can be 1-3. Additional files case.dosxev contain the DOS in (states/ev) and the energy in ev with respect to EF. case.help03x Contains eigenvalues and partial charges for atom number X. case.kgen This file contains the indices of the tetrahedra in terms of the list of k-points. It is used in lapw2 (if EFMOD switch in case.in2 is set to TETRA, see 7.7.3) and in tetra. case.klist This file contains a list of k-points in the BZ on a (special k-point) tetrahedral mesh. It is generated in kgen. case.qtl Contains eigenvalues and corresponding partial charges (bandwise) in a form suitable for tetra and band structure plots with band character. The decomposition of these charges is controlled by ISPLIT in case.struct.
56 38 CHAPTER 4. FILES AND PROGRAM FLOW case.radwf Contains the radial basis functions inside spheres (generated optional by lapw2). case.rho Contains the electron densities on a grid in a specified plane generated by lapw5. This file can be used as input for your favorite contour or 3D plotting program. case.rsp Contains the atomic densities generated by lstart. They are used by dstart to generate a first crystalline density (case.clmsum). case.r2v Contains the exchange potential (in the lattice harmonics representation as r 2 V LM (r) and as Fourier coefficients) in a form suitable for plotting with lapw5. case.scf mini Contains the last scf-iteration of each individual time (geometry) step during a structural minimization using mini. Thus this file contains a complete history of properties (energy, forces, positions) during a structural minimization. case.sigma Contains the atomic densities for those states with a P in case.inst. Generated in lstart and used for difference densities in lapw5. case.spaghetti ps A ps file with the energy bandstructure plot generated by spaghetti. case.symmat Contains the momentum matrix elements between bands i,j. Created by optic and used in joint. case.vcoul Contains the Coulomb potential (in the lattice harmonics representation as r 2 V LM (r) and as Fourier coefficients) in a form suitable for plotting with lapw5. case.vorb Contains the orbital potential (in Ry) generated by orb for LDA+U or onsite-hybrid- DFT calculations in form of a (2l+1,2l+1) matrix. case.vtotal Contains the total potential (in the lattice harmonics representation as r 2 V LM (r) and as Fourier coefficients) in a form suitable for plotting with lapw5. case.vector Binary file, contains the eigenvalues and eigenvectors of all k-points calculated in lapw1. In spin-polarized calculations two files case.vectorup and case.vectordn are used instead. lapwso generates case.vectorso. case.energy Contains the eigenvalues of all k-points calculated in lapw1. In spin-polarized calculations two files case.vectorup and case.vectordn are used instead. lapwso generates case.energyso. case.vns Contains the non-spherical part of the total potential V. Inside the sphere the radial coefficients of the lattice harmonics representation are listed (for L greater than 0), while for the interstitial region the reanalyzed Fourier coefficients are given (see equ. (2.10)). In spinpolarized calculations two files case.vnsup and case.vnsdn are used instead. case.vorbup/dn Contains the orbital dependent part of the potential in LDA+U, OP or Hybrid- DFT calculations. Generated in orb, used in lapw1. case.vsp Contains the spherical part of the total potential V stored as r V (thus the first values should be close to 2 Z). In spin-polarized calculations two files case.vspup and case.vspdn are used instead. 4.3 The master input file case.struct The file case.struct defines the structure and is the main input file used in all programs. We provide several examples in the subdirectory example struct file If you are using the Struct Generator from the graphical user interface w2web, or the makestruct lapw utility, you don t have to bother with this file directly, but generate it by specifying the relevant data in a mask. Alternatively, the utilities cif2struct or xyz2struct convert the corresponding cif or xyz files to the WIEN2k-format. However, the description of the fields of this master input file can be found here. Note: If you are changing this file manually, please note that this is a formatted file and the proper column positions of the characters are important! Use REPLACE instead of DELETE and INSERT during edit! Also some parameters are usually element-specifically chosen (R0)
57 4.3. THE CASE.STRUCT.FILE 39 We start the description of this file with an abridged example for rutile TiO 2 (adding line numbers): top of file line # Titaniumdioxide TiO2 (rutile): u= P LATTICE,NONEQUIV. ATOMS 2 2 MODE OF CALC=RELA ATOM -1: X= Y= Z= MULT= 2 ISPLIT= 8 6 ATOM -1: X= Y= Z= Titanium NPT= 781 R0= RMT= Z: LOCAL ROT MATRIX: ATOM -2: X= Y= Z= MULT= 4 ISPLIT= 8 ATOM -2: X= Y= Z= ATOM -2: X= Y= Z= ATOM -2: X= Y= Z= Oxygen NPT= 781 R0= RMT= Z: 8.0 LOCAL ROT MATRIX: SYMMETRY OPERATIONS: bottom of file Interpretive comments on this file are as follows. P all primitive lattices except hexagonal [a sin(γ ) sin(β), a cos(γ ) sin(β), (a cos(β))], [0, b sin(α), b cos(α)], [0, 0, c] F face-centered [a/2, b/2, 0], [a/2, 0, c/2], [0, b/2, c/2] B body-centered [a/2, -b/2, c/2],[a/2, b/2, -c/2], [-a/2, b/2, c/2] CXY C-base-centered (orthorhombic only) [a/2, -b/2, 0], [a/2, b/2, 0], [0, 0, c] CYZ A-base-centered (orthorhombic only) [a, 0, 0], [0, -b/2, c/2], [0, b/2, c/2] CXZ B-base-centered (orthorh. and monoclinic [a sin(γ)/2, a cos(γ)/2, -c/2], [0, b, 0], [a sin(γ)/2, a symmetry) cos(γ)/2, c/2] R rhombohedral [a/ 3/2, -a/2, c/3],[a/ 3/2, a/2, c/3],[-a/ 3, 0, c/3] H hexagonal [ 3a/2, -a/2, 0],[0, a, 0],[0, 0, c] Table 4.4: Lattice type, description and bravais matrix used in WIEN2k. The angle γ is defined via cos(γ) = cos(γ ) sin(α) sin(β) + cos(β) cos(α) line 1: format (A80) title (compound) line 2: format (A4,23X,I3) lattice type, NAT lattice type NAT as defined in table 4.4. For centered monoclinic lattices only the CXZ setting is supported and the monoclinic angle must be gamma. Eventually you have to transform a given spacegroup setting into one supported in WIEN2k (for instance for SG #12 we need (B112/m) or (B2/m11) setting and not (C122/m1) or (C2/m11) (it depends on your starting setting, but the final setting must have a monoclinic angle gamma); for SG #15 we need (B2/b) or one of the alternative B settings, but not one of the many others) using the Bilbao crystallographic server ( structure utilities ; SETSTRU) number of inequivalent atoms in the unit cell
58 40 CHAPTER 4. FILES AND PROGRAM FLOW line 3: format (13X,A4) mode RELA NREL fully relativistic core and scalar relativistic valence non-relativistic calculation line 4: format (6F10.6) a, b, c, α, β, γ a, b, c unit cell parameters (in a.u., 1 a.u. = Å). In face- or body-centered structures the non-primitive (cubic) lattice constant, for rhombohedral (R) lattices the hexagonal lattice constants must be specified. (The following may help you to convert between hexagonal and rhombohedral specifications: a hex = 2cos( π α rhomb )a 2 rhomb c hex = 3 a 2 rhomb 1 3 a2 hex and (for fcc-like lattices) a rhomb = a cubic / 2 α, β, γ angles between unit axis (if omitted, 90 is set as default). Set it only for P and CXZ lattices line 5: format (4X,I4,4X,F10.8,3X,F10.8,3X,F10.8) atom-index, x, y, z atomindex x,y,z running index for inequivalent atoms positive in case of cubic symmetry negative for non-cubic symmetry this is set automatically using symmetry position of atom in internal units, i.e. as positive fractions of unit cell parameters. (0 x 1; the positions in the unit cell are consistent with the convention used in the International Tables of Crystallography 64. In face- (body-) centered structures only one of four (two) atoms must be given, eg. in Fm3m position 8c is specified with 0.25, 0.25, 0.25 and.75, 0.75, 0.75). For R lattice use rhombohedral coordinates. (To convert from hexagonal into rhombohedral coordinates use the auxiliary program hex2rhomb, which can be called at a command-line: X ortho = X hex X rhomb = X ortho line 6: format (15X,I2,17X,I2) multiplicity, isplit multiplicity number of equivalent atoms of this kind isplit this is just an output-option and is used to specify the decomposition of the lm-like charges into irreducible representations, useful for interpretation in case.qtl). This parameter is automatically set by symmetry: 0 no split of l-like charge 1 p-z, (p-x, p-y) e.g.:hcp 2 e-g, t-2g of d-electrons e.g.:cubic 3 d-z2, (d-xy,d-x2y2), (d-xz,dyz) e.g.:hcp 4 combining option 1 and 3 e.g.:hcp 5 all d symmetries separate 6 all p symmetries separate 8 combining option 5 and 6-2 d-z2, d-x2y2, d-xy, (d-xz,d-yz)
59 4.3. THE CASE.STRUCT.FILE split lm like charges (for old telnes, not necessary anymore) 99 calculate cross-terms (for old telnes, not necessary anymore) >>>: line 5 must now be repeated MULT-1 times for the other positions of each equivalent atom according to the Wyckoff position in the International Tables of Crystallography. line 7: format (A10,5X,I5,5X,F10.8,5X,F10.5,5X,F5.2) name of atom, NPT, R0, RMT, Z name of atom NPT R0 RMT Z Use the chemical symbol. Positions 3-10 for further labeling of nonequivalent atoms (use a number in position 3) number of radial mesh points (381 gives a good mesh for LDA calculations, but for GGA twice as many points are recommended; always use an odd number of mesh points!) the radial mesh is given on a logarithmic scale: r(n) = R 0 e [(n 1) DX] first radial mesh point (typically between and , smaller for heavy elements, bigger for light ones; a struct-file generated by w2web will have proper R0 values.) atomic sphere radius (muffin-tin radius), can easily be estimated after running nn (see 6.1) and are set automatically with setrmt lapw see 5.2.7). The following guidelines will be given here: Choose spheres as large as possible as this will save MUCH computer time. But: Use identical radii within a series of calculations (i.e. when you want to compare total energies) therefore consider first how close the atoms may possibly come later on (volume or geometry optimization); do NOT make the spheres too different (even when the geometry would permit it), instead use the largest spheres for f-electron atoms, % smaller ones for d-elements and again % smaller for sp-elements; H is a special case, you may choose it much smaller (e.g. 0.6 and 1.2 for H and C) and systems containing H need a much smaller RKMAX value (3-5) in case.in1. atomic number line 8-10: format (20X,3F10.7) ROTLOC local rotation matrix (always in an orthogonal coordinate system). Transforms the global coordinate system (of the unit cell) into the local at the given atomic site as required by point group symmetry (see in the INPUT-Section of LAPW2). SYMMETRY calculates the point group symmetry and determines ROTLOC automatically. Note, that a proper ROTLOC is required, if the LM values generated by SYMMETRY are used. A more detailed description with several examples is given in the appendix A and sec >>>: lines 5 thru 10 must be repeated for each inequivalent atom line 11: format (I4) nsym number of symmetry operations of space group (see International Tables of Crystallography 64) If nsym is set to zero, the symmetry operations will be generated automatically by SYMMETRY. line 12-14: format (3I2,F10.7) matrix, tau (as listed in the International Tables of Crystallography 64) matrix tau matrix representation of (space group) symmetry operation non-primitive translation vector line 15: format (I8) index of symmetry operation specified above >>>: lines 12 thru 15 must be repeated for all other symmetry operations
60 42 CHAPTER 4. FILES AND PROGRAM FLOW line 16: free format (optional) after a line Precise positions, a list of all atomic positions can follow with full machine precision. These coordinates are written by mixer if one performs a MSR1a structure optimization and they will be used instead of the truncated numbers read above (only if they agree, but not if one modifies them by hand such that they differ more significantly. 4.4 The history file case.scf During the self-consistent field (SCF) cycle the essential data are appended to the file case.scf in order to generate a summary of previous iterations. For an easier retrieval of certain quantities the essential lines are labeled with :LABEL:, which can be used to monitor these quantities during self-consistency as explained below. The most important :LABELs are :ENE :WAR :DIS :FER :GAP :FORxx :FGLxx :FR :DTOxx :CTOxx :NTOxx :QTLxx :EPLxx :EPHxx :EFGxx :ETAxx :RTOxx :VZERO total energy (Ry). If there is a WARNING mentioned, check :WAR contains some warnings indicating that there might be a problem with your calculations. Usually these problems are not fatal, but may influence the accuracy. charge distance between last 2 iterations ( ρ n ρ n 1 dr). Good convergence criterium. Fermi energy (and Fermi-method) energy gap (for insulators). Please note, this value will only be correct, if the VBM/CBM are in your k-mesh. ( Shifted k-meshes do not contain tha Gamma-point and often gaps are at Gamma!!) force on atom xx in mry/bohr (in the local (for each atom) cartesian coordinate system) force on atom xx in mry/bohr (in the global coordinate system of the unit cell (in the same way as the atomic positions are specified)) in MSR1a mode prints information about the remaining size of the forces and whether it will/has switched to MSR1 mode. total difference charge density for atom xx between last 2 iterations total charge in sphere xx (mixed after MIXER) total charge in sphere xx (new (not mixed) from LAPW2+LCORE) partial charges in sphere xx l-like partial charges and mean energies in lower (semicore) energy window for atom xx. Used as energy parameters in case.in1 for next iteration l-like partial charges and mean energies in higher (valence) energy window for atom xx. Used as energy parameters in case.in1 for next iteration Electric field gradient (EFG) V zz for atom xx Asymmetry parameter of EFG for atom xx Density for atom xx at the nucleus (first radial mesh point) Gives the total, Coulomb and xc-potential at z=0 and z=0.5 (meaningfull only for slab calculations) To check to which type of calculation a scf file corresponds use: :POT :LAT :VOL :POSxx :RKM :NEC Exchange-correlation potential used in this calculation Lattice parameters in this calculation Volume of the unit cell Atomic positions for atom xx (as in case.struct) Actual matrix size and resulting RKmax normalization check of electronic charge densities. If a significant amount of electrons is missing, one might have core states, whose charge density is not completely confined within the respective atomic sphere. In such a case the corresponding states should be treated as band states (using LOs). For spin-polarized calculations: :MMTOT Total spin magnetic moment/cell
61 4.5. FLOW OF PROGRAMS 43 :MMIxx :CUPxx :CDNxx :NUPxx :NDNxx :ORBxx :HFFxx Spin magnetic moment of atom xx. Note, that this value depends on RMT. spin-up charge (mixed) in sphere xx spin-dn charge (mixed) in sphere xx spin-up charge (new, from lapw2+lcore) in sphere xx spin-dn charge (new, from lapw2+lcore) in sphere xx Orbital magnetic moment of atom xx (needs SO calculations and LAPWDM). Hyperfine field of atom xx (in kgauss). One can monitor the energy eigenvalues (listed for the first k-point only), the Fermi-energy or the total energy. Often the electronic charges per atom reflect the convergence. Charge transfer between the various atomic spheres is a typical process during the SCF cycles: large oscillations should be avoided by using a smaller mixing parameter; monotonic changes in one direction suggest a larger mixing parameter. In spin-polarized calculations the magnetic moment per atomic site is an additional crucial quantity which could be used as convergence criterion. If a system has electric field gradients and one is interested in that quantity, one should monitor the EFGs, because these are very sensitive quantities. It is best to monitor several quantities, because often one quantity is converged, while another still changes from iteration to iteration. The script run lapw has three different convergence criteria built in, namely the total energy, the atomic forces and the charge distance (see 5.1.3, 5.1.4). We recommend the use of UNIX commands like : grep :ENE case.scf or use Analysis from w2web for monitoring such quantities. You may define an alias for this (see sec. 11.2), and a csh-script grepline lapw is also available to get a quantity from several scf-files simultaneously (sec and 5.3). 4.5 Flow of programs The WIEN2k package consists of several independent programs which are linked via C-SHELL SCRIPTS described below. The flow and usage of the different programs is illustrated in the following diagram (Fig. 4.2): The initialization consists of running a series of small auxiliary programs, which generates the inputs for the main programs. One starts in the respective case/ subdirectory and defines the structure in case.struct (see 4.3). The initialization can be invoked by the script init lapw (see sec. 3.7 and 5.1.3), and consists of running: SETRMT a perl-program which helps to select proper RMT values NN a program which lists the nearest neighbor distances up to a specified limit (defined by a distance factor f) and thus helps to determine the atomic sphere radii. In addition it is a very useful additional check of your case.struct file (equivalency of atoms) SGROUP determines the spacegroup of the structure defined in your case.struct file. SYMMETRY generates from a raw case.struct file the space group symmetry operations, determines the point group of the individual atomic sites, generates the LM expansion for the lattice harmonics and determines the local rotation matrices. LSTART generates free atomic densities and determines how the different orbitals are treated in the band structure calculations (i.e. as core or band states, with or without local orbitals,... ). KGEN generates a k-mesh in the irreducible part of the BZ. DSTART generates a starting density for the scf cycle by a superposition of atomic densities generated in LSTART.
62 44 CHAPTER 4. FILES AND PROGRAM FLOW NN check for overlap. spheres SGROUP struct files SYMMETRY struct files input files LSTART atomic calculation Hψ nl = E nl ψ nl atomic densities input files KGEN DSTART superposition of atomic densities ρ k mesh generation ORB LDA+U, OP potentials LAPW0 2 V C = 8πρ Poisson V XC ( ρ) LDA V= V C + V XC V LAPW1 2 + V ψ k = E k ψ k V MT LCORE atomic calculation Hψ nl = E nl ψ nl E k ψ k LAPWSO ρ core E core add spin orbit interaction LAPW2 ρ val = Σ ψ k ψ k E k < EF ρ val ρ old LAPWDM calculates density matrix MIXER ρ new = ρold ( ρ val + ρ core ) ρ new STOP yes converged? no Figure 4.2: Program flow in WIEN2k
63 4.5. FLOW OF PROGRAMS 45 Then a self-consistency cycle is initiated and repeated until convergence criteria are met (see 3.8 and 5.1.4). This cycle can be invoked with a script run lapw, and Core, semi-core and valence states In many cases it is desirable to distinguish three types of electronic states, namely core, semi-core and valence states. For example titanium has core (1s, 2s, 2p), semi-core (3s, 3p) and valence (3d, 4s, 4p) states. In our definition core states are only those whose charge is entirely confined inside the corresponding atomic sphere. They are deep in energy, e.g., more than 7-10 Ry below the Fermi energy. Semi-core states lie high enough in energy (between about 1 and 7 Ry below the Fermi energy), so that their charge is no longer completely confined inside the atomic sphere, but has a few percent outside the sphere. Valence states are energetically the highest (occupied) states and always have a significant amount of charge outside the spheres. The energy cut-off specified in lstart during init lapw (usually -6.0 Ry) defines the separation into core- and band-states (the latter contain both, semicore and valence). If a system has atoms with semi-core states, then the best way to treat them is with local orbitals, an extension of the usual LAPW basis. An input for such a basis set will be generated automatically. (Additional LOs can also be used for valence states which have a strong variation of their radial wavefunctions with energy (e.g. d states in TM compounds) to improve the quality of the basis set, i.e. to go beyond the simple linearization) Spin-polarized calculation For magnetic systems spin-polarized calculations can be performed. In such a case some steps are done for spin-up and spin-down electrons separately and the script runsp lapw consists of the following steps: LAPW0 (POTENTIAL) generates potential from density LAPW1 -up (BANDS) calculates valence bands for spin-up electrons LAPW1 -dn (BANDS) calculates valence bands for spin-down electrons LAPW2 -up (RHO) computes valence densities for spin-up electrons LAPW2 -dn (RHO) computes valence densities for spin-down electrons LCORE -up computes core states and densities for spin-up electrons LCORE -dn computes core states and densities for spin-down electrons MIXER mixes input and output densities The use of spin-polarized calculations is illustrated for fcc Ni (section 10.2), one of the test cases provided in the WIEN2k package Fixed-spin-moment (FSM) calculations Using the script runfsm lapw -m XX it is possible to constrain the total spin magnetic moment per unit cell to a fixed value XX and thus force a particular ferromagnetic solution (which may not correspond to the equillibrium). This is particularly useful for systems with several metastable
64 46 CHAPTER 4. FILES AND PROGRAM FLOW (non-) magnetic solutions, where conventional spin-polarized calculation would not converge or the solution may depend on the starting density. Additional SO-interaction is not supported. Please note, that once runfsm lapw has finished, only case.vectordn is ok, but case.vectorup is NOT the proper up-spin vector and MUST NOT be used for the calculations of QTLs (and DOS). It must be regenerated by x lapw1 -up (see also the comments for iterative diagonalization in section ) Antiferromagnetic (AFM) calculations Several considerations are necessary, when you want to perform an AFM calculation. Please have also a look into $WIENROOT/SRC afminput/afminput test. You must construct a unit cell which allows for the desired AF ordering. For example for bcc Cr you must select a P lattice and specify both atoms, Cr1 at (0,0,0) and Cr2 at (.5,.5,.5), corresponding to a CsCl structure. Note, that it is important to label the two Cr atoms with Cr1 and Cr2, since only then the symmetry programs can detect that those atoms should be different (although they have the same Z). If sgroup has interchanged some axis, try to undo these changes, since afminput may not properly find the correct symmetry operations in such a case. When you generate case.inst you must specify the correct magnetic order and flip the spin of the AF atoms (i.e. invert the spin up and dn occupation numbers). In addition you should set a zero moment (identical spin up and dn occupations) for all non-magnetic atoms. This can be done conveniently using instgen lapw -ask or during initialization using w2web. Now you can run either a normal spinpolarized initialization (without AFM option) and runsp lapw or: Create a struct file of the non-magnetic (or ferro-magnetic) supergroup (run init lapw up to lstart). Name it case.struct supergroup. (For example for bcc Cr, this would be a struct file with the ordinary cubic lattice parameters, B type lattice and just one Cr at (0,0,0).) Run init lapw. At the end AFMINPUT creates an input file for the program CLMCOPY. Depending on the presence of case.struct supergroup and the specific symmetry it may/may not ask you to supply a symmetry operation/nonprimitive translation (see Sect Run runafm lapw. This script calls LAPW1 and LAPW2 only for spin-up but the corresponding spin-dn density is created by CLMCOPY according to the rules defined during initialization. This reduces the required cpu time by a factor of 2 (and in addition the scf cycle is much more stable). It is highly recommended that you save your work (save lapw) and check the results by continuing with a regular runsp lapw. If nothing changes (E-tot and other properties), then you are ok, otherwise make sure the scf calculation is well converged (-cc or better). Eventually the system may not want to be antiferromagnetic (but for instance it is ferrimagnetic!). runafm lapw saves you more than a factor of 2 in in computer time, since only spin-up is calculated and in addition the scf-convergence may be MUCH faster. It works also with LDA+U (case.dmatup/dn are also copied), but does NOT work with Hybrid-DFT nor spin-orbit coupling, since this requires the presence of both vector files in the LAPWSO step Spin-orbit interaction You can add spin-orbit interaction in LAPWSO (called directly after LAPW1) using a secondvariational method with the scalar-relativistic orbitals (from LAPW1) as basis. The number of
65 4.5. FLOW OF PROGRAMS 47 eigenvalues will double since SO couples spin-up and dn states, so they are no longer separable. In addition, LOs with a p 1/2 radial basis can be added. (Kunes et al. 2001) To assist with the generation of the necessary input files and possible changes in symmetry, a script initso lapw exists. For non-spinpolarized cases nothing particular must be taken into account and SO can be easily applied by running run lapw -so. It will automatically use the complex version of LAPW2. However, for spin-polarized cases, the SO interaction may change (lower) the symmetry depending on how you choose the direction of magnetization and care must be taken to get a proper setup. initso lapw together with symmetso generates the proper symmetry. Just a few hints what can happen: Suppose you have a cubic system and put the magnetization along [001]. This will create a tetragonal symmetry (and you can temporarely tell this to the initialization programs by changing the respective lattice parameter c to a tetragonal system). If you put the magnetization along [111], this creates most likely a rhombohedral (or hexagonal) symmetry. (Try to visualize this for a fcc lattice, XCRYSDEN is very useful for this purpose). Symmetry operations can be classified into operations which invert the magnetization,others which leave it unchanged and some which do some arbitrary rotation. The program symmetso (part of initso lapw) sorts these operations in the proper way. If you don t have inversion symmetry in the original structure, you must not add inversion in KGEN. The recommended way to include SO in the calculations is to run a regular scf calculation first, save the results, initialize SO and run another scf cycle including SO: run[sp] lapw save lapw case nrel initso lapw run[sp] lapw -so For spin-polarized systems you may want to add the -dm switch to calculate also the orbital magnetic moment Orbital potentials In WIEN2kit is possible to go beyond standard LDA (GGA) and include orbital dependent potentials in methods like LDA+U or the Orbital-Polarization, which are very useful for strongly correlated systems. To use these features you need to create input-files for LAPWDM and ORB (case.indm, case.inorb). also choose the proper U and J values for them. Once this is done, you can include this using the -orb switch. The density matrix (case.dmatup/dn) will be calculated in lapw2 (or in lapwdm when spin-orbit is also used), it will be mixed in mixer (consistently with the regular charge density) and the orbital dependent potentials will be calculated on orb (after lapw0). Note, you must run spin-polarized in order to use orbital potentials. runsp lapw -orb [-so]
66 48 CHAPTER 4. FILES AND PROGRAM FLOW If you want to force a non-magnetic solution you can constrain the spin-polarization to zero using runsp c lapw. Without SO, case.vorbup/dn will be considered in LAPW1(c). With SO, it will be applied in LAPWSO (and allows coupling of nondiagonal spin-terms) Onsite-exact-exchange and hybrid functionals for correlated electrons In WIEN2k, it is also possible to go beyond standard LDA (GGA) and include onsite-exactexchange (i.e., Hartree-Fock), which is very useful for strongly correlated systems, since such calculations are computationally nearly as cheap as standard DFT (or LDA+U). The onsite-exactexchange/hybrid methods apply HF only inside the atomic spheres and only to one particular orbital. Thus you can use it only for localized electrons (see Tran et al for details). Onsiteexact-exchange will NOT improve gaps in sp-semiconductors. For these systems you have to use full hybrid-dft (see Sec.4.5.8) or the mbj potential (see Sec.4.5.9) The one-parameter onsite hybrid functionals have the general following form: Exc onsite hybrid [ρ] = Exc SL [ρ] + α ( Ex HF [Ψ corr ] Ex SL [ρ corr ] ) where Exc SL is the underlying semilocal (SL) functional. The following semilocal functionals can be used in E onsite hybrid xc : LDA: XC LDA (indxc=5) in case.in0. mode=hybr and fraction=α in case.ineece PBE: XC PBE (indxc=13) in case.in0. mode=hybr and fraction=α in case.ineece WC: XC WC (indxc=11) in case.in0. mode=hybr and fraction=α in case.ineece PBEsol: XC PBESOL (indxc=19) in case.in0. mode=hybr and fraction=α in case.ineece TPSS: XC TPSS (indxc=27) in case.in0. mode=hybr and fraction=α in case.ineece The three-parameter onsite hybrid functionals B3PW91 and B3LYP are also available. These two functionals were proposed with the fraction of exact exchange α = 0.2, however other values for α can be chosen as well. B3PW91: EX B3PW91 EC B3PW91 VX B3PW91 VC B3PW91 (indxc=18) in case.in0. mode = HYBR and fraction = 0.2 in case.ineece. E onsite B3PW91 xc [ρ] = Exc LDA [ρ] ( Ex HF [Ψ corr ] Ex LDA [ρ corr ] ) ( Ex B88 [ρ] Ex LDA [ρ] ) ( Ec PW91 [ρ] Ec LDA [ρ] ) where Ec LDA = Ec PW92. B3LYP: XC B3LYP (indxc=47) in case.in0. case.ineece. E onsite B3LYP where E LDA c xc [ρ] = Exc LDA = E VWN5 c. Onsite Hartree-Fock calculations, i.e., mode = HYBR and fraction = 0.2 in [ρ] ( Ex HF [Ψ corr ] Ex LDA [ρ corr ] ) ( Ex B88 [ρ] Ex LDA [ρ] ) ( Ec LYP [ρ] Ec LDA [ρ] ) Exc onsite HF [ρ] = E SL xc [ρ] + Ex HF are also possible with the following semilocal functionals. [Ψ corr ] E SL xc [ρ corr ]
67 4.5. FLOW OF PROGRAMS 49 LDA: XC LDA (indxc=5) in case.in0. mode=eece and fraction=1 in case.ineece PBE: XC PBE (indxc=13) in case.in0. mode=eece and fraction=1 in case.ineece WC: XC WC (indxc=11) in case.in0. mode=eece and fraction=1 in case.ineece PBEsol: XC PBESOL (indxc=19) in case.in0. mode=eece and fraction=1 in case.ineece TPSS: XC TPSS (indxc=27) in case.in0. mode=eece and fraction=1 in case.ineece In addition to the input files which are necessary for an usual LDA or GGA calculation, the input file case.ineece is necessary to start a calculation. which type of functional you want to use. A sample input for calculations with exact exchange is given below top of file: case.ineece emin, natorb st atom index, nlorb, lorb nd atom index, nlorb, lorb HYBR HYBR / EECE mode 0.25 fraction of exact exchange bottom of file Interpretive comments on this file are as follows: line 1: free format emin, natom emin natorb lower energy cutoff, to be selected so that the energy of correlated states is larger than emin number of atoms for which the exact exchange is calculated line 2: free format iatom(i), nlorb(i), (lorb(li,i), li=1,nlorb(i)) iatom nlorb lorb index of atom in struct file number of orbital moments for which exact exchange shall be calculated orbital numbers (repeated nlorb-times) 2 nd line repeated natorb-times line 3: free format mode HYBR EECE means that LDA/GGA exchange will be replaced by exact exchange means that LDA/GGA exchange-correlation will be replaced by exact exchange line 4: free format alpha This is the fraction of Hartree-Fock exchange (between 0 and 1) As with LDA+U, hybrid functionals can be used only for spin-polarized calculations (runsp lapw with the switch -eece). runsp lapw will internally call runeece lapw, which will create all necessary additional input files (it requires a case.in0 file including the optional IFFT line as generated by init lapw): case.indm (case.indmc), case.inorb, case.in0eece, case.in2eece (case.in2ceece) and once this is done, calculates in a series of lapw2/lapwdm/lapw0/orb calculations the corresponding orbital dependent potentials.
68 50 CHAPTER 4. FILES AND PROGRAM FLOW runsp lapw -eece [-so] Unscreened and screened hybrid functionals ( hf -module) The onsite exact-exchange/hybrid functionals from can be applied only to localized electrons (typically 3d or 4f), but lead to cheap calculations. In WIEN2k, it is also possible to apply hybrid (and Hartree-Fock) functionals to all electrons, however this leads to calculations which are one or two orders of magnitude more expensive. Hybrid functionals are usually more accurate than the semilocal functionals for the electronic properties of semiconductors and insulators. They also give accurate results for strongly correlated systems like NiO. In hybrid functionals a fraction α of semilocal (SL) exchange is replaced by Hartree-Fock (HF) exchange: ). E hybrid xc = Exc SL + α ( Ex HF E SL x Hybrid functionals can also be constructed by considering only the short-range part of Ex HF and, which leads to the so-called screened hybrid functionals. In WIEN2k, the unscreened and E SL x screened hybrid functionals are implemented using the second-variational procedure (Tran and Blaha 2011). A few important points should be noted: Both, k-point and MPI parallelizations can be used (simultaneously or only one of them). As usual, the k-point parallelization is over the k-points in the irreducible Brillouin zone. The MPI parallelization is implemented in two subroutines which calculate the Hamiltonian and HF exchange energy, the latter being used only if option -nonself is set (see below). In the subroutine for the Hamiltonian, two separate loops are parallelized with MPI. The first loop is over the number of occupied bands and the second is over the total number of atoms in the unit cell ( NAT*MULT ). Note, however, that when option -diaghf is set (see below), the second loop is not executed. The same is done inside the subroutine for the HF exchange energy, the only difference being that the second loop is over the inequivalent atoms only ( NAT ). This has to be kept in mind, when you specify the number of MPI-jobs (it does not make sense for a cell with 2 atoms to MPI-parallelize with 64 cores). Due to the orbital-dependency of the HF potential, the files case.vectorhf, case.energyhf and case.weighhf are also saved when save lapw is executed. If you restart a calculation without case.vectorhf, then, for the first iteration, it will be generated from the semilocal potential (lapw1), and therefore the number of scf iterations to reach convergence will be larger. It is not possible to use spin-orbit coupling (-so) with hybrid functionals. case.vectorhf contains the orbitals for all k-points in the full Brillouin zone (while for case.vector it is only in the irreducible Brillouin zone). The available functionals Among the semilocal functionals Exc SL available in WIEN2k, only a few of them can be used in Exc hybrid (both in unscreened and screened modes). The functionals are the following (case.in0 grr is for the exchange part Ex SL ): LDA: XC LDA (indxc=5) in case.in0 and EX SLDA VX SLDA (indxc=51) in case.in0 grr PBE: XC PBE (indxc=13) in case.in0 and EX SPBE VX SPBE (indxc=52) in case.in0 grr. The functionals PBE0 and YS-PBE0 (similar to HSE06) correspond to α = 0.25 in case.inhf (see 7.4). WC: XC WC (indxc=11) in case.in0 and EX SWC VX SWC (indxc=53) in case.in0 grr PBEsol: XC PBESOL (indxc=19) in case.in0 and EX SPBESOL VX SPBESOL (indxc=54) in case.in0 grr
69 4.5. FLOW OF PROGRAMS 51 BPW91: EX B88 VX B88 EC PW91 VC PW91 (indxc=17) in case.in0 and EX SB88 VX SB88 (indxc=55) in case.in0 grr. (this is not B3PW91). BLYP: EX B88 VX B88 EC LYP VC LYP (indxc=24) in case.in0 and EX SB88 VX SB88 (indxc=55) in case.in0 grr. (this is not B3LYP). In addition, calculations with the well-known B3PW91 and B3LYP (with VWN5) unscreened hybrid functionals (see for the functionals form) can also be done: B3PW91: XC B3PW91 (indxc=18) in case.in0, EX SLDA VX SLDA (indxc=51) in case.in0 grr and α = 0.2 in case.inhf B3LYP: XC B3LYP (indxc=47) in case.in0, EX SLDA VX SLDA (indxc=51) in case.in0 grr and α = 0.2 in case.inhf Hartree-Fock calculations (without correlation) are also possible: HF: EX LDA VX LDA (indxc=6) in case.in0, EX SLDA VX SLDA (indxc=51) in case.in0 grr and α = 1 in case.inhf Flow in run lapw -hf The flow of programs during a scf iteration when executing run lapw -hf is the following (nonspin-polarized and real case): x lapw0 -grr (semilocal exchange) x lapw0 (semilocal exchange-correlation) x lapw1 (semilocal orbitals) x lapw2 (semilocal bands) mv case.vectorhf case.vectorhf old x hf (hybrid orbitals) cp case.klist fbz case.klist, cp case.kgen fbz case.kgen x lapw2 -hf (hybrid electron density and bands) cp case.klist ibz case.klist, cp case.kgen ibz case.kgen x lcore x mixer Self-consistent calculation The steps to perform a calculation with hybrid functionals are the following: Do a calculation with the underlying semilocal functional Exc SL mandatory). save the semilocal calculation. (recommended but not The next steps can be done conveniently using init hf lapw [-up]: create case.inhf (cp $WIENROOT/SRC templates/template.inhf case.inhf). While there are (more or less) reasonable default values for most parameters, you must set nband manually. Set nband to at least the number of occupied bands plus one. Larger values are more accurate, but be aware that computing time scales as nband 2. The value of nband which leads to a converged result will strongly depend on the studied system and property (e.g., much higher for EFG than for band gap or lattice constant). create case.in0 grr (cp case.in0 case.in0 grr), this file contains:
70 52 CHAPTER 4. FILES AND PROGRAM FLOW a screened exhccange functional (EX SLDA,... or indxc=51, 52, 53, 54 or 55) for the exchange functional (see above) R2V option (instead of NR2V ) such that the exchange potential is written to case.r2v grr KXC (instead of TOT ) such that αex SL is printed in case.scf0 grr (and case.scf) under the label :AEXSL In case.inc the print switch has to be 1 for all atoms such that the core orbitals are printed in case.corewf (you don t have to set this manually, the script run lapw will do it automatically when -hf is specified). if nband is large, you may have to edit case.in1 and set EMAX to a higher value (e.g., 5 Ry). Execute run kgenhf lapw. This generates case.klist fbz, case.kgen fbz, case.klist ibz, case.kgen ibz and case.outputkgenhf. One must use identical k-meshes and shifts for IBZ and FBZ. Note that the k-parallelization is done over the k-points specified in case.klist ibz (irreducible Brillouin zone). All these steps above can be conveniently performed using the script init hf lapw. Once the initializations has been done, execute run lapw (or runsp lapw) with the switch -hf: run(sp) lapw -hf... Neglect of the nondiagonal terms If only the eigenvalues are wanted, you may use the switch -diaghf. By using this switch, only the diagonal elements of the 2nd variational Hamiltonian matrix are calculated (the non-diagonal elements are set to zero). This leads to a much faster calculation of the eigenvalues, while keeping a very good accuracy (Tran 2012). However, the orbitals will not be modified, therefore running the calculation for more than one iteration is useless (the result will not change except for metallic systems). This option is not recommended for systems which are described as metallic with the semilocal functional or for difficult systems (e.g., NiO, see Tran 2012). It is important to be aware that with this option, the total energy (:ENE in case.scf) is nonsense unless the option -nonself (see below) was also used. After having done and saved a well converged calculation with the semilocal functional, the setting up of such a calculation is the same as for a self-consistent calculation (see above), but then run(sp) lapw is executed with -diaghf (-hf and -i 1 will be set automatically): run(sp) lapw -diaghf... Using a reduced k-mesh for the HF potential In order to reduce the computational time for the calculation of the HF potential, the internal loop over the k-points can be reduced to a subset of k-points. For instance, for a calculation with a k-mesh, the reduced k-mesh for the HF potential can be one of the following: 6 6 6, 4 4 4, 3 3 3, or This option, which should be used only in the case of screened exchange (see Paier et al. 2006), is particularly interesting for total energy calculations. Obviously, choosing such a reduced k-mesh is an approximation which needs to be tested. The setting up of such a calculation is the same as for a self-consistent calculation (see above), but with the switch -redklist when executing run kgenhf lapw (to create also case.klist rfbz): and run(sp) lapw: run kgenhf lapw -redklist run(sp) lapw -hf -redklist...
71 4.5. FLOW OF PROGRAMS 53 Non-self-consistent calculation of the total energy for hybrid functionals It is possible to calculate the total energy non-self-consistently, i.e., by plugging the orbitals obtained from a calculation with the underlying semilocal functional Exc SL into the total-energy hybrid functional. By doing so, the 2nd variational Hamiltonian is not calculated and therefore the computational time will be reduced. After having done and saved a well converged calculation with the semilocal functional, the setting up of a non-self-consistent calculation is the same as for a self-consistent calculation (see above), but with the additional switch -nonself (-hf and -i 1 will be set automatically) that has to be used in run(sp) lapw : run(sp) lapw -nonself... This option can be particularly interesting for the calculation of the lattice constant, which depends mainly on the functional, but very little on the orbitals plugged into the functional. It can be used simultaneously with the option -diaghf (see above). Starting a calculation from another k-mesh Due to the orbital-dependence of the HF potential, it is not straightforward to start directly a calculation with a potential generated from a previous calculation with another k-mesh. However, due to the high cost of a hybrid calculation, it is desirable to have this possibility in order to reduce the number of iterations during the scf procedure. This option is also useful if a vector file on a very dense k-mesh is needed, e.g. for optics or transport properties (BoltzTraP), while using such a k-mesh for a full self-consistent calculation would not be necessary (and would be too expensive). In this case you want to do only one iteration (-i 1). The procedure is the following: Do the calculation with the first k-mesh and save it when it is finished (do not execute clean lapw since case.vectorhf should be present). cp case.klist fbz case.klist fbz old cp case.klist rfbz case.klist rfbz old (if the option -redklist is also used) Execute run kgenhf lapw to create the files for the new k-mesh. Run the HF calculation with -newklist: run(sp) lapw -hf -newklist (-i 1)... This option can be used simultaneously with -redklist but not with -diaghf (see above). Band structure plotting In order to make a plot of the band structure with hybrid functionals, it is more convenient to use the program run bandplothf lapw. After the self-consistent calculation is finished and saved (do not execute clean lapw since case.vectorhf must be present), do the following steps: Create case.klist band. Execute run bandplothf lapw with one or several of the following flags that were also used during the self-consistent calculation: -up/dn, -diaghf, -redklist and -in1orig. Note that a parallel calculation of the band structure (with -p) can be done even if the scf calculation was not done in parallel (but you still need a file.machines). You can also use -qtl to calculate the partial charges for band character plotting. Create case.insp.
72 54 CHAPTER 4. FILES AND PROGRAM FLOW Execute x spaghetti with the switch -hf. First, run bandplothf lapw calculates the semilocal orbitals (x lapw1 -band) for the k-points in case.klist band. Then, the hybrid eigenvalues at these k-points are calculated (x hf -band). If -qtl is used, then the partial charges will be calculated (x lapw2 -band -qtl). Density of states The calculation of the DOS is the same as for the semilocal functionals, but using the additional flag -hf when executing lapw2 for the partial charges (x lapw2 -qtl -hf) and tetra for the DOS (x tetra -hf) modified Becke-Johnson potential (mbj) for band gaps The modified Becke-Johnson exchange potential + LDA-correlation (Tran and Blaha 2009) allows the calculation of band gaps with an accuracy similar to very expensive GW calculations. It is a semilocal approximation to an atomic exact-exchange potential and a screening term. This is just a XC-potential, not a XC-energy functional, thus E xc is taken from LSDA and the forces cannot be used with this option. We recommend the following steps to perform a mbj calculation (the purpose of the first five steps is just only to create the starting case.r2v and case.vresp files): run a regular initialization and SCF calculation using LDA or PBE (it does not matter at all which functional you choose). init mbj lapw. This performs automatically the following steps: create case.inm vresp (cp $WIENROOT/SRC templates/template.inm vresp case.inm vresp. edit case.in0 and set R2V option (instead of NR2V ) such that the XC potential is written in case.r2v. run one more iteration (use run lapw -NI -i 1) to generate the required case.r2v and case.vresp files. save the LDA (or PBE) calculation. run init mbj lapw again. The second call (once case.inm vresp is present) will do the following steps: edit case.in0 and change the functional to option XC MBJ (indxc=28) (this is mbj). cp case.in0 case.in0 grr and choose EX GRR VX GRR (indxc=50) in case.in0 grr. This option will calculate the average of ρ/ρ over the unit cell. (The presence of case.in0 grr will be detected during the SCF procedure and lapw0 will be called twice, first with the input file case.in0 grr, then with case.in0.) select a specific mbj parametrization (see below) and creates the corresponding file case.in0abp. Eventually, edit case.inm and choose the PRATT mixing scheme. run the mbj SCF calculation. It could well be that the default mixing scheme leads to convergence problems (this is what we have observed in many cases). The reason is that the mbj potential also depends on the kinetic energy density which is not mixed in mixer. If such a convergence problem appears, you have to use the PRATT mixing. The PRATT mixing can be slow, lead to oscillations or even lead to divergence. Thus, first you should use a smaller mixing factor (eg. 0.2 or 0.1) and later (when the calculation approaches convergence) increase it to about 0.40 to make sure that your calculation
73 4.5. FLOW OF PROGRAMS 55 did not stop at a false (pseudo) convergence. In most cases it is also possible to switch back to MSR1 after some initial (typical 5-10) scf-cycles. The mbj potential uses an average of ρ/ρ over the unit cell. This does not make sense for surfaces or molecules. In such cases, run a similar bulk structure first, then cp case bulk.grr to case.grr and remove case.in0 grr. This runs mbj with a fixed value of c. If you want to use other mbj parameters than those defined in (Tran and Blaha 2009), eg. the optimized values of (Koller et al. 2012) you can define them during init mbj lapw or directly in case.in0abp. Put 3 values A, B, e (default=-0.012, 1.023, 0.5), which determines the parameter c in mbj according to eq. 7 or Table II. in (Koller et al. 2012) DFT-D3 for dispersion energy. run(sp) lapw has to be executed with the -dftd3 switch: run(sp) lapw -dftd3 The user can either create the input file case.indftd3 (described in Sec ) by hand or let run(sp) lapw copy the default one from $WIENROOT/SRC templates/. The dftd3 package requires the file case.poscar (or case.xyz if periodic boundary conditions are switched off) created by the utility program struct2poscar, which is run automatically by run(sp) lapw. The DFT-D3 method contains parameters which are specific to the exchange-correlation functional to which the dispersion energy is added. The functionals available in WIEN2k for which such parameters are available are the GGAs PBE, PBEsol, revpbe, RPBE, and BLYP, the MGGA TPSS, the GGA-hybrids PBE0, B3LYP, B3PW91 and HSE06 (corresponding to YS-PBE0 in WIEN2k) and the MGGA-hybrids TPSSh and TPSS0. More detailed informations on the DFT-D3 method and available options are given in Sec. 7.2 and in the file man.pdf included in the dftd3 TAR file.
74 56 CHAPTER 4. FILES AND PROGRAM FLOW
75 5 Shell scripts for running programs Contents 5.1 Job control Utility scripts Structure optimization Phonon calculations Parallel Execution Chemical shift NMR calculations Wannier functions (wien2wannier) Spontaneous Polarization, Piezoelectricity and Born Charges (BerryPI) Getting on-line help Interface scripts Job control (c-shell scripts) In order to run WIEN2k several c-shell scripts are provided which link the individual programs to specific tasks. All available (user-callable) commands have the ending lapw so you can easily get a list of all commands using ls $WIENROOT/ lapw in the directory of the WIEN2k executables. (Note: all of the more important commands have a link to a short name omitting lapw.) All these commands have at least one option, -h, which will print a small help indicating purpose and usage of this command Main execution script (x lapw) The main WIEN2kscript, x lapw or x, executes a single WIEN2kprogram. First it creates the corresponding program.def-file, where the connection between Fortran I/O-units and filenames are defined. One can modify its functionality with several switches, modifying file definitions in case of spin-polarized or complex calculations or tailoring special behaviour. All options are listed with the help switch x -h or x lapw -h With some of the options the corresponding input files may be changed temporarely, but are set back to the original state upon completion. 57
76 58 CHAPTER 5. SHELL SCRIPTS USAGE: x PROGRAMNAME [flags] PURPOSE:runs WIEN executables: afminput,aim,arrows,broadening,cif2struct, clmaddsub,clmcopy,clminter,convham,conv2prim,dftd3,dipan,dmftproj, dstart,eosfit,eosfit6,filtvec,findbands,fleur2wien,hex2rhomb,hf, initxspec,irrep,joint,joinvec,kgen,kram,lapw0,lapw1,lapw2, lapw3,lapw5,lapw7,lapwdm,lapwso,lcore,lorentz,lstart,mini,mixer,nn, optimize,orb,pairhess,plane,rhomb_in5,sgroup,shifteig,spaghetti, struct2cif,struct2poscar,struct_afm_check,sumpara,supercell,symmetry, symmetso,telnes3,tetra,txspec,wannier90,w2w,w2waddsp,wplot,xspec FLAGS: -f FILEHEAD -> FILEHEAD for path of struct & input-files -t/-t -> suppress output of running time -h/-h -> help -d -> create only the def-file -up -> runs up-spin -dn -> runs dn-spin -du -> runs up/dn-crossterm -sc -> runs semicore calculation -c -> complex calculation (no inversion symmetry present) -p -> run lapw0/1/2/hf/so/dm/optic/dstart in parallel (needs.machines or.processes file) -scratch dir/ ->defines (and makes) $SCRATCH variable -grr -> lapw0 for mbj or hf (using $file.in0_grr) -eece -> for hybrid-functionals (lapw0,lapw2,mixer,orb,sumpara) -band -> for lapw1/2/hf bandstructures: uses *klist_band -orb -> runs lapw1 with LDA+U/OP or B-ext correction, mixer with dmat -it -> runs lapw1 with iterative diagonalization -nohinv -> runs lapw1 with iterative diag. without Hinv -nohinv0 -> runs lapw1 with iterative diag. writing new Hinv -nohns-> runs lapw1 without HNS -nmat_only-> runs lapw1 and yields only the matrixsize -nmr -> runs lapw1 in NMR mode -in1orig -> runs lapw2 but does not modify case.in1 -emin X -> runs lapw2 with EMIN=X (in bin9_blaha.in2) -all X Y -> runs lapw2 with ALL and E-window X-Y (in bin9_blaha.in2) -qtl -> runs lapw2 and calculates QTL -alm -> runs lapw2 and calculates ALM,BLM -almd -> runs lapw2 and calculates ALM,BLM in lapw2 for DMFT (Aichhorn) -qdmft -> runs lapw2 and calculates charges including DMFT (Aichhorn) -help_files -> runs lapw2 and creates case.helpxx files -vresp-> runs lapw2 and creates case.vrespval (for TAU/meta-GGA) -fermi-> runs lapw2 with FERMI switch -efg -> runs lapw2 with EFG switch -so ->runs lapw2/optic/spaghetti with def-file for spin-orbit calc. -hf -> runs lapw2 with Hartree-Fock/hybrid vectors -diaghf -> calculates only the diagonal elements of HF Hamiltonian -nonself -> calculates hf with Ex only (no eigenvalues/vectors) -fbz ->runs kgen and generates a full mesh in the BZ -fft -> runs dstart only up to case.in0_std creation -super-> runs dstart and creates new_super.clmsum (and not $file.clmsum) -lcore-> runs dstart with $file.rsplcore (produces $file.clmsc) -sel -> use reduced vector file in lapw7 -settol 0.000x -> run sgroup with different tolerance -sigma-> run lstart with case.inst_sigma (autogenerated) for diff.dens. -rxes-> run tetra using case.rxes weight file for RXES-spectroscopy. -rxesw E1 E2-> run tetra and create case.rxes file for RXES for energies E1-E2 -enefile -> spaghetti+tetra with case.energy instead case.qtl (only tot-dos) -delta-> run arrows program with difference between two structures -copy -> runs pairhess and copies.minpair to.minrestart and.minhess -telnes -> run qtl after generating case.inq based on case.innes -txt -> runs cif2struct using case.txt (see UG) -pp -> run wannier90 in "preprocessing mode" -wf N -> run wplot for Wannier function N -efermi EF -> run findbands (unit:ryd) / shifteig (unit:ev) with Fermi energy EF -emax Y -> for findbands USE: x -h PROGRAMNAME for valid flags for a specific program Note: To make use of a scratch file system (usually a local file system for reducing the network or central fileserver load), you may specify such a filesystem in the environment variable SCRATCH (it may already have been set by your system administrator and must exist on all your nodes) or using the -scratch switch (directory will be created automatically if it does not exist). However, you have to make sure that there is enough disk-space in the SCRATCH directory to hold your case.vector* and case.help* files.
77 5.1. JOB CONTROL Create the master input file case.struct (makestruct lapw) The primary input file for a case is called case.struct. It can be created by the Struct Generator of w2web, by some utilities like cif2struct or xyz2struct or using an interactive script makestruct lapw. This script asks for lattice-type or spacegroup, atoms and their positions, and produces an intermediate file datastruct. The auxilliary programs Tmaker and setrmt lapw converts this into init.struct, which must be copied to the proper location/filename by the user. makestruct lapw was provided by Morteza Jamal (m and Peter Blaha Job control for initialization (init lapw) In order to start a new calculation, one should make a new subdirectory and run all calculations from there. At the beginning one must provide at least one file (see quick-start 3 or the makestruct lapw script5.1.2), namely case.struct (see 4.3). (case.inst can be created automatically on the fly, see 6.4.3), then one runs a series of programs using init lapw. This script is described briefly in chapter 4.5) and in detail in Getting started for the example TiC (see chapter 3). You can get help with switch -h. All actions of this script are logged in short in :log and in detail in the file case.dayfile, which also gives you a restart option when problems occurred. In order to run init lapw starting from a specific point on, specify -s PROGRAM. Ignoring ERRORS and in many cases also WARNINGS during the execution of this script, most likely will lead to errors at a later stage. Neglecting warnings about core-leakage creates.lcore, which directs the scf-cycle to peform a superposition of core densities. init lapw supports switch -b, a batch mode (non-interactive) for trivial cases AND experienced users. You can supply various options and specify spin-polarization, XC-potential, RKmax, k-mesh or mixing. See init lapw -h for more details. Changes to case.struct by nn will be accepted, but by sgroup will be neglected. Please check the terminal output for ERRORS and WARN- INGS!!! Job control for iteration (run lapw or runsp lapw) In order to perform a complete SCF calculation or even perform both, a optimization of internal atomic positions and a SCF calculation simultaneously, several types of scripts are provided with the distribution. For the specific flow of programs see chapter 4.5. For more information on atomic position optimization see chapter For non-spinpolarized calculations use: run lapw, for spin-polarized calculations use: runsp lapw. for antiferromagnetic calculations use: runafm lapw for FSM (fixed-spin moment) calculations use: runfsm lapw for a spin-polarized setup, where you want to constrain the moment to zero (e.g. for LDA+U calculations) use: runsp c lapw Cases with/without inversion symmetry and with/without semicore or core states are handled automatically by these scripts. All activities of these scripts are logged in short in :log (appended) and in detail together with convergence information in case.dayfile (overwriting the old dayfile ). You can always get help on its usage by invoking these scripts with the -h flag. run lapw -h
78 60 CHAPTER 5. SHELL SCRIPTS PROGRAM: PURPOSE: USAGE: /zeus/lapw/wien2k/bin/run_lapw running the nonmagnetic scf-cycle in WIEN to be called within the case-subdirectory has to be located in WIEN-executable directory run_lapw [OPTIONS] [FLAGS] OPTIONS: -cc LIMIT -> charge convergence LIMIT ( e) -ec LIMIT -> energy convergence LIMIT ( Ry) -fc LIMIT -> force convergence LIMIT (1.0 mry/a.u.) default is -ec ; multiple convergence tests possible -e PROGRAM -> exit after PROGRAM () -i NUMBER -> max. NUMBER (40) of iterations -s PROGRAM -> start with PROGRAM () -r NUMBER -> restart after NUMBER (99) iterations (rm *.broyd*) -nohns NUMBER ->do not use HNS for NUMBER iterations -in1new N -> create "new" in1 file after N iter (write_in1 using scf2 info) -ql LIMIT -> select LIMIT (0.05) as min.charge for E-L setting in new in1 -qdmft NP -> including DMFT from Aichhorn/Georges/Biermann running on NP proc -scratch dir/ -> sets (and creates) scratch directory (for vector files) FLAGS: -h/-h -> help -I -> with initialization of in2-files to "TOT" -NI -> does NOT remove case.broyd* (default: rm *.broyd* after 60 sec) -p -> run k-points in parallel (needs.machine file [speed:name]) -it -> use iterative diagonalizations -it1 -> use iterative diag. with recreating H_inv (after basis change) -it2 -> use iterative diag. with reinitialization (after basis change) -nohinv -> use iterative diag. without H_inv -vec2pratt -> use vec2pratt instead of vec2old for iterative diag. -so -> run SCF including spin-orbit coupling -renorm-> start with mixer and renormalize density -in1orig-> if present, use case.in1_orig file; do not modify case.in1 -hf -> HF/hybrid-DFT calculation -diaghf -> non-selfconsistent HF with diagonal HF only (only e_i) -nonself -> non-selfconsistent HF/hybrid-DFT calculation (only E_x(HF)) -newklist -> HF/hybrid-DFT calculation starting from a different k-mesh -reklist -> HF/hybrid-DFT calculation with a reduced different k-mesh for -dftd3 -> include the dispersion energy and forces with the DFT-D3 method -min -> force optimization using MSR1a CONTROL FILES:.lcore.stop.minstop.fulldiag.noHinv case.inm_vresp case.in0_grr runs core density superposition producing case.clmsc stop after SCF cycle in MSR1A mode(structure optimization) switches to MSR1 force full diagonalization remove case.storehinv files activates calculation of vresp files for meta-ggas activates a second call of lapw0 (mbj pot., or E_xc analysis) ENVIRONMENT VARIBLES: SCRATCH directory where vectors and help files should go Additional flags valid only for magnetic cases (runsp lapw) include: -dm -> calculate the density matrix (when -so is set, but -orb is not) -eece -> use "exact exchange+hybrid" methods -orb -> use LDA+U, OP or B-ext correction -orbc -> use LDA+U correction, but with constant V-matrix Calling run lapw (after init lapw) from the subdirectory case will perform up to 40 iterations (or what you specified with switch -i) unless convergence has been reached earlier. You can choose from three convergence criteria, -ec (the total energy convergence is the default and is set to Ry for at least 3 iterations), -fc (magnitude of force convergence for 3 iterations, ONLY if your system has free structural parameters!) or -cc (charge convergence, just the last iteration), and any combination can also be specified. Be careful with these criteria, different systems will require quite different limits (e.g. fcc Li can be converged to µry, a large unit cell with heavy magnetic atoms only to 0.1 mry). You can stop the scf iterations after the current cycle by generating an empty file.stop (use eg. touch.stop in the respective case-directory).
79 5.1. JOB CONTROL 61 The scf-cycle creates case.broyd* files which contain the charge-history. Once run lapw has finished, you should usually save lapw (see below) the results. When you continue with another run lapw without save lapw (because the previous run did not fulfill the convergence criteria or you want to specify a more strict criterium) the broyden-files will be deleted unless you specify -NI. With -e PROGRAM you can run only part of one scf cycle (e.g. run lapw0, lapw1 and lapw2), with -s PROGRAM you can start at an arbitrary point in the scf cycle (e.g. after a previous cycle has crashed and you want to continue after fixing the problem) and continue to self-consistency. Before mixer is invoked, case.clmsum is copied to case.clmsum old, and the final important files of the scf calculation are case.clmsum and case.scf. Invoking run lapw -I -i 30 -fc 0.5 will first set in case.in2 the TOT-switch (if FOR was set) to save cpu time, then run up to 30 scf cycles till the force criterion of 0.5 mry/a.u. is met (for 3 consecutive iterations). Then the calculation of all terms of the forces is activated (setting FOR in case.in2) for a final iteration. An additional switch -min will activate the optimization of the internal positions using the MSR1a option in case.inm (see Sec ). Note, this option can take several hundreds of scf-cycles in more complicated cases. By default the file case.in1 is updated after lapw2 and the current Fermi-energy is inserted. This will force lapw1 to use instead of the default energy parameters (0.30) an energy E F 0.2. The switch -in1orig can be used to keep the present case.in1 file unmodified (or to copy case.in1 orig back after -in1new). The switch -in1new N preserves for N iteration the current case.in1 file. After the first N iterations write in1 lapw is called and a new case.in1 file is generated, where the energy parameters are set according to the :EPLxx and :EPHxx values of the last scf iteration and the -ql value (see sections 4.4 and 7.5). In this way you may select in some cases better energy-parameters and also additional LOs to improve the linearization may be generated automatically. Note, however, that this option is potentially unsave and dangerous, since it may set energy-parameters of LOs and APW+lo too close (leading to ghostbands) or in cases where you have a bad last iteration (or large changes from one scf iteration to the next. The original case.in1 file is saved in case.in1 orig and is used as template for all further scf-cycles. Parallelization is described in Sec Iterative diagonalization, which can significantly save computer time (in particular for cases with few electrons (like surfaces) and large matrices (larger than 2000) a factor 2-5! is possible), is described in Sec It needs the case.vector.old file from the previous scf-iteration (and this file is created from case.vector when the -it switch is set) and an inverse of a previous Hamiltonian (H0 1 ) stored in case.storehinv. When you change the Hamiltonian significantly (changing RKmax or local orbitals), reinitialize the iterative diagonalization either by touch.fulldiag (performs one full diagonalization) or touch.nohinv (recreates case.storehinv files) or using the -it1 -it2 switch. You can save computer time by performing the first scf-cycles without calculating the non-spherical matrix elements in lapw1. This option can be set for N iterations with the -nohns N switch. The presence of the file.lcore directs the script to superpose the radial core densities using dstart and generating case.clmsc. It is created automatically during init lapw when chargeleakage warnings are ignored. This option allows to reduce the number of semi-core states, but still keeping a good charge density. dstart can also run in mpi-parallel mode, otherwise it can be slow for big cases.
80 62 CHAPTER 5. SHELL SCRIPTS The presence of the file case.in0 grr activates a second call of lapw0, which is necessary for modified Becke-Johnson potentials (see Section 4.5.9) or E xc analysis. It is also possible to calculate exact exchange (Hartree-Fock) and perform full hybrid-dft calculations. However, such calculations are very expensive. They are activated using the -hf switch. More information can be found in Sec If you have a previous scf-calculation and changed lattice parameters or positions (volume optimization or internal positions minimization), one could use -renorm to renormalize the density prior to the first iteration., but the recommended way is to use clmextrapol lapw. For magnetic systems which are difficult to converge you can use the script runfsm lapw -m M (see section 4.5.3) for the execution of fixed-spin moment (FSM) calculations. 5.2 Utility scripts Save a calculation (save lapw) After self-consistency has been reached, the script save lapw head of save filename saves case.clmsum, case.scf, case.dmat, case.vorb and case.struct as well as all inputs (case.in* under the new name and removes the case.broyd* files. Now you are ready to modify structural parameters or input switches and rerun run lapw, or calculate properties like charge densities (lapw5), total and partial DOS (tetra) or energy bandstructures (spaghetti). For more complicated situations, where many parameters will be changed, we have extended save lapw so that calculations can not only be saved under the head of save filename but also a directory can be specified. If you use any of the possible switches (-o, -f, -d, -s) all input files will be saved as well (and can be restored using restore lapw). Options to save lapw can be seen with save lapw -h Currently the following options are supported -h help -o old scheme, does not save input files -f force save lapw to overwrite previous saves of the same name -d directory save calculation in directory specified -s silent operation (no output on screen) -dos saves case.int, qtl and dos files -band saves case.output1/so, qtl, irrep and spaghetti files -optic saves case.symmat,joint,epsilon,sigma,eloss,absorp,klist,kgen,inop,injoint,inkram... files Note: for DOS, bandstructure or optic, there is no corresponding restore lapw option, but files must be handled by hand Restoring a calculation (restore lapw) To restore a calculation the script restore lapw can be used. This script restores the struct, clmsum, vorb and dmat files as well as all input files. Note: The input files will only be restored when save lapw -d was used, i.e. when you have saved a calculation in an extra directory.
81 5.2. UTILITY SCRIPTS 63 After restore lapw you can continue and either run an scf cycle (run lapw) or recreate the scf-potential (x lapw0) and the corresponding eigenvectors (x lapw1) for further tasks (DOS, electron density,...). Options to restore lapw are: -h help -f force restore lapw to overwrite previous files -d directory restore calculation from directory specified -s silent operation (no output) -t only test which files would be restored Reduce atomic spheres and interpolate density (reduce rmt lapw) reduce rmt lapw [ -r XX -up] When a structure optimization (MSR1a and run(sp) lapw or min lapw) fails because of overlapping spheres, this script will reduce the spheres (default: 3 % or use -r XX) and interpolate the density inside the spheres to the new radial mesh. Setting the switch -up will do it for clmsum, clmup and clmdn files Remove unnecessary files (clean lapw) Once a case has been completed you can clean up the directory with this command. Only the most important files (scf, clmsum, struct, input and some output files) are kept. It is very important to use this command when you have finished a case, since otherwise the large vector and helpxx files will quickly fill up all your disk space. Options to clean lapw are: -h help -s silent operation (no output) -r recursively clean all directories starting from the current one Migrate a case to/from a remote computer (migrate lapw) This script migrates a case to a remote computer (to be called within the case-dir). Needs working ssh/scp without password; local and remote case-dir must have the same name. Call it within the desired case-dir as: migrate lapw [FLAGS OPTIONS] with the following options: -put -get -all -start -end -save savedir -> transfer of files to a remote host (default) -> transfer of files from a remote host -> the complete directory is copied -> only files to start an scf cycle are copied (default for put) -> only new files resulting from an scf cycle are copied (default for get) -> "save_lapw -d save_dir" is issued and only save_dir is copied FLAGS: -h -> help
82 64 CHAPTER 5. SHELL SCRIPTS -clean -> a clean_lapw is issued before copying -r -> files in source directory are removed after copying -R -> source directory (and all files) are removed after copying -s -> do it silent (in batch mode) -z -> gzip files before scp (slow network) Generate case.inst (instgen lapw) This script generates case.inst from a case.struct file. It is used automatically in init lapw, if case.inst is not present. Using some options (see below) it allows to define the spin-state of all/certain atoms. Note: the label RMT is necessary in case.struct. instgen_lapw [-h -s -up -dn -nm -ask] -h: generate this message -s: silent operation (do not ask) -up: generates spin-up configuration for all atoms (default) -dn: generates spin-dn configuration for all atoms -nm: generates non-magnetic configuration for all atoms -ask: asks for each atom which configuration it should generate Set R-MT values in your case.struct file (setrmt lapw) This perl-script executes x nn and uses its output to determine the atomic sphere radii (obeying recommended ratios for H, sp-, d- and f- elements). It is called automatically within init lapw or you may call it in the or explicitly using: setrmt lapw case [-r X ] [-a XX:A,YY:B,... ] [-orig] where case gives the head of the case.struct file. You may specify a reduction (-r) of the RMTs by X percent in order to allow for structural optimizations. If you already know which RMT values you want to know for a certain element, you can fix them using eg. (-a Mg:1.9). The new setrmt lapw version knows optimal RKmax values for all atoms and makes a finer tuning of the different RMTs. with (-orig) you can go back to the old scheme which distinguishes only between H, sp- and d-elements. It creates case.struct setrmt with the modified RMTs create add atom clmsum lapw The script create add atom clmsum lapw creates a better starting density for a case, where you alsready have a scf-solution for a similar case. Similar means, that the new and old case are identical except for ONE atom (adding an adsorbate,...). This script is experimental and only for experienced users. It is usefull in BIG cases, which are difficult to converge from init lapw. Modifications and adaptions to a specific case are probably necessary Create case.int file (for DOS) (configure int lapw) This script creates the input file case.int for the program tetra and allows to specifiy which partial DOS (atom, l and m) should be calculated. It was provided by Morteza Jamal (m You can specify interactively:
83 5.2. UTILITY SCRIPTS 65 total (for plotting Total Dos ) N (to select atom N) s,p,d,... (to select a set of PDOS for previously selected atom N) use labels as listed in the header of your case.qtl file) end (for exit) There is also a batch (non-interactive) mode: configure_int_lapw -b total 1 tot,d,d-eg,d-t2g 2 tot,s,p end which will prepare case.int (eg. for the TiC example) with: tic #Title #Emin, DE, Emax, Gauss-Broad 8 #Number of DOS 0 1 total-dos 1 1 tot-ti 1 4 d-ti 1 5 d-eg-ti 1 6 d-t2g-ti 2 1 tot-c 2 2 s-c 2 3 p-c Check for running WIEN jobs (check lapw) This script searches for.running.* files within the current directory (or the directory specified with -d full path directory ) and then performs a ps command for these processes. If the specified process has not been found, it removes the corresponding.running.* file after confirmation (default) or immediately (when -f has been specified) Cancel (kill) running WIEN jobs (cancel lapw) This script searches for.running.* files within the current directory (or the directory specified with -d full path directory ) and then kills the corresponding process after confirmation (default) or immediately (when -f has been specified). It is particular useful for killing k-point parallel jobs Extract critical points from a Bader analysis (extractaim lapw) This script extracts the critical points (CP) after a Bader analysis (x aim (-c)) from case.outputaim. It sorts them (according to the density), removes duplicate CPs, converts units into Å, e/å 3,... and produces critical points ang. It is used with: extractaim lapw case.outputaim scfmonitor lapw This program was contributed by:
84 66 CHAPTER 5. SHELL SCRIPTS Hartmut Enkisch Institute of Physics E1b University of Dortmund Dortmund, Germany Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. It produces a plot of some quantities as function of iteration number (a maximum of 6 quantities is possible at once) from the case.scf file as specified on the commandline using analyse lapw and GNUPLOT. This plot is updated in regular intervals. You can call scfmonitor lapw using: scfmonitor lapw [-h] [-i n] [-f case.scf] [-p] arg1 [arg2.. arg6] -h help switch -i n show only the last n iterations -f scf-file use "scf-file" instead of the default "case.scf" -p produces file "scfmonitor.png" instead of X-window plot arg1,... arguments to monitor (like ":ENE" or ":DIS", see analyse_lapw ) The scfmonitor can also be called directly from w2web using the Analyse tool. In order to have a reasonable behavior of scfmonitor the GNUPLOT window should stay in background. This can be achieved by putting a line into your.xdefaults file like: gnuplot*raise: off Note: It does not make sense to start scfmonitor before the first cycle has finished because no case.scf exists at this point analyse lapw The script analyse lapw is usually called from scfmonitor lapw. It greps from an scf-file the specified arguments and produces analyse.out. analyse lapw is called using: analyse lapw [-h] scf-file arg1 [arg2 arg3 arg4 arg5 arg6] -h help switch scf-file "scf-file" to analyse (there s no default "case.scf"!) arg1,... arguments to analyse: atom independent: :ENE :DIS :FER :MMT :VOL :GAP atom iii dependent: :CTOiii :CUPiii :CDNiii :NTOiii :NUPiii :NDNiii :DTOiii :DUPiii :DDNiii :RTOiii :EFGiii :HFFiii :MMIiii vector quantities: :FORiii[x/y/z] :POSiii[x/y/z] :FGLiii[x/y/z] where magnitude z z is the default For vector quantities like :FGLiii or :POSiii (useful with case.scf mini) one can specify the respective coordinate by adding x/y/z to the corresponding labels.
85 5.2. UTILITY SCRIPTS Check parallel execution (testpara lapw) testpara lapw is a small script which helps you to determine an optimal selection for the file.machines for parallel calculations (see sec. 5.5) Check parallel execution of lapw1 (testpara1 lapw) testpara1 lapw is a small script which determines how far the execution of lapw1para has proceeded Check parallel execution of lapw2 (testpara2 lapw) testpara2 lapw is a small script which determines how far the execution of lapw2para has proceeded grepline lapw Using grepline lapw :label filename*.scf lines for tail or grepline :label filename*.scf lines for tail you can get a list of a quantity :label (e.g. :ENE for the total energy) from several scf files at once initso lapw initso lapw helps you to initialize the calculations for spin-orbit coupling. It helps together with make inso lapw (based on an idea of Morteza Jamal, m to create/modify all required input files (case.inso, case.in1, case.in2c). In a spinpolarized case SO may reduce symmetry or equivalent atoms may become non-equivalent, and the script calls symmetso and will help you to find proper symmetries and setup the respective input files. It is called using initso lapw or initso and you should carefully follow the instructions and explanations of the script and the explanations for case.inso given in section 7.6. Since forces are not correct for atoms with SO, it can be very useful to suppress SO for light atoms (eg. the O-atoms in UO 2 ), because then one can optimize the O-positions init hf lapw init hf lapw helps you to initialize the calculations for hybrid-dft functionals. It creates several files (case.inhf, case.in0 grr), selects YS-PBE0 (see Ref. Tran,Blaha 2011), changes some input files (case.in0) and calls run kgenhf lapw to generate the k-mesh for the HF calculation. It takes -up for spin-polarized cases. For details of hybrid-dft calculations see
86 68 CHAPTER 5. SHELL SCRIPTS init mbj lapw init mbj lapw helps you to initialize the calculations for a TB-mBJ (see Tran, Blaha 2009) calculation, which usually requires a couple of steps done in proper order. A proper sequence would be: init mbj lapw run lapw -i 1 init mbj lapw save lapw xxxx pbe run lapw The first call to init mbj lapw creates case.inm vresp and sets R2V in case.in0. The second call of init mbj lapw creates case.in0 and case.in0 grr with the proper input for mbj. It also lets you select parameters of the original TB-mBJ potential, or the later adaption to semiconductors or insulators, or the original BJ method. For details of TB-mBJ calculations see vec2old lapw vec2old lapw moves case.vector files to case.vector.old. Usually called automatically just before lapw1 when the iterative diagonalization (run lapw -it) is specified. It also works for the k-parallel case including local $SCRATCH directories (add -p as first argument, uses hosts from.processes and requires commensurate k-point/number of processors) and spinpolarization (-up/-dn switches). For runfsm lapw the sequence had to be changed and the switches -updn or -dnup forces vec2old to COPY case.vectorup tocase.vectordn (and vice versa). In the runfsm lapw case the corresponding case.vector*.old files are generated just AFTER lapw2/lapwdm and not BEFORE lapw1. Thus after runfsm lapw has finished, the corresponding spin-up/dn vectors are case.vector*.old and NOT case.vector*. The switches -p -local will copy $SCRATCH/case.vector* to case.vector*. It will be done automatically when you run x lapw2 -p -qtl. An alternative script vec2pratt lapw was provided by L.D.Marks which together with SRC vecpratt mixes the last two vectors (Pratt mixing) to generate case.vector.old. It is activatd using the -vec2pratt switch in run lapw clmextrapol lapw clmextrapol lapw extrapolates the charge density (case.clmsum/up/dn) from old to new positions (or from old to new lattice parameters). It takes the density from the old positions (copied into old.clmsum) and subtracts an atomic superposition density (new super.clmsum) fom the old positions and adds an atomic superposition density fom the new ones (generated by dstart). If new super.clmsum (generated automatically by init lapw) is not present, it will be generated and for the next geometry step an extrapolation will take place. It is usually called from min lapw after a geometry step has finished and a new struct file has been generated. It can significantly reduce the number of scf-cycles for the new geometry step.
87 5.3. STRUCTURE OPTIMIZATION makescratch lapw makescratch lapw scratch-dir-name checks the existense of the directory and eventually creates it (up to 3 levels deep). Usually called automatically by other Wien2k-scripts. 5.3 Structure optimization Lattice parameters (Volume, c/a, lattice parameters) Package optimize The auxilliary program optimize (x optimize) generates from an existing case.struct (or case initial.struct, which is generated at the first call of optimize) a series of struct files with various volumes (or c/a ratios, or other modified parameters) (depending on your input): [1] VARY VOLUME with CONSTANT RATIO A:B:C [2] VARY C/A RATIO with CONSTANT VOLUME (tetr and hex lattices) [3] VARY C/A RATIO with CONSTANT VOLUME and B/A (orthorh lattice) [4] VARY B/A RATIO with CONSTANT VOLUME and C/A (orthorh lattice) [5] VARY A and C (2D-case) (tetragonal or hexagonal lattice) [6] VARY A, B and C (3D-case) (orthorhombic lattice) [7] VARY A, B, C and Gamma (4D-case) (monoclinic lattice) [8] VARY C/A RATIO and VOLUME (2D-case) (tetr and hex lattices) It also produces a shell-script optimize.job which looks similar to: #!/bin/csh -f foreach i ( \ tic_vol_-10.0 \ tic_vol -5.0 \ tic_vol 0.0 \ tic_vol 5.0 \ tic_vol 10.0 \ ) cp $i.struct tic.struct # cp $i.clmsum tic.clmsum # x dstart # run_lapw -ec in1new 3 -renorm run_lapw -ec set stat = $status if ($stat) then echo "ERROR status in" $i exit 1 endif save_lapw ${i} # save_lapw -f -d XXX $i end You may modify this script according to your needs: use runsp lapw or even min lapw, or specify different convergence parameters; modify the save lapw command and change the save-name or save into a directory to separate e.g. gga and lda results. Eventually you may activate the line cp $i.clmsum case.clmsum to use a previously saved clmsum file, e.g. from a calculation with smaller RKmax,... and deactivate the clmextrapol lapw lines, but usually the latter is so efficient that this is no longer recommended. Note: You must have a case.clmsum file (either from init lapw or from a previous scf calculation) in order to run optimize.job. After execution of this script you should have a series of scf-files with energies corresponding to the modified parameters, which should allow you to find the corresponding equillibrium parameters. For the volume optimization an analysis tool is available, other tools are under development). Using the script grepline (or the Analysis Analyze multiple SCF-files menu of w2web) you get a summary of the total energy vs. volume (c/a). The file case.analysis can be used in
88 70 CHAPTER 5. SHELL SCRIPTS eplot lapw or gibbs lapw to find the minimum total energy and the equilibrium volume (or c/a or b/a). Supported equation of states include the EOS2, Murnaghan and Birch-Murnaghan EOS. grepline :ENE *.scf 1 > case.analysis grepline :VOL *.scf 1 >> case.analysis Alternatively you can also use eplot lapw directly and the case.analysis file is generated automatically : or eplot lapw -a vol eplot -a "*" will analyse all scf files *vol*.scf eplot -a pbe will analyse all scf files *vol*pbe.scf Using such strategies also higher-dimensional optimizations (e.g. c/a ratio and volume) are possible in combination with the -d option of save lapw. For optimization of more degrees of freedom (2-4 lattice parameters), you can use the corresponding option and for analysis of the data the script parabolfit lapw together with the program eosfit6. It performs a non-linear least squares fit, using a parabolic fit-function in your variables and get an analytic description of your energy surface. Please note, this is only a harmonic fit (no odd or higher terms) and the description may not be very good if your parameter range is large and/or the function is quite anharmonic, or you suffer from numerical noise. For the determination of elastic constants see the description of ELAST in sec 8.5 and IRelast in sec 8.8. Package 2DRoptimize This program was contributed by: Morteza Jamal Ghods City-Tehran,Iran m Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. This package [see also Ref. Reshak 2013] performs a convenient 2D structure optimization (Volume and c/a for tetragonal, rhombohedral or hexagonal spacegroups). After initialization of a case, one generates a set of structures and a job-file 2Doptimize.job using the command set2d lapw This calls setup2d and you have to specify the changes in volume and c/a. The resulting 2Doptimize.job script should be adapted (eg. use min lapw instead of run lapw; insert switches,...) and executed. Finally ana2d lapw
89 5.3. STRUCTURE OPTIMIZATION 71 can be executed and will analyze the results. It uses a set of case.vconst* files (produced by 2Doptimize.job and stored also in subdirectory Vconst) and the numbvcoa file. ana2d lapw checks the sensitivity of the results with the order of fitting (3,4 or 5th order polynomials) and lets you select the best one. Note: Fits of high order (and few data points ) may lead to artificial results due to unphysical oszillations of the fit. You can see results for - energy vs. c/a for each volume, - energy vs. volume (with optimized c/a) and - c/a vs. volume. At the end, ana2d lapw calculates a and c lattice constants (and a R, α R for rhombohedral compounds) and checks the sensitivity of them to the order of fit (order of fit=3 or 4 or 5) when it finds the equation of c/a vs. volume and stores in fitorder. Optionally you can specify more cases by rerunning set2d lapw. Specify also your old volume and c/a points again (or leave them out on purpose in case they were very bad (eg. very far from the minimum). The old results will be taken automatically into account without recalculation (unless you modify 2Doptimize.job, see the comments at the top of this file). Thus a good strategy is to use only 3x3 points (order of fit = 3) and in a second step you add points where they are needed. When you want to rerun such an optimization with different parameters (RKmax, k-mesh, XCpotentials) modify the top of 2Doptimize.job and set answscf=no and a new savename (eg. pbe rk8 1000k ) Minimization of internal parameters (min lapw) Most of the more complicated structures have free internal structural parameters, which can either be taken from experiment or optimized using the calculated forces on the nuclei. Starting with WIEN2k 11.1 there are two possibilities to determine the equilibrium position of all individual atoms automatically (obeying the symmetry constraints of a certain space group). One can use either the shell script min lapw, together with the program mini, which will run a scf-cycle, update the positions using the calculated forces and restarts a new scf cycle. This continues until forces drop below a certain value; or use the normal scf-scripts run lapw -min where in case.inm the switch MSR1 will be modified to MSR1a such that the charge density and the positions are simultaneously optimized during the scf-cycle. At present we recommend the second (new) option, although there are cases where this scheme can be slower or may even fail to converge. A typical sequence of commands for an optimization of the internal positions would look like: Generate struct file init lapw run lapw -fc 1 [another runxx script or additional options are of course also possible] (this may take some time) Inspect the scf file whether you have significant forces (usually at least.gt. 5 mry/bohr), otherwise you are more or less at the optimal positions (An experienced user may omit the run lapw step and proceed directly from init lapw to the next step) Now you have to decide which method to use:
90 72 CHAPTER 5. SHELL SCRIPTS min lapw [options] (this may take some time) it will generate a default case.inm (if not present) by: executing x pairhess -copy ; cp case.inm st case.inm (i.e. it sets up the PORT minimization option and calculates an approximate starting Hessian). when -nohess is specified, it will generate case.inm from SRC templates with the NEW1 option (not recommended). Without -NI switch min lapw performs an initialization first: removes histories (case.broyd*, case.tmpm) if present; copies.min hess to.minrestart (if present from previous min lapw or x pairhess). or edit case.inm and put MSR1a (or MSEC1a) as mixing method. save lapw xxx the original calculation and then continue with run lapw -fc 0.5 -ec cc [-it]. It will run x pairhess (unless case.inm is already present) and then run (several hundreds) scf-cycles, simultaneously updating positions and charge densities. Once the forces seem to be smaller than the limit defined in case.inm it will switch to mixing method MSR1 and finalize the scf-cycle with fixed positions. Because of this, the final forces may not be as small as desired and eventually you have to restart this step using MSR1a again. When using the second method we recommend you read carefully $WIEN- ROOT/SRC mixer/readme 5.2.pdf. Overall the method is very good for semiconductors (or well behaved metals), and allows tricks like small k-mesh or small RKMax at the beginning of the minimization and using higher accuracy only towards the end. The following text refers (mainly) to the first method using min lapw: When case.scf is not present, an scf-cycle will be performed first, otherwise the corresponding forces are extracted into case.finm and the program mini generates a new case.struct with modified atomic positions. The previous step is saved under case 1/2/3... Then a new scfcycle is executed and this loop continues until convergence (default: forces below 2mRy/bohr) is reached. The last iteration of each geometry step is appended to case.scf mini, so that this file contains the complete history of the minimization and can be used to monitor the progress (grep :ENE *mini; or :FORxxx...). By default (unless switch -noex is specified), min will call the script clmextrapol lapw after the first geometry step and try to extrapolate the charge density to the new positions. This procedure usually significantly reduces the number of scf-cycles and is thus highly recommended. mini requires an input file case.inm (see Sec. 8.15) which is created automatically and MUST NOT be changed while min lapw is running (except the force tolerance, which terminates the optimization). We recommend the PORT minimization method, a reverse-communication trust-region Quasi- Newton method from the Port library, which seems to be stable, efficient and does not depend too much on the users input (DELTAs, see below with NEWT). The PORT option also uses/produces a file.min hess, which contains the (approximate) Hessian matrix (lower-triangle Cholesky factor) If you restart a minimization with different k-points, RMT, RKmax,... or do a similar calculation (eg. for a different volume,...) it will be copied to.minrestart (unless -nohess is specified), so that you start with a reasonable approximation for the Hessian. The program pairhess, which calculates the first Hessian, also prints out the average Hessian eigenvalue for the symmetric, symmetry-preserving modes in mryd/au2 as well as the minimum and maximum, and also the vibration frequencies. A list of these is given at the end of case.pairhess. Note that these are not all possible modes, but only the symmetry preserving ones. Therefore if you have prior information about the vibrations of the system you can adjust the rescaling term so the average
91 5.3. STRUCTURE OPTIMIZATION 73 vibration frequency is about correct. (see the description of pairhess in 9.2). (In addition there is a program eigenhess, which will analyze the Hessian after the minimization has been completed. It also prints vibrational frequencies and may give you hints about dynamical instability of your system. Some more description is given in $WIENROOT/SRC pairhess/readme and at the top of the output file case.outputeig. When using PORT you may also want to check its progress using grep :LABEL case.outputm where :LABEL is :ENE (should decrease), :GRAD (should also go down, but could sometimes also go up for some time as long as the energy still decreases), :MIN (provides a condensed summary of the progress), :WARN may indicate a problem), :DD (provides information about the step sizes and mode used). Some general explanations are: 1) The algorithm takes steps along what it considers are good directions (using some internal logic), provided that these steps are smaller than what is called the trust-region radius. After a good step (e.g. large energy decrease) it expands the trust-region; after a bad one it reduces it. Sometimes it will try too large a step then have to reduce it, so the energy does not always go down. You can see this by using :DD and :MIN. 2) A grep on :MIN gives a condensed progress output, in which the most significant terms are E (energy in some rescaled units), RELDF (last energy reduction), PRELDF (what the algorithm predicted for the step), RELDX (RMS change in positions in Angstroms) and NPRELDF (predicted change in next cycle). Near the solution RELDF and RELDX should both become small. However, sometimes you can have soft modes in your structure in which case RELDX will take a long time before it becomes small. 3) A warning that the step was reduced due to overlapping spheres if it happens only once (or twice) is not important; the algorithm tested too large a step. However, if it occurs many times it may indicate that the RMT s are too big. 4) A warning CURVATURE CONDITION FAILED indicates that you are still some distance from the minimum, and the Hessian is changing a lot. If you see many of these, it may be that the forces and energy are not consistent. Sometimes PORT gets stuck (often because of inconsistencies of energy and forces due to insufficient scf convergence or a very non-harmonic potential energy surface). A good alternative is NEW1, which is a sophisticated steepest-descent method with optimized step size. It can be very efficient in certain cases, but can also be rather slow when the potential energy surface is rather flat in one, but steep in another direction (eg. a weakly bound molecule on a surface, but constraining the sensitive parameters, like the bond distance of the molecule, may help). Another alternative is NEWT, where one must set proper DELTAs and a FRICTION for each atom. Unfortunately, these DELTAs determine crucially how the minimization performs. Too small values lead to many (unnecessary) geometry steps, while too large DELTAs can even lead to divergence (and finally to a crash). Thus you MUST control how the minimization performs. We recommend the following sequence after 2-3 geometry steps: grep :ENE *mini :ENE : ********** TOTAL ENERGY IN Ry = :ENE : ********** TOTAL ENERGY IN Ry = :ENE : ********** TOTAL ENERGY IN Ry = Good, since the total energy is decreasing. grep :FGL001 *mini :FGL001: 1.ATOM :FGL001: 1.ATOM :FGL001: 1.ATOM
92 74 CHAPTER 5. SHELL SCRIPTS Good, since the force (only a force along z is present here) is decreasing reasonably fast towards zero. You must check this for every atom in your structure. When you detect oszillations or too small changes of the forces during geometry optimization, you will have to decrease/increase the DELTAs in case.inm and rm case.tmpm. (NOTE: You must not continue with modified DELTAs but keeping case.tmpm.) Alternatively, stop the minimization (touch.minstop and wait until the last step has finished), change case.inm and restart. You can get help on its usage with: min -h or min lapw -h PROGRAM: USAGE: min min [OPTIONS] OPTIONS: -j JOB -> job-file JOB (default: run_lapw -I -fc 1. -i 40 ) -noex -> does not extrapolate the density for next geometry step -p -> adds -p (parallel) switch to run_lapw -it -> adds -it (iterative diag.) switch to run_lapw -it1 -> adds -it1 (it.diag. with recreating H_inv) switch to $job -it2 -> adds -it2 (it.diag. with reinitialization) switch to $job -nohinv -> adds -it -nohinv (it.diag. without H_inv) switch to $job -sp -> uses runsp_lapw instead of run_lapw -nohess -> removes.minrestart (initial Hessian) from previous minimization -m -> extract force-input and execute mini (without JOB) and exit -mo -> like -m but without copying of case.tmpm1 to case.tmpm -h/-h -> help -NI -> without initialization of minimization (eg. continue after a crash) -i NUMBER -> max. NUMBER (50) of structure changes -s NUMBER -> save_lapw after NUMBER of structure changes CONTROL FILES:.minstop stop after next structure change For instance for a spin-polarized case, which converges more difficultly, you would use: min -j runsp lapw -I -fc 1.0 -i Phonon calculations Calculations of phonons is based on a program PHONON by K.Parlinski, which runs under MS- Windows and must be ordered separately (see ). Alternatively you may also try the package PHONOPY by Atsushi Togo (see /reg_user/unsupported/). You would define the structure of your compound in PHONON together with a supercell of sufficient size (e.g. 64 atoms). PHONON will then generate a list of necessary displacements of the individual atoms. The resulting file case.d45 must be transfered to UNIX. Here you would run WIEN2k-scf calculations for all displacements and collect the resulting forces, which will be transfered back to PHONON (case.dat and/or case.dsy). With these force information PHONON calculates phonon at arbitrary q-vectors together with several thermodynamic properties init phonon lapw init phonon lapw uses case.d45 from PHONON and creates subdirectories case XX and case XX.struct files for all required displacements. It allows you to define globally RMT values for the different atoms and - initializes every case individually (batch option of init lapw is now supported) or
93 5.5. PARALLEL EXECUTION 75 - initializes every second case (useful for pos. and neg. displacements, which have the same symmetry and thus only one initialization is necessary), or - initializes only the first case and copies the files from the first case to all others. This is most convenient in low symmetry cases with P1 symmetry for all cases and thus just one init lapw needs to be executed (while for higher symmetry a separate initialization is required (but computational effort is reduced). Please use mainly nn to reduce equivalent atoms. sgroup might change the unitcell and than the collection of forces into the original supercell is not possible (or quite difficult). A script run phonon has been created. Modify it according to your needs (parallelization,...) and run all cases to selfconsistency. Note that good force convergence is essential (at least 0.1 mry/bohr) and if your structure has free parameters, either very good equillibrium positions must have been found before, or even better, use both, positive and negative displacements to average out any resulting error from nonequillibrium positions analyse phonon lapw analyse phonon lapw uses the resulting scf files and generates the Hellmann-Feynman -file required by PHONON. When you have positive and negative displacements an automatic averaging will be performed. The resulting case.dat and case.dsy filse should be transfered back to MS-Windows and imported into PHONON. 5.5 Running programs in parallel mode This section describes two methods for running WIEN2k on parallel computers. One method, parallelizing k-points over processors, utilizes c-shell scripts, NFS-file system and passwordless login ((public/private keys). This method works with all standard flavors of Linux without any special requirements. The parallelization is very efficient even on heterogeneous computing environments, e. g. on heterogeneous clusters of workstations, but also on dedicated parallel computers and does NOT need very large network bandwidth. The other parallelization method is based on fine grained methods, MPI and SCALAPACK. It is especially useful for larger systems, if the required memory size is no longer available on a single computer or when more processors than k-points are available. It requires a fast network (Infiniband) or a shared memory machine. Although for small systems (less than 50 atoms/cell) is is not as efficient as the simple k-point parallelization, the current mpi-version has been enhanced a lot and shows for larger problems very good scaling with the number of processors for most parts. In any case, the number of processors and the size of the problem (number of atoms, matrixsize due to the plane wave basis) must be compatible and typically [NMAT / sqrt(processors)].gt should hold. The k-point parallelization can use a dynamic load balancing scheme and is therefore usable also on heterogeneous computing environments like networks of workstations or PCs, even if interactive users contribute to the processors work load. If your case is large enough, but you still have to use a few k-points, a combination of both parallelization methods is possible (always use k-point parallelism first if you have more than 1 k-point) k-point Parallelization Parts of the code are executed in k-parallel, namely lapw1, lapwso, hf, lapw2, lapwdm and optic, qtl, irrep, nmr. These are the numerically intensive parts of most calculations.
94 76 CHAPTER 5. SHELL SCRIPTS Parallelization is achieved on the k-point level by distributing subsets of the k-mesh to different processors and subsequent summation of the results. The implemented strategy can be used both on a multiprocessor architecture and on a heterogeneous (even multiplatform) network. To make use of the k-point parallelization, make sure that your system meets the following requirements: NFS: All files for the calculation must be accessible under the same name and path. Therefore you should set up your NFS mounts in a cluster in such a way, that on all machines the path names are the same. Remote login: ssh to all machines must be possible without specifying a password. This will be handled automatically for a single shared memory machine and when you have specified shared memory during site config (setenv USE REMOTE 0 in $WIENROOT/parallel options). Otherwise you must correctly specify public/private keys for ssh. This can be done by running ssh-keygen -t rsa and copying the id rsa.pub key into /.ssh/authorized keys at the remote sites. The command for launching a remote shell is platform dependent, and usually can be ssh, rsh or remsh. It should be specified during installation when siteconfig lapw is executed (see chapter 11) MPI parallelization Fine grained MPI parallel versions are available for the programs dstart, lapw0, lapw1, lapwso, hf, nmr and lapw2. This parallelization method is based on parallelization libraries, including MPI, ScaLapack, PBlas and FFTW 2 or FFTW 3 (lapw0). The required libraries are not included with WIEN2k. On parallel computers, however, they are usually installed. Otherwise, free versions of these libraries are available 1. The parallelization affects the naming scheme of the executable programs: the fine grained parallel versions of lapw0/1/2/so, dstart and hf are called lapw0 mpi, lapw1[c] mpi, lapwso mpi, dstart mpi, hf[c] mpi, and lapw2[c] mpi. These programs are executed by calls to the local execution environments, as in the sequential case, by the scripts x, dstartpara, lapw0para, lapw1para, lapwsopara, hfpara and lapw2para. On most computers this is done by calling mpirun and this must be configured using siteconfig lapw How to use WIEN2k as a parallel program To start the calculation in parallel, a switch must be set and an input file has to be prepared by the user. The switch -p switches on the parallelization in the scripts x and run lapw. In addition to this switch the file.machines has to be present in the current working directory. In this file the machine names on which the parallel processes should be launched, and their respective relative speeds must be specified. If the.machines file does not exist, or if the -p switch is omitted, the serial versions of the programs are executed. Generation of all necessary files, starting of the processes and summation of the results is done by the appropriate scripts lapw1para, lapwsopara, hfpara, lapwdmpara and lapw2para (when using -p), and parallel programs dstart mpi, lapw0 mpi, lapw1 mpi, lapwso mpi, hf mpi, and lapw2 mpi (when using fine grained parallelization has been selected in the.machines file). org/
95 5.5. PARALLEL EXECUTION The.machines file The following.machines file describes a simple example. We assume to have 5 computers, (alpha,... epsilon), where epsilon has 4, and delta and gamma 2 cpus. In addition, gamma, delta and epsilon are 3 times faster than alpha and beta.: # This is a valid.machines file # granularity:1 1:alpha 1:beta 3:gamma:2 delta epsilon 3:delta:4 epsilon:4 residue:delta:4 lapw0:gamma:2 delta:2 epsilon:4 dstart:gamma:2 delta:2 epsilon:4 To each set of processors, defined by a single line in this file, a certain number of k-points is assigned, which are computed in parallel. In each line the weight (relative speed) and computers are specified in the following form: weight:machine name1:number1 machine name2:number2... where weight is an integer (e.g. a three times more powerful machine should have a three times higher weight). The name of the computer is machine name[1/2/...], and the number of processors to be used on these computers are number[1/2/...]. If there is only one processor on a given computer, the :1 may be omitted. Empty lines are skipped, comment lines start with #. Assuming there are 8 k-points to be distributed in the above example, they are distributed as follows. The computers alpha and beta get 1 each. Two processors of computer gamma and one processor of computers delta and epsilon cooperate in a fine grained parallelization on the solution of 3 k-points, and four processors of computers delta and epsilon cooperate on the solution of 3 k-points. If there were additional k-points, they would be calculated by the first processor (or set of processors) becoming available. With higher numbers of k-points, this method ensures dynamic load balancing. If a processor is busy doing other (e. g., interactive) work, the overall calculation will not stall, but most of its work will be done by other processors (or sets of processors using MPI). This is, however, not an implementation for fail safety: if a process does not terminate (e. g., due to shutdown of a computer) the calculation will never terminate. It is up to the user to handle with such hardware failures by modifying the.machines file and restarting the calculation at the appropriate point. During the run of lapw1para the file.processes is generated. This file is used by lapw2para (and some others) to determine which case.vector* to read. In case you need to create a.processes file for a NEW.machines file and don t want to run lapw1 (for instance in a PBSjob with x lapw1 -p -qtl ) you can issue: x lapw1 -p -d [-up] to create an updated version of this file. A granularity different from 1 (use eg. 3) allows for some load balancing in heterogeneous environments. Suppose you have 10 k-points and 2 nodes, granularity:1 will start 2 jobs with 5 k-points each. However, if node 1 is heavily overloaded, node 2 will idle for quite some time and time will be wasted. With a larger granularity we would decompose the load into 4 or 6 parts. Two jobs would start first, but the next parts go to the node which is free because it has finished earlier. If you can be sure that load balancing is not an issue (eg. because you use a queuing-system and can be sure that you will get 100% of the cpus for your jobs) it is recommended to set granularity:1
96 78 CHAPTER 5. SHELL SCRIPTS for best performance. On shared memory machines it is advisable to add a residue machine to calculate the surplus (residual) k-points (given by the expression MOD(klist, j newweight j) and rely on the operating system s load balancing scheme. Such a residue machine is specified as residue:machine name:number in the.machines file. Alternatively, it is also possible to distribute the remaining k-points one-by-one (and not in one junk) over all processors. The option extrafine:1 can be set in the.machines file. When using iterative diagonalization or the $SCRATCH variable (set to a local directory), the k-point distribution must be fixed. This means, the ratio (k-points / processors) must be integer (sloppy called commensurate at other places in the UG) and granularity:1 should be set. The lines lapw0:gamma:2 delta:2 epsilon:4 dstart:gamma:2 delta:2 epsilon:4 defines the computers used for running lapw0 mpi and dstart mpi. In this example the 8 processors of the computers gamma, delta, and epsilon run lapw0 mpi and dstart mpi in parallel. The parallel dstart is useful for big cases, where core-leakages occured and a core-density superposition is done automatically (activated by the file.lcore) during scf. Please note, parallelization in lapw0 and dstart is done mainly over atoms, thus the number of useful cores is in general different than for lapw1/2/so/hf. If fine grained parallelization is used, each set of processors defined in the.machines file is converted to a single file.machine[1/2/...], which is used in a call to mpirun (or another parallel execution environment). When using a queuing system (like PBS, LoadLeveler or SUN-Gridengine) one can only request the NUMBER of processors, but does not know on which nodes the job will run. Thus a static.machines file is not possible. On can write a simple shell script, which will generate this file on the fly once the job has been started and the nodes are assigned to this job. Examples can be found at our web-site How the list of k-points is split In the setup of the k-point parallel version of LAPW1 the list of k-points in case.klist is split into subsets according to the weights specified in the.machines file: newweight i = weight i klist granularity j weight j where newweight i is the number of k-points to be calculated on processor i. newweight i is always set to a value greater equal one. A loop over all i processors is repeated until all k-points have been processed.
97 5.5. PARALLEL EXECUTION 79 Speedup in a parallel program is intrinsically dependent on the serial or parallel parts of the code according to Amdahl s law: 1 speedup = (1 P ) + P N whereas N is the number of processors and P the percentage of code executed in parallel. In WIEN2k usually only a small part of time is spent in the programs lapw0, lcore and mixer which is very small (negligible) in comparison to the times spent in lapw1 and lapw2. The time for waiting until all parallel lapw1 and lapw2 processes have finished is important too. For a good performance it is therefore necessary to have a good load balancing by estimating properly the speed and availability of the machines used. We encourage the use of testpara lapw or Utils. testpara from w2web to check the k-point distribution over the machines before actually running the programs in parallel. While running lapw1 and lapw2 in parallel mode, the scripts testpara1 lapw (see ) and testpara2 lapw (see ) can be used to monitor the succession of parallel execution Flow chart of the parallel scripts To see how files are handled by the scripts lapw1para and lapw2para refer to figures 5.1 and 5.2. After the lapw2 calculations are completed the densities and the informations from the case.scf2 x files are summarized by sumpara. Note: parallel lapw2 and sumpara take two command line arguments, namely the case.def file but also a number of processor indicator. Figure 5.1: Flow chart of lapw1para On the fine grained parallelization The following parallel programs use different parallelization strategies: dstart mpi is parallelized over the atoms and the K-vectors. This method leads to good scalability as long as there are more atoms than processors. For very many processors, however, the speedup is limited, which is usually not at all critical, since the overall computing time of dstart mpi is quite small. It uses an extra line dstart: in.machines to specify the parallelization.
98 80 CHAPTER 5. SHELL SCRIPTS Figure 5.2: Flow chart of lapw2para lapw0 mpi is parallelized over the number of atoms and with a parallel FFT, which is important in case you have large FFT grids. This method leads to good scalability as long as there are more atoms than processors. For very many processors, however, the speedup is limited, which is usually not at all critical, since the overall computing time of lapw0 mpi is quite small. It uses an extra line lapw0: in.machines to specify the parallelization. lapw1 mpi uses a two-dimensional processor setup to distribute the Hamilton and overlap matrices. For higher numbers of processors two-dimensional communication patterns (4x4=16, 8x8=64,..) are clearly preferable to one-dimensional communication patterns (never use 47 cores, as it gives a 1x47 pattern). Let us assume, for example, 64 processors. In a given processing step, one of these processors has to communicate with the other 63 processors if a one-dimensional setup was chosen. In the case of a two-dimensional processor setup it is usually sufficient to communicate with the processors of the same processor row (7) or the same processor column (7), i. e. with 14 processors. In general the processor array P Q is chosen as follows: P = number of processors, number of processors Q =. Because of SCALAPACK, often P P arrays (i.e. 4, 9, 16,... P processors) give best performance but others are also possible (eg. 2x4=8, 4x8=32,...). Of course it is not recommended to use eg. 17x1 processors. k-point and mpi-parallelization can be used at the same time and are specified by the lines speed:hostname:number of cores in.machines. hf mpi If you use a full hybrid scheme (see also Sect ) and the -hf option for run lapw, then the hf program will be by far the most time consuming part. MPI-parallelization is done over the total number of atoms/cell ( NAT*MULT ) and over the number of occupied bands. Thus it is important that you choose first the best k-parallelization (if you have more than one k-point) and then a MPI-parallelization which is compatible (meaningful) as much as possible with the two parallelizations mentioned above (if you have just 16 occupied bands and 4
99 5.6. CHEMICAL SHIFT NMR CALCULATIONS 81 atoms, for sure using more than 16 cores is completely useless, but probably the scaling will be bad already for more than 4 cores). The parallelization follows that of lapw1 as specified in.machines, although the script uses.processes, which is created at the lapw1 step. lapwso mpi is parallelized over the Hamiltonian. The size is determined by NE*2, where NE is the number of eigenvalues in lapw1 (determined by EMAX in case.in1). Since this size is usually much smaller than the Hamiltonian of lapw1, try to use quadratic processor grids (4x4=16, 8x8=64). Memory size is larger than for the sequential code, but scales with N/4. The parallelization follows that of lapw1 as specified in.machines, although the script uses.processes, which has been created in the lapw1 step. lapw2 mpi is parallelized in two main parts: (i) The density inside the spheres is parallelized over atoms, and (ii) the fast Fourier transforms are done in parallel. In addition the density calculation for each atom can be further parallelized by distributing the eigenvector on a certain subset of processors (usually 2-8). This is in principle not so efficient, but must be used if the memory requirement is too big (typically when lapw2 mpi crashes without reasons) or the network is slow and using more cpu-time but less network traffic is more efficient. Test it out for your hardware and specific case). You set it in.machines using lapw2 vector split:2 Otherwise, the parallelization follows that of lapw1 as specified in.machines, although the script uses.processes, which is created at the lapw1 step. nmr mpi in mode current supports the same parallelization strategy (mixed k-point and mpischeme) as lapw1 or lapw2. The keyword nmr integ: node1 node2... allows for an additional mpi-parallelization (over the atoms) in mode integ (see description in chapter 5.6). If more than one k-point is distributed at once to lapw1 mpi or lapw2 mpi, they will be treated consecutively. Depending on the parallel computer system and the problem size, speedups will vary to some extend. Matrix setup in lapw1 should scale nearly perfect, while diagonalization (using SCALA- PACK) will not. Usually, iterative scales better than full diagonalization and is preferred for large scale computations. Scalability over atoms will be very good if processor and atom numbers are compatible. Running the fine grained parallelization over a 100 Mbit/s or 1,Gbit/s Ethernet network is not recommended, even for large problem sizes. 5.6 Chemical shift NMR calculations Introduction The calculation of the magnetic shielding tensor σ is based on a linear response theory described in Laskowski et al. 2012a,b and In short, the calculation of the NMR shielding tensor requires eigenvectors computed at seven different k-meshes: original and shifted by q in +/- x,y,z direction, where q is small compared to the BZ size. Those eigenvectors are then used to compute the induced current and magnetic susceptibility. The induced current is afterwards integrated (Biot-Savart) to get the NMR shielding tensor. The script x nmr lapw helps you to performs all the necessary steps and together with the NMRprogram (see chapter 8.16) allows you to calculate the chemical shielding (and further the chemical shift with respect to some reference compound). It requieres a converged scf-calculation of your case (and for the time being, the system should be insulating, see below for Knight shifts)
100 82 CHAPTER 5. SHELL SCRIPTS The implemented method uses an enriched APW basis set (extended number of local orbitals, called NMR-LOs). The setup of NMR-LOs is communicated to other programs (for instance lapw1) via the filecase.in1 nmr file (case.in1c nmr for cases without inversion symmetry). Therefore after converging SCF or restoring a previously saved calculation, one has to create case.in1 nmr. The case.in1 nmr file should be generated using: x nmr lapw -mode in1 [parameters] The important parameter here is -nodes val, where val is an integer used to determine the number of NMR-LOs in each orbital quantum number l (see Laskowski,Blaha 2012a, 2014 for details). The default value (8) gives well a converged tensor, but it may also lead to an unnecessarily large basis size. In such cases the number of NMR-LOs may be reduced using a smaller number val (eg. 5), or by using -focus atom option that decreases the number of NMR-LOs for atoms other then the one specified. By default the algorithm implemented here adds NMR-LOs to the bases for all orbital numbers up to l+1, where l is the maximal explicitly specified orbital in case.in1. In a case where the magnetic susceptibility needs to be computed precisely, an l+2 limit may be necessary to reach full convergence. In such cases it is required to add an extra entrance for the next l-value in case.in1 with a default 0.3 linearization energy (eg. a l=2 line for an O atom). You may also consider to run x kgen and create a (finer) k-mesh for the NMR calculation (in any case, the k-point dependency of the NMR tensor should always be tested explicitly by at least 2 different k-meshes. After successful generation of a basic k-mesh and the case.in1 nmr file the NMR shielding tensor can be computed using: x nmr lapw [parameters] By default the x nmr script will execute sequentially the following steps (you don t need to call them explicitly): 1. shifted k-mesh generation based on the existing k-mesh generated previously x nmr lapw -mode klist 2. eigenvectors (lapw1) x nmr lapw -mode lapw1 In a case where spin-orbit coupling needs to be included ( x nmr -so ) the proper eigenvectors vectors are generated with: x nmr lapw -mode lapwso Similarly, for hybrid-dft calculations the eigenvectors will be computed by x nmr lapw -mode hf The eigenvectors are computed sequentially in subdirectories: nmr\_q0 (original k-mesh) nmr\_pqx (shifted in (+q,0,0) in Cartesian frame) nmr\_mqx (shifted in (-q,0,0) in Cartesian frame) nmr\_pqy (shifted in (0,+q,0) in Cartesian frame) nmr\_mqy (shifted in (0,-q,0) in Cartesian frame) nmr\_pqz (shifted in (0,0,+q) in Cartesian frame) nmr\_mqz (shifted in (0,0,-q) in Cartesian frame) If you are using a SCRATCH variable different from./, it is recommended to define a unique scratch directory with x nmr lapw -scratch /scratch/case A
101 5.6. CHEMICAL SHIFT NMR CALCULATIONS 83 in order to avoid collisions between multiple NMR calculations running simultaneously. 3. weight files x nmr lapw -mode lapw2 4. core wave functions x nmr lapw -mode lcore 5. induced current density and magnetic susceptibility x nmr lapw -mode current The current is written to case.current sp (x,y,z), case.current int (x,y,z), where x,y,z are the Cartesian directions of external magnetic field. The current density is UNSYMMETRIZED with respect to irreducible BZ. In order to get a symmetrized current for plotting purposes the full BZ sampling has to be used (x kgen -fbz). The magnetic susceptibility is written to case.xim. 6. integration of current density x nmr lapw -mode integ The full NMR tensor and other related quantities can be found in case.outputnmr integ. The isotropic chemical shift σ iso and its anisotropy is printed under the label :NMR- TOTxxx (in ppm) and :NMRASYxxx (Haeberlen convention): :NMRTOT001 ATOM: Te 1 NMR(total/ppm) Sigma-ISO= Sigma xx= Sigma yy= Sigma zz= :NMRASY001 ATOM: Te 1 NMR(total/ppm) ANISO(delta-sigma)= ASYM(eta) = SPAN= SKEW= The steps 1) to 6) are executed one after another by x nmr script, there is no need to run through them manually. However if there is need to recompute the current without changing eigenvectors (for analysis purposes), steps 5) and 6) can be executed using x nmr lapw -noinit Or when one needs to compute only initialization steps 1) to 4) x nmr lapw -initonly may be used Options All options of the x nmr script can be seen using: x nmr lapw -h -h/h -mode modeid print this message runs in specific mode given by modeid. If mode is not defined, runs sequence needed for actual calculations (klist,lapw1,[lapwso], lapw2, lcore, current, integ), however preceding execution in mode in1 is still required. modeid can be: in1 (initialize case.in1_nmr, adds extra LO) testval (testing case.in1_nmr) klist (initialize shifted k-lists ) lapw1 (executes lapw1) lapwso (executes lapwso, only after lapw1 step)
102 84 CHAPTER 5. SHELL SCRIPTS hf (runs hf on top of lapw1, only after lapw1 step) lapw2 (executes lapw2 for weights, only after lapw1, lapwso or hf) lcore (executes lcore) current (generate induced current) integ (integrates current and computes nmr shielding parameters) plot (plot of the induced current, uses extra input file case.innmrplot, generated automatically if not present) -noinit -initonly -so -orb -hf -hfdir subdir -redklist -diaghf executes mode current and integ executes modes klist, lapw1, [lapwso], lapw2, lcore executes mode lapwso adds LDA+U to lapw1 or lapwso executes mode hf between lapw1 and lapw2 (as this takes long time, you certainly should run this in parallel. If you have more cores, use -hf -hfdir [nmr_q0, nmr_pqx, nmr_mqx...] in parallel) prepares HF vectors (starting from lapw1 and ending with lcore) for the subdir=[q0, pqx, mqx,...]. It allows more parallelization as all "subdir"s can be run with a different.machines file in parallel. uses a reduced k-list (case.klist_rfbz) for the HF potential (note, the general HF k-mesh must be the same as in the scf) diagonal approximation to HF (only eigenvalues updated) -p run in k-point or mpi parallel mode -case name set the casename to name, otherwise the current dir name is used -up include spin polarisation (up spin) -dn include spin polarisation (dn spin) -save dir saves result in directory dir -scratch scratch_dir sets (and creates if necessary) the scratch directory for storing vectors Mode specific parameters (ignored by others): mode: in1 -nodes val number of nodes of the top radial function, default = 8 -focus val index or name of an atom of interest, if not set then all -ovlpmax val maximum allowed overlap between top (energy) radial function from in1 and NMR LO (default 0.6) mode: testval -up/dn include spin polarization (up/dn spin) -orb add LDA+U switch to lapw1 mode: klist -q val sets the q to value, if not defined uses default of mode: lapw1 / lapw2 / lapwso -p run in k-point or mpi parallel mode -up/dn include spin polarization (up/dn spin) -orb add LDA+U switch to lapw1 mode: hf -up/dn include spin polarization (up/dn spin) -hfdir subdir prepares HF vectors (starting from lapw1 up to lcore) for the subdir=[q0, pqx, mqx,...]. It allows additional parallelization as all "subdir"s can be run with a different
103 5.6. CHEMICAL SHIFT NMR CALCULATIONS 85 -redklist -diaghf.machines file in parallel. allows to use a reduced k-list (case.klist_rfbz) for the HF potential (note, the general HF k-mesh must be the same as in the scf) diagonal approximation to HF (only eigenvalues updated) the occupied states OS. Leaves only nonzero alm for iat and l. mode: current -up/dn include spin polarization (up/dn spin) -so use lapwso vectors -hf use hf vectors -emin val overrides the valence bands minimum -emax val overrides the valence bands maximum -iemin val sets lowest valence band to val -iemax val sets highest valence band to val -filt_cxyz_o iat l filter coupling matrix element(<os COUPOP ES>,make_cxyz) the occupied states <OS. Leaves only nonzero alm for iat and l ( FOP_oc>=SUM_es( ES><ES COUPOP OS>/(ENE_os-ENE_es) -filt_cxyz_q iat l filter in coupling matrix elements (<OS COUPOP ES>,make_cxyz) the empty states ES>. Leaves only nonzero alm for iat and l ( FOP_oc>=SUM_es( ES><ES COUPOP OS>/(ENE_os-ENE_es) -filt_curr_o iat l filter in current density (make_current_sp,j(r)=<os JOP FOP>) -filt_curr_fop iat l filter in current density (make_current_sp,j(r)=<os JOP FOP> the perturbation w-f FOP>. Leaves only nonzero alm for iat and l For all -filt_* if (iat.eq. 0) do only interstitial contribution For all -filt_* if (l.lt. 0) apply and sum all l channels -nocc do not add core states to the Green function -noduc do not add du (radial derivative of u) to the Green function -scissor val applies scissor shift to conduction bands -coreonly only core contribution -xionly calculate only macroscopic magnetic suszeptibility -noxi do not calculate macroscopic magnetic suszeptibility -fbz k-sampling uses full BZ (no symmetrization of xi) -scratch dir sets the scratch directory -metal should be set in case of metals, sets default kbt= kbt XX sets kbt for Fermi level smearing in metals for Green function mode: integ -nocore subtract core contribution -up/dn include spin polarization (up/dn spin) mode: plot (note: current is not symmetrized, must use full BZ sampling) -nocore subtract core contribution -up/dn include spin polarization (up/dn spin) Additional notes Parallelization : x nmr lapw -p will execute lapw1, lapw2 and x nmr -mode current -p in k-point parallel mode following the standard WIEN2k scheme. The standard.machines file is used in this case. A mixed k-point/mpi parallelization (if more then one core is assigned to one k-point) is also implemented for x nmr -mode current -p. The integration step x nmr -mode integ
104 86 CHAPTER 5. SHELL SCRIPTS -p supports mpi parallelization over atoms. In order to use it, the following line has to be added to the.machines file: nmr_integ: $proc_list where $proc list is a list of processors. NMR and hybrid DFT : It is possible to combine hybrid-dft and nmr calculations, but note that this is quite expensive, in particular because of additional NMR-local orbital AND the need for ALL eigenvalues, which makes the hf step MUCH more expensive than for a normal scf calculation (and we need calculations for 7 different k-meshes). We therefore recommend a good parallelization (if possible, over ALL k-points and in addition with mpi over the number of atoms/cell). After mode in1 run: x nmr lapw -p -hf or, if you have enough cores create several different.machines files and run the 7 directories in parallel: cp.machine q0.machines x nmr lapw -p -hfdir q0 & cp.machine pqx.machines x nmr lapw -p -hfdir pqx &... Metals : For paramagnetic metals, the Knight shift dominates usually the Chemical shift, which comes from the Fermi-contact term due to the spin-polarization at E F. The contact term can be calculated in an extra directory using a spin-polarized setup. First do a scf cycle using (runsp c lapw -cc (to obtain quickly a non-magnetic solution), then use runsp lapw -orb -cc , where you can apply an external field introducing a spin-polarization (see chapter 7.3). Typically you would apply magnetic fields of T and get the contact term from :HFFxxx. Please note: You need to check carefully the convergence with respect to k-mesh (huge meshes might be necessary). Of course, also the orbital contribution is non-negligible and one should also run x nmr -metal -kbt noxi. Please note: you will usually need an ENOURMOUS k-mesh (more than k-points), and also check convergence with respect to the -kbt 0.00x parameter in the line given above. This procedure excludes the contributions from both, the spin and orbital part of the macroscopic susceptibility, because we have found that this quantity is in most cases still an order of magnitude more difficult to converge. In principle you could run x nmr -noinit -metal -kbt 0.00x -xionly and check the corresponding susceptibility in case.xim. If you can reach convergence, you could add its contribution in the final integration using x nmr -mode integ. Analyses : x nmr lapw -p -noinit -emin xx [-emax yy] allows you to separate the contributions to the magnetic shielding according to the energy range (in Ry) of the valence bands (eg. the contributions from a p-band and a d-band,...). The switch -noinit runs only the modes current and integ. Additional analysis is possible with the -filt options, but requires some understanding of the underlying formalism (see the NMR papers by Laskowski, Blaha). Current plotting : You can also plot the induced current (it needs the dx Dataexplorer software), but since the current is not symmetrized, you need to run first with a full k-mesh. Use x kgen -fbz # for plotting purposes this can be on a smaller k-mesh x nmr lapw x nmr lapw -plot # prepares current.dx and current x/y/z.dx files current2dx lapw
105 5.7. WANNIER FUNCTIONS (WIEN2WANNIER) Wannier functions (wien2wannier) This program was contributed by: Wien2Wannier Version 1.0 by J.Kunes. P.Wisgott and E.Assmann. Please cite the following paper when using it: J.Kunes, R.Arita, P.Wissgott, A.Toschi, H.Ikeda, K.Held, Comp.Phys.Commun. 181, 1888 (2010) Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. wien2wannier is an interface program between WIEN2k and Wannier90 ( to obtain maximally localized Wannier functions from WIEN2k calculations. It provides the necessary overlap matrices for the construction of Wannier functions and besides some auxilliary programs it also contains a package for plotting the resulting Wannier functions in real space. With this interface, the whole world of Wannier90, i.e. applications which rely on maximally localized Wannier functions and the resulting hopping parameters (Transport, Berry phases (see Chapter 5.8), DMFT) can be combined with WIEN2k. Wannier90 must be installed separately from and should be cited when using it [Mostofi 2008] Usage This section contains only a very brief summary of wien2wannier. Please consult the detailed wien2wannier usersguide for more details, which is available from $WIENROOT/SRC w2w or the textbooks site at For a quick reference, see also the plain-text file CHEATSHEET in $WIENROOT/SRC w2w. Preparatory steps Before running wien2wannier, one needs a converged WIEN2k calculation. Additionally, during the setup for wien2wannier, the bands which are to be taken into account will have to be specified, and the main character (e.g., d bands on atom 2) of these bands should be known. To obtain this information, a combination of partial DOS and bandstructure, or a band character plot is often necessary (e.g. spaghettis fat bands option, or SpaghettiPrimavera and prima.py, available in the unsupported software section of the WIEN2k website). Converge a Wien2k calculation: run[sp sp c] OPTIONS obtain band structure and partial DOS identify target bands and band characters Then create a subdirectory with the necessary files using: prepare w2wdir TARGET which also gets the Fermi energy from case.scf (or case.scf2, if case.scf is not present (take care after x lapw2 -qtl -band!)) and change into this new directory TARGET.
106 88 CHAPTER 5. SHELL SCRIPTS Interface and Wannierization init w2w [-up -dn] generates various input files and performs the following steps: x kgen -fbz Prepares an unshifted k-mesh in the full BZ. Of course, the meshdensity influences the quality of localization of the Wannier functions. x findbands: looks in case.output1 for bands in a given energy range [E min ;E max ] (in ev with EF=0), and outputs the corresponding band indices b min ; b max. To choose the energy window of interest, consult the (partial) DOS and/or a band structure plot. write inwf: prepares the main input file case.inwf for the interface. The band indices b min ; b max have to be specified, and initial projections A mn may be given in terms of atomic sites and appropriate spherical harmonics. write win writes the input file case.win for wannier90.x on the basis of case.inwf and other files. x wannier90 -pp reads the k-mesh in case.win and writes a list of nearest-neighbor k-points to case.nnkp. x lapw1 OPTIONS: computes the eigenvectors on the full-bz k-mesh you may use.machines and -p, -up/-dn, -orb, you may also consider spin-orbit: x lapwso OPTION x w2w [-up -dn] [-p] [-so]: computes the overlaps M nm, initial projections A mn and eigenvalues E n, and writes them to case.mmn, case.amn, and case.eig. x wannier90 [-up -dn] [-so]: computes the U(k) by maximum localization. Output is stored in case.wout. The Wannier orbitals should be converged to a spread which is usually smaller than the unit cell of the structure. Verification and Postprocessing After a successful WANNIER90 run, one should check if the centers and spreads of the Wannier functions (printed in case.wout) are sensible. Another important consistency check is to compare the Wannier-interpolated bandstructure to the one computed by WIEN2k. wien2wannier also provides programs to create a real-space plot of the Wannier functions. compare band structures: With the option hr plot=t in case.win, WANNIER90 writes a bandstructure derived from the Wannier-interpolated Hamiltonian H(k) to case band.dat. To compare this to the bandstructure computed by spaghetti, you can use gnuplot, using the command (including a conversion from Bohr to Å) gnuplot case_band.dat \\ p case.spaghetti_ene u ($4/.53):5, case_band.dat w l The steps for plotting of Wannier functions are: write inwplot: asks for a real-space grid on which the Wannier functions should be plotted, and writes case.inwplot. x wplot -wf m [-up -dn][-p] [-so] evaluates Wannier function number m on the real-space grid, and writes the density w m (r) 2 to case m.psink and the phase argw m (r) to case m.psiarg. use positions from case.wout wplot2xsf converts all case*.psink and case*.psiarg files in the directory to the corresponding xsf files which can be opened by XCrySDen. It can also shift the origin according to case centres.xyz. xcrysden --xsf case m.xsf (or VESTA) visualizes the Wannier functions. Pick Tools - Data Grid from the menu and press OK. In the isosurface controls window choose an appropriate isovalue, e.g. 0.1, and check the Render +/- isovalue box.
107 5.8. SPONTANEOUS POLARIZATION, PIEZOELECTRICITY AND BORN CHARGES (BERRYPI) Help and FAQ Additional information about all programs can be accessed via the help flag, program -h. And of course, read the detailed wien2wannier userguide in $WIENROOT/SRC w2w. In particular there is a FAQ section, which may answer your question. 5.8 Spontaneous Polarization, Piezoelectricity and Born Charges (BerryPI) This program was contributed by: S.J. Ahmed, J. Kivinen, B. Zaporzan, L. Curiel, S. Pichardo, O. Rubel Thunder Bay Regional Research Institute, Ontario, Canada Computer Physics Communications 184, (2013) Sources also available from: Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. These calculations are based on the Modern Theory of Polarization (Berry Phase) pioneered by King-Smith 1993, Resta 1993, which noticed that (in a solid) we can only see a change of polarization P in response to an external perturbation, but not the polarization itself. BerryPI computes both, the ionic and electronic contributions to P using wien2wannier to obtain the overlap integral between two cell periodic parts of the Bloch functions. Of course, this theory applies only to insulators (semiconductors), but not for metals. For more details study the relevant literature (see the CPC paper mentioned above, which should be cited when this module is used in a publication) or the detailed tutorials at $WIENROOT/SRC BerryPI/BerryPI. A current limitation of this implementation is that the structures must have orthogonal lattice vectors. This also means that cubic F and B centered lattices must be converted into a P-type conventional supercell with 4 (2) times as many atoms as the primitive cell. As this should be applied to insulators only, you have to use the TETRA method for the BZ integration. In addition, parallel execution is not yet supported directly (see below) Options The program is called using berrypi -knx:ny:nz [-s -o -j -l] [-h] An online help of all options can be obtained with the -h switch. The parameter -knx:ny:nz is mandatory and determines the k-mesh for the BZ sampling. The additional switches -s allows spin-polarized calculations; -o supports additional orbital potentials (LDA+U or EECE); -j includes spin-orbit coupling (x lapwso); and -l skips the lapw1 run. The option -l can be used to make the most time consuming lapw1 step running in parallel. Execute x kgen -fbz ; x lapw1 -p and join vectorfiles case NUM before the call fo berrypi -l.
108 90 CHAPTER 5. SHELL SCRIPTS Spontaneous Polarization To obtain P one has to do two calculations, one for the unperturbed structure (λ 0 ) and one for the perturbed one (λ 1 ) and obtain P=P 1 -P 0. Start out with the distorted structure (eg. the ferroelectric phase of BaTiO 3 ) and perform a standard WIEN2k calculation. Then run the berrypi program: mkdir case;cd case;mkdir case0;mkdir case1 # create suitable directories cd case1 makestruct # create your structure init_lapw -b... # initialize wien2k run_lapw... # run scf cycle berrypi -k6:6:6 # run berrypi where -k defines a suitable k-mesh. This will give you the corresponding x,y,z components of the polarization as: ========================================================================= Value spin dir(1) dir(2) dir(3) Electronic polarization (C/m2) sp(1) [ e-12, e-13, e-01] Ionic polarization (C/m2) sp(1) [ e-11, e-11, e-01] Tot.spin polariz.=pion+pel(c/m2) sp(1) [ e-12, e-11, e-01] TOTAL POLARIZATION (C/m2) both [ e-12, e-11, e-01] ========================================================================== Now copy all files to the case0 directory, rename the files and change the struct file such that it corresponds to the undistorted (cubic) structure (keeping all other inputs identical: cd..;cp -r case1 case0;cd case0;rename_files case1 case0 edit case0.struct # create undistorted structure x dstart # new starting density run_lapw... # run scf cycle berrypi -k6:6:6 # run berrypi The spontaneous polarization in z-direction is defined as the difference in z component of polarization between the non-centrosymmetric P z (λ 1 ) and centrosymmetric structure P z (λ 0 ). In this case P z (λ 0 ) = 0 (output not shown) and the resultant spontaneous polarization is P s =0.31 C/m 2. Please consider the effects of possible π wrapping, so in general the smallest possible value should be considered. If there is a suspect of π-wrapping artifacts, it is useful to study intermediate structures (between λ 1 and λ 0 ) and ensure continuity in the evolution of P z Born effective charges The Born effective charge Zs,αβ of an atom s is defined as the change in polarization due to a displacement of its position. These charges are also used to estimate the LO/TO splitting of the optical vibrational modes at Γ. For the calculation of the Born effective charge of As in GaAs one has first to create a P -type supercell with 4 formula units/cell (see limitations above). One of the 4 As atoms has to be displaced along the z-axis from it s equilibrium position by +0.01(λ 1 ) and -0.01(λ 2 ) in fractional coordinates. Then perform (identical) WIEN2k calculations for the two structures and run berrypi -k6:6:6. The two calculations yield lines like:
109 5.8. SPONTANEOUS POLARIZATION, PIEZOELECTRICITY AND BORN CHARGES (BERRYPI)91 "lambda] ========================================================================== "lambda] ========================================================================== The total (ionic + electronic) phase along z-axis in the case of λ 1 and λ 2 is and rad, respectively. The Born charge can be obtained from these phases φ as Z zz = π 2 δφ z δρ z (5.1) where δρ is the relative displacement (0.02) in fractional coordinates. The calculation yields Z zz = The negative sign is indicative of a higher electronegativity of As as compared to that for Ga. Please consider the effects of possible π wrapping, so in general the smallest possible value should be considered Piezoelectric constants For such calculations you need to calculate the Berry phases for the reference (equillibrium) structure (e.g. the tetragonal ferroelectric PbTiO 3 structure) and a perturbed structure, where a compressive strain ɛ z of 0.1 % has been applied in the z-direction (for the latter structure one should also perform a new optimization of the internal coordinates).
110 92 CHAPTER 5. SHELL SCRIPTS The piezoelectric coefficient ε zz is defined as change in polarization with respect to the applied strain: ɛ zz = dp z dɛ z (5.2) 5.9 Getting on-line help As mentioned before, all WIEN2k csh-shell scripts have a help -switch -h, which gives a brief summary of all options for the respective script. To obtain online help on input-parameters, program description,... use help lapw which opens the pdf-version of the users guide (using acroread or what is defined in $PDF- READER). You can search for a specific keyword using f keyword. This procedure substitutes an Index and should make it possible to find a specific information without reading through the complete users guide. In addition there is a html-version of the UG and its starting page is: $WIENROOT/SRC usersguide html/usersguide.html When using the user interface w2web, you have access to the html and pdf-version (the latter requires an X-windows environment) of the usersguide. At our webserver we put informations for the registered user: A FAQ page with answers to some common problems. Update information: When you think the program has an error, please check wether newer versions are available, which might have fixed the problem you encounter. A mailing list: Please check the digest! In many cases your questions may have been answered before. Locate your problem: If a calculation crashes, please locate the problem. Check the content of files like case.dayfile, *.error, case.scf, case.scfx, case.outputx where X specifies the program which crashed. Posting questions: Please provide enough information so that somebody can help you. A question like: My calculation crashed. Please help me! will most likely not be answered Interface scripts We have included a few interface scripts into the current WIEN2k distribution, to simplify the previewing of results. In order to use these scripts the public domain program gnuplot has to be installed on your system eplot lapw The script eplot lapw plots total energy vs. volume or total energy vs. c/a-ratio or b/a-ratio using the file case.analysis. The latter should have been created with grepline (using :VOL and :ENE labels) or the Analysis Analyze multiple SCF-files menu of w2web and the file names must be generated (or compatible) with optimize.job. Alternatively you can use eplot lapw -a search-string-in-scf-files, which generates case.analysis automatically using the specified string. For a description of how to use the script for batch like execution call the script using
111 5.10. INTERFACE SCRIPTS 93 eplot lapw -h gibbs lapw The script gibbs lapw (provided by M. Jamal) is an extension of eplot lapw and can also plot Volume vs. Pressure curves as well as the Gibbs energy difference (stored in case.outputdeltag) of two different phases as function of Pressure. When interested in pressure driven phase transitions, one can do calculations for the two phases of interest in two different subdirectories and perform Volume optimization (using x optimize; optimize.job, see sec. 5.3). Once this has been finished, one can use gibbs lapw (instead of eplot lapw), which will also create case.outputeos meshp, eos.meshp1 and deos1 files. These files allow for a comparison of the Gibbs energy as function of pressure for the two different phases. A typical sequence to determine the transition pressure of this phase transition (assuming that the struct files and initializations have been done before) would look like: cd dir1 x optimize # select Volume optimization and a suitable volume range optimize.job # eventually change some run or save-options before gibbs lapw -v vol cd../dir2 x optimize # select Volume optimization and a suitable volume range optimize.job # eventually change some run or save-options before cp../dir1/eos.meshp1 eos.meshp2 cp../dir1/deos1 deos2 gibbs lapw -v vol For a description of how to use the script for batch like execution call the script using gibbs lapw -h which will yield: gibbs lapw [-v vol] [-a string in scf-files] [-plt/-gbs/-ene] For instance, gibbs lapw -a pbe will analyse all scf files *pbe.scf parabolfit lapw The script parabolfit lapw is an interface for a harmonic fitting of E vs. 2-4-dim lattice parameters by a non-linear least squares fit (eosfit6) using PORT routines. Once you have several scf calculations at different lattice parameters (usually generated with optimize.job) it generates the required case.ene and case.latparam from your scf files. Using parabolfit lapw [ -t 2/3/4 ] [ -f FILEHEAD ] [ -scf *xxx*.scf ] you can optionally specify the dimensionality of the fit or the specific scf-filenames.
112 94 CHAPTER 5. SHELL SCRIPTS dosplot lapw The script dosplot lapw plots total or partial Density of States depending on the input used by case.int and the interactive input. It can be used to generate all partial DOS plots in a simple way to get an overview. A more advanced plotting interface is provided by dosplot2 lapw, see below. For a description of how to use the script for batch like execution call the script using dosplot lapw -h dosplot2 lapw The script dosplot2 lapw plots total or partial Density of States depending on the input used by case.int and the interactive input. It can plot up to 4 DOS curves into one plot, and simultaneously plot spin-up/dn DOS. It supports also the SUM-DOS option (see description of TETRA. It was provided by Morteza Jamal (m modified by PB. For a description of how to use the script for batch like execution call the script using dosplot2 lapw -h You can also use the script dosplot all lapw [-up] to generate default-plots (4 lines per plot) of all partial DOS cases as defined in case.int Curve lapw The script Curve lapw plots x,y data from a file specified interactively. It asks for additional interactive input. It can plot up to 4 curves into one plot and is a simple gnuplot interface. It was provided by Morteza Jamal (m specplot lapw specplot lapw provides an interface for plotting X-ray spectra from the output of the xspec or txspec program. For a description of how to use the script for batch like execution call the script using specplot lapw -h rhoplot lapw The script rhoplot lapw produces a surface plot of the electron density from the file case.rho created by lapw5. Note: To use this script you must have installed the C-program reformat supplied in SRC reformat.
113 5.10. INTERFACE SCRIPTS prepare xsf lapw This program was contributed by: David Koller Institute for MaterialsChemistry TU Vienna Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. The script prepare xsf lapw produces 3D data of the electron density (or the potential) in XCrysDen-format (case.xsf) for plotting with XCrysDen (Menu Tools Data Grid). It is written in Python and also uses the programs lapw5 and str2xcr.exe (included in the WIEN2k distribution). It requires an input file case.inxsf: # This is an inxsf-file >D9 clmval # unit # 9 in def-file >D1 clmvaldn # unit # 11 in def File >IS # Start of end part of in5-file RHO ATU VAL NODEBUG # careful VAL/TOT!!! NONORTHO >IE # closes what was started with >IS >C # Start-Corner of part of unit cell (compared to lattice vectors of conventional cell) >CX # x-end >CY # y-end >CZ # z-end # use for fcc: #>C #>CX #>CY #>CZ # entire cell: #>C #>CX #>CY #>CZ >NX 30 # number of data points in x-direction >NY 30 >NZ 30 >IZ # additional cells in in5-file >PS # parallel start machine1 machine1 machine2 >PE # parallel end # >PM # End of inxsf-file In this file comments are designated by #. Markers at the beginning of a line consisting of > followed by two characters determine the content of this line or of the following lines, depending on the marker. Explanation of the markers: >D9: The suffix of the main data file. It corresponds to unit 9 in the file lapw5.def
114 96 CHAPTER 5. SHELL SCRIPTS >D1: The suffix of a second data file which can be optionally added to or subtracted from the main data file. It corresponds to unit 11 in the file lapw5.def >IS: This starts a section which needs to be closed with >IE. The lines between these two markers will be used as lines 6-8 in the in5-file. >IZ: This will be used as line 4 in the in5-file. >C0: Coordinates of a corner of a three-dimensional box, delimited by parallel planes, in which the data should be plotted. The units of these numbers are the unit vectors of the conventional cell (e.g is the centre of the xy-plane which would be the 1d-position in space group 111) >CX: Coordinates of the x-end corner of the box >CY: Coordinates of the y-end corner of the box >CZ: Coordinates of the z-end corner of the box >NX: Number of data points in x-direction >NY: Number of data points in y-direction >NZ: Number of data points in z-direction >PS / >PE / >PM: determine the parallelization This script also contains support for parallel execution. One possibility is to include >PM. In this case the file.machines is used to determine which hosts are used. More details can be found in the section about parallel WIEN2k. If >PM is not present (or commented) it is possible to specify the desired hosts between >PS and >PE. If neither >PM nor >PS are present, the script will be executed in non-parallel way which should work well enough in most cases opticplot lapw The script opticplot lapw produces XY plots from the output files of the optics package using the case.joint, case.epsilon, case.eloss, case.sumrules or case.sigmak. For a description of how to use the script for batch like execution call the script using opticplot lapw -h addjoint-updn lapw The script addjoint-updn lapw adds the files case.jointup and case.jointdn together and produces case.joint. It uses internally the program add columns. It should be called for spin-polarized optics calculations after x joint -up and x joint -dn, because the Kramers- Kronig transformation to the real part of the dielectric function (ɛ 1 ) is not a simple additive quantity concerning the spin (see Ambrosch-Draxl 06). The KK transformation should then be done non-spinpolarized (x kram) resulting in files: case.epsilon, case.eloss, case.sumrules or case.sigmak. This script can also be missused to add or subtract (add the keyword sub ) the content of case.jointup and case.jointdn, when they come from calculations of different band-ranges,...
115 6 Programs for the initialization Contents 6.1 NN SGROUP SYMMETRY LSTART KGEN DSTART In sections ( ) we describe the initial utility programs. These programs are used to set up a calculation. 6.1 NN (nearest neighbor distances) This program uses the case.struct file (see 4.3) in which the atomic positions in the unit cell are specified, calculates the nearest neighbor distances of all atoms, and checks that the corresponding atomic spheres (radii) are not overlapping. If an overlap occurs, an error message is shown on the screen. In addition, the next nearest-neighbor distances up to f times the nearest-neighbor distance (f must be specified interactively) are written to an output file named case.outputnn. For negative f values only the distances of non-equivalent atoms are printed., but equivalent ones are not listed again. Optionally one can specify also a dlimit parameter, which helps nn to find equivalent atoms in case of inaccuarate structural data. It is highly recommended in most cases that you change your sphere sizes and do NOT use the default of 2.0. An increase from 2.0 to 2.1 may already result in drastically reduced computing time. More recommendations are given in chapter 4.3. nn also checks if equivalent atoms are specified correctly in case.struct. At the bottom of case.outputnn the coordination shell-structure is listed and from that a comparison with the input is made verifying that equivalent atoms really have equivalent environments. If this is not the case, an ERROR will be printed and a new structure file case.struct nn is generated. You have to recheck your input and then decide whether you want to accept the new structure file, or reject it (because the equivalency may just be an artefact due to a special choice of lattice parameters). It also may be that you have made a simple input error. If you want to force two atoms of the same kind (e.g. 2 Fe atoms) to be nonequivalent (e.g. because you want to do an antiferromagnetic calculation), label the atoms as Fe1 and Fe2 in case.struct. Thus this program helps to generate proper struct-files especially in the case of artificial unit cells, e.g. a supercell simulating an impurity or a surface. It also prints the bond-valences (see also the comments in $WIENROOT/SRC nn/bva). 97
116 98 CHAPTER 6. INITIALIZATION Execution The program nn is executed by invoking the command: nn nn.def or x nn 6.2 SGROUP This program was contributed by: Bogdan Yanchitsky and Andrei Timoshevskii Institute of Magnetism, Kiev, Ukraine and Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. It was published in Yanchitsky and Timoshevskii 2001, and is written in C. This program uses information from case.struct (lattice type, lattice constants, atomic positions) and determines the spacegroup as well as all pointgroups of non-equivalent sites. It uses the nuclear charges Z or the label in the 3rd place of the atomic name (Si1, Si2) to distinguish different atoms uniquely. It is able to find possible smaller unit cells, shift the origin of the cell and can even produce a new struct file case.struct sgroup based on your input case.struct with proper lattice types and equivalency. It is thus most useful in particular for handmade structures. For more information see also the README in SRC sgroup Execution The program sgroup is executed by invoking the command: sgroup -wi case.struct [-wo case.struct sgroup] case.outputsgen or x sgroup 6.3 SYMMETRY This program uses information from case.struct (lattice type, atomic positions). If NSYM was set to zero it generates the space group symmetry operations and writes them to case.struct st to complete this file. Otherwise (NSYM > 0) it compares the generated symmetry operations with the already present ones. If they disagree a warning is given in the output. In addition the point group of each atomic site is determined and the respective symmetry operations and LM values of the lattice harmonics representation are printed. The latter information is written into case.in2 sy, while the local rotation matrix, the positive or negative IATNR values and the proper ISPLIT parameter are written to case.struct st. (See appendix A and Sec. 4.3).
117 6.4. LSTART Execution The program symmetry is executed by invoking the command: symmetry symmetry.def or x symmetry 6.4 LSTART (atomic LSDA program) lstart is a relativistic atomic LSDA code originally written by Desclaux (69, 75) and modified for the present purpose. Internally it uses Hartree atomic units, but all output has been converted to Rydberg units. lstart generates atomic densities which are used by dstart to generate a starting density for a scf calculation and all the input files for the scf run: in0, in1, in2, inc and inm (according to the atomic eigenvalues). In addition it creates atomic potentials (which are truncated at their corresponding atomic radii and could be used to run lapw1) and optional atomic valence densities, which can be used in lapw5 for a difference density plot. The atomic total energies are also printed, but it can only be used for cohesive energy calculations of light elements. Already for second-row elements the different treatment of relativistic effects in lstart and lapwso yields inconsistent data and you must calculate the atomic total energy consistently by a supercell approach via a bandstructure calculation (Put a single atom in a sufficiently large fcc-type unit cell). If the program stops with some lines: NSTOP=... in case.outputst, this means, that a proper solution for at least one orbital could not be obtained. In such a case the input must be changed and one should provide different occupation numbers for these states (e.g. Cu can not be started with 3d 10 4s 1, but it works with 3d 9 4s 2 ). The program produces WARNINGS if R0 is too big or core-density leaks out of RMT Execution The program lstart is executed by invoking the command: lstart lstart.def or x lstart [-sigma] The files case.rsp(up dn) are generated and contain the atomic (spin) densities, which will be used by DSTART later on. Using -sigma generates case.inst sigma with modified input to generate case.sigma used for difference densities (see below) Dimensioning parameters The following parameters are defined in file param.inc (static and not allocatable arrays): NPT total number of radial mesh points, must be gt.(nrad+npt00), where NRAD is the number of mesh-points up to RMT specfied in case.struct. NPT00 max. number of radial mesh points beyond RMT RMAX0 max. distance of radial mesh
118 100 CHAPTER 6. INITIALIZATION Input When running lstart you will first be asked interactively to specify an XC-potential switch. Currently 5 (LSDA, Perdew and Wang 92) as well as 11, 13 and 19 (three GGAs, Wu,Cohen 06; the standard PBE Perdew et al. 96, as well as PBEsol, Perdew et al. 08; respectively) are officially supported, 13 is the standard PBE-GGA. In addition the program asks for an energy cut-off, separating core from valence states. Usually -6.0 Ry is a good choice, but you should check for each atom how much core charge leaks out of the sphere (WARNINGS in case.outputs). If this is the case one should lower this energy cut-off and thus include these low lying states into the valence region. Alternatively you can also select a charge localization criterium (usually between 0.97 and ). This allows a more localized state (like a 4f of 5d elements) to be core, while a more delocalized state at lower energy (like the 5p states of 5d elements) to be semi-core. The rest of the input is described in the sample input below. Note: Only the data at the beginning of the line are read whereas the comment describes the respective orbitals. This file can be generated automatically in w2web during Initialize calc. or using SinglePrograms instgen lapw or with the script instgen lapw. To edit this file by hand choose View/Edit Input Files and choose case.inst top of file: case.inst ZINC Ne 6 (inert gas, # OF VALENCE ORBITALS not counting spin) 3,-1,1.0 N ( N,KAPPA,OCCUP; = 3S UP, 1 ELECTRON) 3,-1,1.0 N 3S DN 3,-2,2.0 N 3P UP 3,-2,2.0 N 3P DN 3, 1,1.0 N 3P*UP 3, 1,1.0 N 3P*DN 3,-3,3.0 P 3D UP 3,-3,3.0 P 3D DN 3, 2,2.0 P 3D*UP 3, 2,2.0 P 3D*DN 4,-1,1.0 P 4S UP 4,-1,1.0 P 4S DN **** END OF Input **** END OF Input bottom of file Interpretive comments follow: line 1: format(a4,a6) title, keyword title keyword The keyword Watson enables a stabilization of negative ions using a Watson -sphere of radius R-wat with charge Q-wat, which must be given in the next line when this keyword is specified. The keyword PRATT enables a scf mixing using standard PRATT scheme. It might be useful if a certain atomic configuration does not converge with the standard mixing scheme and requires a (usually quite small) mixing factor, which must be given in the next line when this keyword is specified. line 2: free format config
119 6.5. KGEN 101 config specifies the core state configuration by an inert gas (He, Ne, Ar, Kr, Xe, Rn) and the number of (valence) orbitals (without spin). (In the example given above one could also use Ar 3 and omit the 3s and 3p states.) The atomic configurations are listed in the appendix and can also be found online using periodic table, a shell script which displays SRC/periodic.ps with ghostview) line 3: format(i1,1x,i2,1x,f5.3,a1) n, kappa, occup, plot n kappa occup plot the principle quantum number the relativistic quantum number (see below) occupation number (per spin) P specifies that the density of the respective orbital is written to the file case.sigma, which can be used for difference density plots in lapw5. N or an empty field will exempt density of the respective orbital from being printed to file. >>>:line 3 is repeated for the other spin and for all orbitals specified above by config. >>>: the last two lines must be **** **** optional inserted as line 2 when Watson has been specified in line 1: free format R-wat, Q-wat R-wat radius of a charged sphere used to stabilize otherwise unstable negative ions (e.g. 2.5 for O 2 ) Q-wat charge of the stabilizing sphere, (e.g. 2 for O 2 ) The quantum numbers are defined as follows (see e.g. Liberman et al 65): Spin quantum number: s = +1 or s = 1 Orbital quantum number j = l + s/2 Relativistic quantum number κ = s(j + 1/2) j = l + s/2 κ max. occupation l s = 1 s = +1 s = 1 s = +1 s = 1 s = +1 s 0 1/2-1 2 p 1 1/2 3/ d 2 3/2 5/ f 3 5/2 7/ Table 6.6: Relativistic quantum numbers 6.5 KGEN (generates k mesh) This program generates the k-mesh in the irreducible wedge of the Brillouin zone (IBZ) on a special point grid, which can be used in a modified tetrahedron integration scheme (Blöchl et al 1994). kgen needs as interactive input the total number of k-points in the BZ. If this is set to zero, you are asked to specify the divisions of the reciprocal unit-cell vectors (3 numbers, be careful not to break symmetry and choose them properly according to the inverse lenght of the reciprocal
120 102 CHAPTER 6. INITIALIZATION lattice vectors) for a mesh yourself. If inversion symmetry is not present, it will be added automatically unless you specified the -so switch (for magnetic cases with spin-orbit coupling). The k-mesh is then created with this additional symmetry. If symmetry permits, it further asks whether or not the k-mesh should be shifted away from high symmetry directions. The file case.klist is used in lapw1 and case.kgen is used in tetra and lapw2, if the EF switch is set to TETRA, i.e. the tetrahedron method for the k-space integration is used. For the format of the case.klist see page Execution The program kgen is executed by invoking the command: kgen kgen.def or x kgen [-so -fbz -hf] With the switch -so it uses a file case.ksym (usually generated by symmetso) instead of case.struct and does not add inversion symmetry. The -fbz switch generates a k-mesh in the full Brillouinzone (no symmetry) Dimensioning parameters The following parameters are used in main.f, ord1.f (static arrays): IDKP NWX INDEXM number of inequivalent k-points (like NKPT in other programs) internal parameter, must be increased for very large k-meshes internal parameter, must be increased for very large k-meshes 6.6 DSTART (superposition of atomic densities) This program generates an initial crystalline charge density case.clmsum by a superposition of atomic densities (case.rsp) generated with lstart. Information about LM values of the lattice harmonics representation and number of Fourier coefficients of the interstitial charge density are taken from case.in1 and case.in2. In the case of a spin-polarized calculation it must also be run for the spin-up charge density case.clmup and spin-down charge density case.clmdn Execution The program dstart is executed by invoking the command: dstart dstart.def or x dstart [-up dn -c -fft -super -lcore -p] With the switch -fft dstart will terminate after case.in0 std has been created. The switch -super will produce new super.clmsum instead of case.clmsum, which is necessary for charge extrapolation (clmextrapol lapw). -lcore produces case.clmsc from the radial core densities case.rsplcore (this is activated during scf when a.lcore file is present. It can run in mpi-parallel mode (-p) for big cases (typically more than 20 atoms) and core-superposition Dimensioning parameters The following parameters are collected in file module.f, but usually need not to be changed:
121 6.6. DSTART 103 NPT LMAX2 NCOM number of r-mesh points in atomic density (should be the same as in LSTART) max l in LM expansion number of LM terms in density
122 104 CHAPTER 6. INITIALIZATION
123 7 Programs for running an SCF cycle Contents 7.1 LAPW DFTD ORB HF LAPW LAPWSO LAPW SUMPARA LAPWDM LCORE MIXER In sections we describe the main programs to run an SCF cycle as illustrated in figure LAPW0 (generates potential) lapw0 computes the total potential V tot as the sum of the Coulomb V c and the exchange-correlation potential V xc using the total electron (spin) density as input. It generates the spherical part (l=0) as case.vsp and the non-spherical part as case.vns. For spin-polarized systems, the spindensities case.clmup and case.clmdn lead to two pairs of potential files. These files are called: case.vspup, case.vnsup and case.vspdn, case.vnsdn. The Coulomb potential is calculated by the multipolar Fourier expansion introduced by Weinert (81). Utilizing the spatial partitioning of the unit cell and the dual representation of the charge density [equ. 2.10], firstly the multipole moments inside the spheres are calculated (Q-sp). The Fourier series of the charge density in the interstitial also represent SOME density inside the spheres, but certainly NOT the correct density there. Nevertheless, the multipole moments of this artificial plane-wave density inside each sphere are also calculated (Q-pw). By subtracting Q-pw from Q-sp one obtains pseudo-multipole moments Q. Next a new plane-wave series is generated which has two properties, namely zero density in the interstitial region and a charge distribution inside the spheres that reproduces the pseudo-multipole moments Q. This series is added to the original interstitial Fourier series for the density to form a new series which has two desirable properties: it simultaneously represents the interstitial charge density AND it has the same multipole moments inside the spheres as the actual density. Using this Fourier series the interstitial Coulomb potential follows immediately by dividing the Fourier coefficients by K 2 (up to a constant). Inside the spheres the Coulomb potential is obtained by a straightforward classical Green s function method for the solution of the boundary value problem. 105
124 106 CHAPTER 7. SCF CYCLE The exchange-correlation potential is computed numerically on a grid. Inside the atomic spheres a Gauss-Legendre integration is used to reproduce the potential using a lattice harmonics representation. In the interstitial region a 3-dimensional fast Fourier transformation (FFT) is used. The total potential V is obtained by summation of the Coulomb V C and exchange-correlation potentials V xc. In order to find the contribution from the plane wave representation to the Hamilton matrix elements we reanalyze the Fourier series in such a way that the new series represents a potential which is zero inside the spheres but keeps the original value in the interstitial region and this series is put into case.vns. The contribution to the total energy which involves integrals of the form ρ V is calculated according to the formalism of Weinert et al (82). The Hellmann-Feynman force contribution to the total force is also calculated (Yu et al 91). Finally, the electric field gradient (EFG) is calculated in case you have an L=2 term in the density expansion. The EFG tensor is given in both, the local-rotation-matrix coordinate system, and then diagonalized. The resulting eigenvectors of this rotation are given by columns. For surface calculations the total and electrostatic potential at z=0 and z=0.5 is calculated and can be used as energy-zero for the determination of the workfunction. (It is assumed that the middle of your vacuum region is either at z=0 or z=0.5) Execution The program lapw0 is executed by invoking the command: lapw0 lapw0.def or x lapw0 [ -p -eece -grr] Dimensioning parameters The following parameters are used (they are collected in file param.inc, but usually need not to be changed: NCOM number of lm components in charge density and potential representation; it must satisfy the following condition: NCOM+3.gt. {[number of l, m with m = 0] + [2 * number of l, m with m > 0]} NRAD number of radial mesh points LMAX2 highest L in the LM expansion of charge and potential LMAX2X highest L for the gpoint-grid in the xcpot generation (may need large values for -eece ) restrict output for mpi-jobs, limits the number of case.output0xxx files to restrict output Input The input is very simple. It is generated automatically by init lapw, and needs to be changed only if a different exchange-correlation potential should be used: top of file: case.in TOT XC_PBE! MULT/COUL/EXCH/POT /TOT ; VXC-SWITCH NR2V IFFT 8! R2V EECE/HYBR IFFT LUSE ! min IFFT-parameters, enhancement factor, iprint (#of FK in E-field expansion, EFELD (Ry) bottom of file
125 7.1. LAPW0 107 Interpretive comments follow: line 1: free format switch, indxc, xc1 switch indxc TOT total energy contributions and total potential calculated KXC total energy contributions and total potential calculated. In addition the kinetic energy contribution as well as the XC-energy will be printed. POT total potential is calculated, but not the total energy MULT multipole moments calculated only COUL Coulomb potential calculated only EXCH exchange correlation potential calculated only NOTE: MULT, COUL, and EXCH are for testing only, whereas POT, saves some CPU time if total energy is not needed keyword(s) to specify type of exchange and correlation potential. The most common options are listed below (for all options see Table 7.3 below), the description in sections about full-hybrid functionals (4.5.8) or Onsite-exact-exchange for correlated electrons (4.5.7) or the SRC lapw0/vxclm2.f subroutine): XC LDA Perdew and Wang 92, parameterization of Ceperly-Alder data, the recommended LDA option (former option 5) XC PBE Generalized Gradient approximation PBE by Perdew-Burke-Ernzerhof 96 (former option 13) XC WC Generalized Gradient approximation (Wu-Cohen 2006, Tran et al. 2007)(former option 11) XC PBESOL Generalized Gradient approximation (PBEsol, Perdew 2008) (former option 19) XC MGGA MS probably best Meta-GGA (energy functional only, uses PBE for the potential) up to now (Sun et al. 2013). In order to generate the requiered case.vresp* files, you need case.inm vresp (cp $WIENROOT/SRC templates/template.inm vresp case.inm vresp and run one scf cycle with XC PBE after creation of case.inm vresp. Only afterwards change indxc to XC MGGA MS. In addition you must use very large IFFT parameters, otherwise it might be numerically unstable. XC REVTPSS Meta-GGA RevTPSS (Perdew et al. 2009). (V XC of PBESOL, see also the notes in previous option above.) (former option 29) XC MBJ modified Becke-Johnson (mbj-lda) potential V XC (Tran and Blaha 2009). Uses the mbj-exchange + LDA-correlation potential and yields gaps in very good agreement with experiment. The xc-energy E XC is from LDA. For detailed usage see chapter about mbj calculations (4.5.9). EX SWITCH EC SWITCH VX SWITCH VC SWITCH (up to) four keywords for XC-energies and potentials, where SWITCH has to be replaced by some keyword:
126 108 CHAPTER 7. SCF CYCLE xc1 NONE, LDA, PBE, WC (EX,VX), PBESOL, PKZB (EX,EC meta-gga of Perdew 1999), PW91, EV93 (EX,VX, Engel-Vosko 1993), RPBE (EX,VX), B88 (EX,VX), AM05, SOGGA (EX,VX), MPBE, LYP (EC,VC), TPSS (EX,XC), REVTPSS (EX,EC), S (VX, reduced density gradient s, for plotting only), RS (VX, r s value for plotting only), LAPRHO (VX, 2 ρ for plotting only), TAU-TAUW (VX, kinetic energy density difference for plotting only), TAU (VX, kinetic energy density for plotting only), Z (VX, inhomogeneity measure for plotting only), VSXC (EX,EC), AK13 (EX,VX), HTBS (EX,VX, see Haas 2011), GRR (EX,VX, average of ρ/ρ), and screened-hybrid-dft options for VX,EX (SLDA, SPBE, SWC, SPBESOL, SB88). (see also Table 7.3 below) optional inputs for certain XC options: XC MGGA MS: xc1 = XC LDA or XC PBE: to modify the spin scaling (reduction of spinpolarization) according to (Ortenzi et al. 2012). xc1 must be between 0 and 2. OPTION EX SWITCH EC SWITCH VX SWITCH VC SWITCH VRESP GGA AEQ XC LDA EX LDA EC LDA VX LDA VC LDA.false..false..true. XC PBE EX PBE EC PBE VX PBE VC PBE.false..true..true. XC WC EX WC EC PBE VX WC VC PBE.false..true..false. XC PBESOL EX PBESOL EC PBESOL VX PBESOL VC PBESOL.false..true..true. XC MBJ EX LDA EC LDA VX MBJ VC MBJ.true..true..false. XC REVTPSS EX REVTPSS EC REVTPSS VX PBESOL VC PBESOL.true..true..false. XC MGGA MS EX MGGA MS EC MGGA MS VX PBE VC PBE.true..true..false. XC B3LYP EX B3LYP EC B3LYP VX B3LYP VC B3LYP.false..true..true. XC B3PW91 EX B3PW91 EC B3PW91 VX B3PW91 VC B3PW91.false..true..true. Table 7.3: XC shortcut-switches line 2: free format (only blanks are allowed as separator) RPRINT, H-mod, FFTopt, LUSE RPRINT NR2V no additional output R2V Exchange-correlation (case.r2v), Coulomb (case.vcoul) and total potentials (case.vtotal) are written as (r 2 V ) to a file for plotting with lapw5 (cp case.vtotal case.clmval; use VAL for normalization in case.in5) H-mod EECE Onsite Hartree-Fock (inside spheres) for selected electrons (see 4.5.7) HYBR Onsite Hybrid functionals (inside spheres) (see 4.5.7) FFTopt IFFT optional keyword, which lets you define the IFFTx mesh and an enhancement factor in the next line (necessary for runeece lapw) LUSE optional l-max value for the angular grid used in xcpot1. For standard LDA/GGA the recommended value is max L value of LM-list in case.in2 + 2; for EECE one should use a better, antialiased grid, thus a large negative LUSE-value is recommended (and set automatically by runeece lapw) line 3: free format (must be omitted when IFFT is not specified above) IFFTx, IFFTy, IFFTz, IFFTfactor, iprint
127 7.2. DFTD3 109 IFFTx,y,z IFFTfactor iprint FFT-mesh parameters in x,y,z directions for the calculation of the XC-potential in the interstitial region. Usually set automatically in init lapw (dstart). The ratio of the 3 numbers should be indirect proportional to the lattice parameters. ( determines these numbers automatically and takes only IFFTfactor into account) Multiplicative factor to the IFFT grid specified above. It needs to be enlarged for highly accurate GGA or meta-gga calculations as well as for systems with H atoms with small spheres. optional print switch. iprint=0 will greatly reduce case.output0 (in particular for lapw0 mpi). The following line is optional and can be omitted. It is used to introduce an electric field via a zig-zag potential (see J.Stahn et al. 2001): line 4: free format IFIELD, EFIELD, WFIELD IFIELD number of Fourier coefficients to model the zig-zag potential. Typically use IEFIELD=30; -999 lists available modes (form) of fields, and these modes can be specified by mode=iefield/1000. (default: mode=0) EFIELD value (amplitude) of the electric field. The electric field (in Ry/bohr) corresponds to EFIELD/c, where c is your c lattice parameter. WFIELD optional value for lambda (see output of IEFIELD=-999). 7.2 DFT-D3 (Calculate the dispersion energy with DFT-D3) Execution The program dftd3 is executed by invoking the command: x dftd Input The options for the dftd3 package have to be specified in the input file case.indftd3. If no input file is created by the user, then the script run(sp) lapw will automatically copy the default one (which is the recommended one) from $WIENROOT/SRC templates/: top of file: case.indftd method bj func default grad yes pbc yes abc no cutoff 95 cnthr 40 num no bottom of file:
128 110 CHAPTER 7. SCF CYCLE A short summary of the options is given below and more details can be found in the file man.pdf included in the dftd3 TAR file. Note that case.indftd3 is read by the C-SHELL script and that all data should be written in small letters. method : choice of the DFT-D method: bj (the recommended one), zero or old. func <functional> : three choices are possible: (a) default, which means the functional specified in case.in0 (possible only if the parameters s 6, s 8, etc. for this functional are available), (b) one of the functionals listed in the FORTRAN file dftd3.f (e.g., pbe or b-lyp) or (c) none, which means that the parameters s 6, s 8, etc. are read from the file.dftd3par.hostname created by the user in his home (not working) directory. Note that for hybrid functionals, it is mandatory to specify the functional name (default will not work). grad : yes or no for the calculation of the forces on the nuclei (necessary for the minimization of internal parameters). pbc : yes or no for periodic boundary conditions (pbc). It should be no for an isolated atom or molecule in a big box. abc : yes or no for the calculation of the three-body dispersion contribution with DFT-D3. cutoff <value> : The cutoff for the dispersion interaction. The default is 95 bohr. cnthr <value> : The cutoff for the coordination number CN. The default is 40 bohr. num : yes or no for the numerical (instead of analytical) calculation of forces. 7.3 ORB (Calculate orbital dependent potentials) This program was contributed by: P.Novák Inst. of Physics, Acad.Science, Prague, Czeck Republic Please make comments or report problems with this program to the WIEN-mailinglist. we will communicate the problem to the authors. If necessary, orb calculates the orbital dependent potentials, i.e. potentials which are nonzero in the atomic spheres only and depend on the orbital state numbers l, m. In the present version the potential is assumed to be independent of the radius vector and needs the density matrix calculated in lapwdm. Four different potentials are implemented in this package: LDA+U. There are three variants of this method, two of them are discussed in Novák et al LDA+U(SIC) - introduced by Anisimov et al. 1993, with an approximate correction for the self-interaction correction. This is probably best suited for strongly correlated systems and for a full potential method we recommend to use an effective U eff = U J; setting J = LDA+U(AMF) - introduced by Czyzyk and Sawatzky 1994 as Around the Mean Field method. (In Novák et al it is denoted as LDA+U(DFT)). This version is (probably) more suitable for metallic or less strongly correlated systems. 3. LDA+U(HMF) - in addition the Hubbard model in the mean field approximation, as introduced by Anisimov et al is also implemented. Note, however, that it is to be used with the LDA (not LSDA) exchange-correlation potential in spin polarized calculations!
129 7.3. ORB 111 All variants are implemented in the rotationally invariant way (Liechtenstein et al. 1995). If LDA+U is used in an unrestricted, general way, it introduces an orbital field in the calculation (in analogy to the exchange field in spin-polarized calculations, but it interacts with the orbital, instead of spin momentum). The presence of such an orbital field may lower the symmetry. In particular the complex version of LAPW1 must be used. Care is needed when dealing with the LDA+U orbital field. It may be quite large, and without specifying its direction it may fluctuate, leading to oscillations of scf procedure or/and to false solutions. It is therefore necessary to use it in combination with the spin-orbit coupling, preferably running first LSDA+(s-o) and then slowly switching on the LDA+U orbital field. If the LDA+U orbital polarization is not needed, it is sufficient to run real version of LAPW1, which then automatically puts the orbital field equal to zero. For systems without the center of inversion, when LAPW1 must be complex, an extra averaging of the LDA+U potential is necessary. Orbital polarization. The additional potential has the form (Brooks 1985, Eriksson et al. 1989): V OP = c OP < L z > l z (7.1) where c OP is the orbital polarization parameter, < L z > is projection of the orbital momentum on the magnetization direction and l z is single electron orbital momentum component z parallel to M. Exact exchange and Hybrid methods: see Tran et al and Interaction with the external magnetic field. In this case the additional potential has a simple form: V Bext = µ B Bext ( l + 2 s). (7.2) The interaction with the electronic spin is taken into account by shifting the spin up and spin down exchange correlation potentials in LAPW0 by the energy +µ B B ext µ B B ext, respectively. The interaction of B ext with spin could be as well calculated using the Fixed spin moment method. For an interaction with the orbital momentum it is necessary to specify the atoms and angular momentum numbers for which this interaction will be considered. Caution is needed when considering interaction of the orbital momentum with B ext in metallic or metallic-like systems. For the analysis see the paper by Hirst 1997 In all cases the resulting potential for a given atom and orbital number l is a Hermitian, (2l + 1)x(2l + 1) matrix. In general this matrix is complex, but in special cases it may be real. For more information see also section Execution The program orb is executed by invoking the command: x orb [ -up/-dn/-du ] or orb up/dnorb.def Dimensioning parameters The following parameters are used (collected in file param.inc): LABC NRAD highest l+1 value of orbital dependent potentials number of radial mesh points Input Since this program can handle three different cases, examples and descriptions of case.inorb for all cases are given below:
130 112 CHAPTER 7. SCF CYCLE Input for all potentials line 1: free format nmod,natorb,ipr nmod natorb ipr defines the type of potential 1...LDA+U, 2...OP, 3...B ext number of atoms for which orbital potential V orb is calculated printing option, the larger ipr, the longer the output line 2: (A5,f8.2) mixmod,amix mixmod PRATT or BROYD (should not be changed, see MIXER for more information) amix coefficient for the Pratt mixing of V orb This option is now only used for testing. The mixing should be set to PRATT, 1.0 line 3: free format iatom(i),nlorb(i),(lorb(li,i),li=1,nlorb(i)) iatom nlorb lorb index of atom in struct file number of orbital moments for which Vorb shall be applied orbital numbers (repeated nlorb-times) 3rd line repeated natorb-times Input for LDA+U (nmod=1) line 4: free format nsic defines double counting correction nsic=0 AMF method (Czyzyk et al. 1994) nsic=1 SIC method (Anisimov et al. 1993, Liechtenstein et al. 1995) nsic=2 HMF method (Anisimov et al. 1991) line 5: free format U(li,i), J(li,i) Coulomb and exchange parameters, U and J, for LDA+U in Ry for atom type i and orbital number li. We recommend to use U eff only. 5th line repeated natorb-times, for each natorb repeated nlorb-times Example of the input file for NiO (LDA+U included for two inequivalent Ni atoms that have indexes 1 and 2 in the structure file): top of file: case.inorb nmod, natorb, ipr PRATT,1.0 mixmod, amix iatom nlorb, lorb iatom nlorb, lorb 1 nsic (LDA+U(SIC) used) U J U J bottom of file:
131 7.3. ORB 113 Input for Orbital Polarization (nmod=2) line 4: (free format) nmodop defines mode of OP 1 average L z taken separately for spin up, spin down 0 average L z is the sum for spin up and spin down line 5: (free format) Ncalc(i) 1 Orb.pol. parameters are calculated ab-initio 0 Orb.pol. parameters are read from input this line is repeated natorb-times line 6: (free format) (only if Ncalc=0, then repeated nlorb-times) pop(li,i) OP parameter in Ry line 7: (free format) xms(1), xms(2), xms(3) direction of magnetization expressed in terms of lattice vectors Example of the input file for NiO (total < L z > used in (1), OP parameters calculated ab-initio, M along [001]): top of file: case.inorb nmod, natorb, ipr PRATT, 1.0 mixmod, amix iatom nlorb, lorb iatom nlorb, lorb 0 nmodop 1 Ncalc 1 Ncalc direction of M in terms of lattice vectors bottom of file Input for interaction with B ext (nmod=3) line 4: (free format) B ext external field in Tesla line 5: (free format) xms(1), xms(2), xms(3) direction of magnetization expressed in terms of lattice vectors Example of the input file for NiO, (B ext = 4 T, along [001]): top of file: case.inorb nmod, natorb, ipr PRATT, 1.0 mixmod, amix iatom nlorb, lorb iatom nlorb, lorb 4. Bext in T direction of Bext in terms of lattice vectors bottom of file
132 114 CHAPTER 7. SCF CYCLE 7.4 HF (Calculates the hybrid orbitals and eigenvalues) hf calculates the orbitals and eigenvalues for hybrid functionals using the second-variational procedure, i.e., the semilocal orbitals generated by lapw1 are used as basis functions for the secondvariational Hamiltonian (Tran and Blaha 2011). The hybrid orbitals are stored in case.vectorhf (full Brillouin zone). Since calculations with hybrid functionals are much more expensive than with semilocal functionals, it is important to choose carefully the values of the various parameters (nband, gmax, lmaxe and lmaxv) in case.inhf because the computational time will depend strongly on them. Choosing carefully the value of a parameter means to determine (by test calculations) the lowest value which is enough for the accuracy that is needed. This will depend on the solid, the property (e.g., lattice constant or band gap) and the RMT. The more the RMT is small, the more lmaxe and lmaxv can be chosen to be small, while gmax will need to be increased. Setting up a hybrid calculation needs some additional considerations and is described in detail in Sec Parallel execution (fine grain MPI and on the k-point level) is also possible and is described in Secs and 5.5. Beside the selfconsistent calculations, it is also possible to calculate the total energy with hybrid functionals non-selfconsistently (switch -nonself) and to calculate the hybrid eigenvalues (but not the orbitals) in a cheap way (switch -diaghf) Execution The program hf is executed by invoking the command: x hf [-up/dn -c -p -band -diaghf -nonself -newklist -redklist] or hf hf.def or hfc hf.def Input top of file: case.inhf alpha T screened (T) or unscreened (F) lambda xx nband 6 gmax 3 lmaxe 3 lmaxv 1d-3 tolu bottom of file: Interpretive comments on this file are as follows: line 1: free format α fraction (α [0, 1]) of Hartree-Fock exchange line 2: free format screening if set to F (false), no screening is applied to the exchange. If set to T (true), the exchange is screened by means of the Yukawa potential and the screening parameter λ will have to be specified in the next line. Note, that unscreend HF requires a denser k-mesh than screened HF.
133 7.4. HF 115 line 3: free format λ screening parameter in bohr 1. This line should be present only if screening is set to T (true) in line 2. With the value λ = bohr 1, the results are very close to the values from the HSE06 hybrid functional (Tran and Blaha 2011). Values for λ smaller than or larger than 5 can eventually lead to suspicious results due to numerical instabilities. line 4: free format nband the number of bands used for the 2nd variational procedure. nband should be at least equal to the number of (partially) occupied bands plus one. The choice for nband will depend strongly on the studied property and accuracy needed. If the switch -diaghf is used, then the accuracy of the eigenvalues will not depend on the value of nband, therefore nband can be chosen as the smallest value that you want (but still at least to the number of occupied bands plus one) line 5: free format gmax magnitude of the largest vector G in the Fourier expansion of the product of two orbitals and the generated potential in the interstitial region (Eqs. (13) and (14) in Tran and Blaha 2011). gmax=6 can eventually represent a good compromise between computational time and accuracy. line 6: free format lmaxe maximum value of the angular momentum for the expansion in spherical harmonics of the product of two orbitals and the generated potential inside the atomic spheres (Eqs. (13) and (14) in Tran and Blaha 2011). lmaxe=3 or 4 are usually large enough for good accuracy for light elements. For systems with f electrons, the value lmaxe=6 may eventually be necessary. line 7: free format lmaxv maximum value of the angular momentum of the expansion of the orbitals (l i in Eq. (15) in Tran and Blaha 2011). The value should be at least equal to the largest chemical l present in the system. line 8: free format tolerance below this value, the double radial integrals in Eq. (26) (Tran and Blaha 2011) are neglected. With tolu=1d-3 (or even 1d-2) not much accuracy is lost.
134 116 CHAPTER 7. SCF CYCLE 7.5 LAPW1 (generates eigenvalues and eigenvectors) lapw1 sets up the Hamiltonian and the overlap matrix (Koelling and Arbman 75) and finds by diagonalization eigenvalues and eigenvectors which are written to case.vector. Besides the standard LAPW basis set, also the APW+lo method (see Sjöstedt et al 2000, Madsen et al. 2001) is supported and the basis sets can be mixed for maximal efficiency. If the file case.vns exists (i.e. non-spherical terms in the potential), a full-potential calculation is performed. For structures without inversion symmetry, where the hamilton and overlap matrix elements are complex numbers, the corresponding program version lapw1c must be used in connection with lapw2c. Since usually the diagonalization is the most time consuming part of the calculations, two options exist here. In WIEN2k we include highly optimized modifications of LAPACK routines. We call all these routines full diagonalization, but we also provide an option to do an iterative diagonalization using a new preconditioning of a block-davidson method (see Singh 89 and Blaha et al. 09). The scheme uses an old eigenvector from the previous scf-iteration, and produces approximate (but usually still highly accurate) eigenvalues/vectors. The preconditioner (inverse of (H λs) can be calculated at the first iterative step (which will therefore take longer than subsequent iterative steps), stored on disk (case.storehinv) and reused in all subsequent scf-iterations (until the next full diagonalization or when it is recreated (x lapw1 -it -nohinv0)). Usually this is the fastest scheme, but storage of case.storehinv can be large (and slow when you have a slow network) and when the Hamiltonian changes too much, performance may degrade. Alternatively, the preconditioner can be recalculated all the time (x lapw1 -it -nohinv). Depending on the ratio of matrix size to number of eigenvalues (cpu time increases linearly with the number of eigenvalues, but a sufficiently large number is necessary to ensure convergence) a significant speedup compared to full diagonalization (LAPACK) can be reached. Iterative diagonalization is activated with the -it switch in x lapw1 -it or run lapw -it. Often the preconditioner is so efficient, that it does not need to be recalculated, even within a structural optimization and one can use min lapw -j run lapw -I -fc 1 -it. In some cases it is preferable to use min lapw -j run lapw -I -fc 1 -it1, which will recreate case.storehinv, or do not store these files at all using min lapw -j run lapw -I -fc 1 -it -nohinv Parallel execution (fine grain and on the k-point level) is also possible and is described in detail in Sec The switch -nohns skips the calculation of the nonspherical matrix elements inside the sphere. This may be used to save computer time during the first scf cycles Execution The program lapw1 is executed by invoking the command: x lapw1 [-c -up dn -it -nohinv -nohinv0 -p -nohns -orb -band -nmat only -nmr] or lapw1 lapw1.def or lapw1c lapw1.def In cases without inversion symmetry, the default input filename is case.in1c. For 2-window (not recommended) semi-core calculations the lapw1s.def file uses a case.in1s file and creates the files case.output1s and case.vectors. For the spin-polarized case lapw1 is called twice with uplapw1.def and dnlapw1.def. To all relevant files the keywords up or dn are appended (see the fcc Ni test case in the WIEN2k package) Dimensioning parameters The following parameters (collected in file param.inc r or param.inc c) are used: LMAX highest l+1 in basis function inside sphere (consistent with input in case.in1)
135 7.5. LAPW1 117 LMMX number of LM terms in potential (should be at least NCOM-1) LOMAX highest l for local orbital basis (consistent with input in case.in1) NGAU number of Gaunt coefficients for the non-spherical contributions to the matrix elements NMATMAX maximum size of H,S-matrix (defines size of program, should be chosen according to the memory of your hardware, see chapter !) NRAD number of radial mesh points NSLMAX highest l+1 in basis functions for non-muffin-tin matrix elements (consistent with input in case.in1).if set larger than 5, parameter MAXDIM (modules.f) and LO- MAX=8, P(10,10) (gaunt2.f) must also be increased. NSYM order of point group NUME maximum number of energy eigenvalues per k-point NVEC1 defines the largest triple of integers which define reciprocal NVEC2 K-vectors when multiplied with the reciprocal Bravais matrix NVEC3 restrict output for mpi-jobs, limits the number of case.output1 X proc XXX files to restrict output Input Below a sample input is shown for T io 2 (rutile), one of the test cases provided in the WIEN2k package. The input file is written automatically by LSTART, but was modified to set APW only for Ti-3d and O-2p orbitals top of file: case.in WFFIL EF= (WFPRI,WFFIL,SUPWF ; wave fct. print,file,suppress (R-mt*K-max; MAX l, max l for hns ) (global energy parameter E(l), with 5 other choices, LAPW) CONT 0 ENERGY PARAMETER for s, LAPW CONT 0 ENERGY PARAMETER for s-local orbital, LAPW-LO CONT 0 ENERGY PARAMETER for p LAPW CONT 0 ENERGY PARAMETER for p-local orbitals LAPW-LO CONT 1 APW (global energy parameter E(l), with 1 other choice, LAPW) STOP 0 LAPW CONT 0 LAPW-LO CONT 1 APW K-VECTORS FROM UNIT: emin/emax/nband 1.d spro_limit for it.diag., lambda for it.diag bottom of file Interpretive comments follow: line 1: free format switch, EF switch WFFIL standard option, writes wave functions to file case.vector (needed in lapw2) SUPWF suppresses wave function calculation (faster for testing eigenvalues only) WFPRI prints eigenvectors to case.output1 and writes case.vector (produces long outputs!) EF optional input. If EF= key is present, lapw1 reads EF and sets the default energy parameters (0.3) to EF-0.2 or EF+0.2 (for a high- LO ) Ry. line 2: free format
136 118 CHAPTER 7. SCF CYCLE rkmax, lmax, lnsmax rkmax lmax lnsmax R mt K max determines matrix size (convergence), where Kmax is the plane wave cut-off, Rmt is the smallest of all atomic sphere radii. Usually this value should be between 5 and 9 (APW+lo) or (LAPWbasis) (Kmax 2 would be the plane wave cut-off parameter in Ry used in pseudopotential calculations.) Note that d (f) wavefunctions converge slower than s and p. For systems including hydrogen with short bondlength and thus a very small R mt (e.g. 0.7 a.u.), RKmax = 3 might already be reasonable, but convergence must be checked for a new type of system. Note, that the actual matrix size is written on case.scf1. It is determined by whatever is smaller, the plane wave cut-off (specified with RKmax) or the maximum matrix dimension NMATMAX, (see previous section). maximum l value for partial waves used inside atomic spheres (should be between 8 and 12) maximum l value for partial waves used in the computation of nonmuffin-tin matrix elements (lnsmax=4 is quite good) line 3: free format Etrial, ndiff, Napw Etrial ndiff Napw default energy used for all E l to obtain u l (r, E l ) as regular solution of the radial Schrödinger equation [used in equ.2.4,2.7] (see figure 7.1). number of exceptions (specified in the next ndiff lines) 0... use LAPW basis, 1... use APW-basis for all global l values of this atom. We recommend to use LAPW here. line 4: format(i2,2f10.5,a4) l, El, de, switch, NAPWL l El de switch CONT STOP l of partial wave E l for L=l energy increment de=0: this E(l) overwrites the default energy (from line 3) de 0: a search for a resonance energy using this increment is done. The radial function u l (r, E) up to the muffin-tin radius RMT varies with the energy. A typical case is schematically shown in Fig At the bottom of the energy bands u has a zero slope (bonding state), but it has a zero value (antibonding state) at the top of the bands. One can search up and down in energy starting with E l using the increment de to find where u l (R MT, E) changes sign in value to determine E top and in slope to specify E bottom. If both are found E l is taken as the arithmetic mean and replaces the trial energy. Otherwise E l keeps the specified value. For E top and E bottom bounds of +1 and -10 Ry are defined respectively, and if they are not found, they remain at the initial value set to used only if de.ne.0 calculation continues, even if either E top or E bottom are not found calculation stops if not both E top and E bottom are found (especially useful for semi-core states)
137 7.5. LAPW1 119 NAPWL 0... use LAPW basis, 1... use APW-basis for this l value of this atom. We recommend to use APW+lo when the corresponding wavefunction is localized and thus difficult to converge with standard LAPW (like 3d functions) and/or when the respective atomic sphere is small compared to the other spheres in the unit cell. u (r,e) l E bottom E E top E l E l R MT E top r E bottom DOS Figure 7.1: Schematic dependence of DOS and u l (r, E l ) on the energy >>>:line 4 is repeated ndiff times (see line 3) for each exception. If the same l value is specified twice, local orbitals are added to the (L)APW basis. The first energy (E 1 ) is used for the usual LAPW s and the second energy (E 2 ) for the LOs, which are formed according to (see equ. 2.7): u E1 + u E1 + u E2. Note: The default energy parameters (0.30) are replaced by an energy E F 0.2 if the EF-switch was read before. Please read also the comments about run lapw in section In addition, you may want to change the automatically created input and add d- or f-local orbitals to reduce the linearization error (e.g. in late transition metals you could put E 3d at 0.0 and 1.0 Ry) or s, p, d, and/or f-los at very high energy (e.g Ry) to better describe unoccupied states. >>>:lines 3 and 4 are repeated for each non equivalent atom line 5: format (20x,i1,2f10.1,i6) unit-number, Emin, Emax nband unitnumber EMIN, EMAX nband file number from which the k-vectors in the irreducible wedge of the Brillouin zone are read. Default is 4, for which the corresponding information is contained in case.klist (generated by KGEN). Should not be changed. energy window in which eigenvalues shall be searched (overrides setting in case.klist. A small window saves computer time, but it also limits the energy range for the DOS calculation of unoccupied states. number of eigenvalues calculated with iterative diagonalization. Set automatically to nband = ne in lstart. Larger values will lead to more cpu-time. (Optional input) line 6: free format; optional input line, but necessary if k-vectors are read from unit 5 spro limit, lambda iter spro limit limit for detection of linear dependency for iterative diagonalization (optional input), typical around 1.d-15)
138 120 CHAPTER 7. SCF CYCLE lambda iter optional λ value for preconditioner of iterative diagonalization (see above). By default we use λ = 0, but in some cases convergence can be improved by a small (around 1.0) positive or negative λ line 7: format (A10,4I10,3F5.2); (only when unit-number=5, not recommended, use unit 4 and case.klist) name, ix,iy,iz, idv, weight name name of k-vector (optional) >>>: the last line must be END!! ix,iy,iz, defines the k-vector, where x= ix/idv etc. We use cartesian coordinates idv in units of 2π/a, 2π/b, 2π/c for P,C,F and B cubic, tetragonal and orthorhombic lattices, but internal coordinates for H and monoclinic/triclinic lattices weight of k-vector (order of group of k) >>>: line 7 is repeated for each k-vector in the IBZ. The utility program kgen (see section 6.5) provides a list of such vectors (on a tetrahedral mesh) in case.klist. >>>: the last line must be END 7.6 LAPWSO (adds spin orbit coupling) lapwso includes spin-orbit (SO) coupling in a second-variational procedure and computes eigenvalues and eigenvectors (stored in case.vectorso) using the scalar-relativistic wavefunctions from lapw1. For reference see Singh 94 and Novák 97. The SO coupling must be small, as it is diagonalized in the space of the scalar relativistic eigenstates. For large spin orbit effects it might be necessary to include many more eigenstates from lapw1 by increasing EMAX in case.in1 (up to 10 Ry!). We also provide an additional basisfunction, namely a relativistic-lo (RLO) with a p 1/2 radial wavefunction, which improves the basis and removes to a large degree the dependency of the results on EMAX and RMT (see Kuneš et al. 2001). It is particular helpfull for heavier atoms with semicore p-states, but it must not be used for EFG calculations. SO is considered only within the atomic spheres and thus the results may depend to some extent on the choice of atomic spheres radii. The nonspherical potential is neglected when calculating dv dr. Orbital dependent potentials (LDA+U, EECE or OP) can be added to the hamiltonian in a cheap and simple way. In spin-polarized calculations the presence of spin-orbit coupling may reduce symmetry and even split equivalent atoms into non-equivalent ones. It is then necessary to consider a larger part of the Brillouin zone and the input for lapw2 should also be modified since the potential has lower symmetry than in the non-relativistic case. The following inputs may change: case.struct case.klist case.kgen case.in2c case.in1 We recommend to use initso (see Sec ) which helps you together with symmetso (see Sec.9.1) to setup spinorbit calculations. Note: SO eigenvectors are complex and thus lapw2c must be used in a selfconsistent calculation.
139 7.6. LAPWSO Execution The program lapwso is executed by invoking the command: x lapwso [ -up -p -c -orb] or lapwso lapwso.def where here -up indicates a spin-polarized calculation (no -dn is needed, since spin-orbit will mix spin-up and dn states in one calculation) Dimensioning parameters The following parameters are used (collected in file module.f): FLMAX constant = 3 LMAX highest l of wave function inside sphere (consistent with lapw1) LOMAX max l for local orbital basis NRAD number of radial mesh points Input A sample input for lapwso is given below. It will be generated automatically by initso top of file: case.inso WFFIL llmax,ipr,kpot Emin, Emax h,k,l (direction of magnetization) 2 number of atoms with RLO STOP atom-number, E-param for RLO STOP atom-number, E-param for RLO 1 2 number of atoms without SO, atomnumbers bottom of file Interpretive comments on this file are as follows: line 1: format(a5) switch WFFIL wavefunctions will also be calculated for scf-calculation. Otherwise only eigenvalues are calculated. line 2: free format LLMAX, IPR, KPOT LLMAX maximum l for wavefunctions IPR print switch, larger numbers give additional output. KPOT 0 V(dn) potential is used for < dn V dn > elements, V(up) for < up V up > and [V(dn)+V(up)]/2 for < up V dn >. 1 averaged potential used for all matrix elements. line 3: free format Emin, Emax
140 122 CHAPTER 7. SCF CYCLE Emin Emax minimum energy for which the output eigenvectors and eigenenergies will be printed (Ry) maximum energy line 4: free format h,k,l vector describing the direction of magnetization. For R lattice use h,k,l in rhombohedral coordinates (not in hexagonal) line 5: free format nlr number of atoms for which a p 1/2 LO should be added line 6: free format nlri, El, de, switch nlri El de switch CONT STOP atom-number for which RLO should be added E l for L=l energy increment (see lapw1) used only if de.ne.0 calculation continues, even if either E top or E bottom are not found calculation stops if not both E top and E bottom are found (especially useful for semi-core states) >>>: line 6 must be repeated nlr times (or should be omitted if nlr=0). line 7: free format noff, (iatoff(i),i=1,noff) noff iatoff number of atoms for which SO is switched off (for light elements, saves time) atom-numbers 7.7 LAPW2 (generates valence charge density expansions) lapw2 uses the files case.energy and case.vector and computes the Fermi-energy (for a semiconductor E F is set to the valence band maximum) and the expansions of the electronic charge densities in a representation according to eqn for each occupied state and each k-vector; then the corresponding (partial) charges inside the atomic spheres are obtained by integration. In addition Pulay-corrections to the forces at the nuclei are calculated here. For systems without inversion symmetry you have to use the program lapw2c (in connection with lapw1c). The partial charges for each state (energy eigenvalue) and each k-vector can be written to files case.help031, case.help032 etc., where the last digit gives the atomic index of inequivalent atoms (switch -help files). Optionally these partial charges are also written to case.qtl (switch -qtl). For meta-gga calculations energy densities are written to case.vrepval(switch -vresp). In order to get partial charges for bandstructure plots, use -band, which sets the QTL option and uses ROOT in case.in2. Several other switches change the input file case.in2 temporarely and are described there.
141 7.7. LAPW Execution The program lapw2 is executed by invoking the command: x lapw2 [-c -up dn -p -so -qtl -fermi -efg -hf -band -eece -vresp -help files -emin X -all X Y] or lapw2 lapw2.def [proc#] or lapw2c lapw2.def [proc#] where proc# is the i-th processor number in case of parallel execution (see Fig. 5.2). The -so switch sets -c automatically. For complex calculations case.in2c is used. For a spin-polarized case see the fcc Ni test case in the WIEN2k package Dimensioning parameters The following parameters are used (collected in file modules.f): IBLOCK Blocking parameter (32-255) in l2main.f, optimize for best performance LMAX2 highest l in wave function inside sphere (smaller than in lapw1, at present must be.le. 8) LOMAX max l for local orbital basis NCOM number of LM terms in density NGAU max. number of Gaunt numbers NRAD number of radial mesh points restrict output for mpi-jobs, limits the number of case.output2 X proc XXX files to restrict output Input A sample input for lapw2 is listed below, it is generated automatically by the programs lstart and symmetry top of file: case.in TOT (TOT,FOR,QTL,EFG) (EMIN, # of electrons,esepermin, ESEPER0,iqtlsave) TETRA 0.0 (EF-method (ROOT,TEMP,GAUSS,TETRA,ALL),value) (GMAX) FILE (NOFILE, optional) bottom of file Interpretive comments on this file are as follows: line 1: format(2a5) switch, EECE switch TOT total valence charge density expansion inside and outside spheres FOR same as TOT, but in addition a Pulay force contribution is calculated (this option costs extra computing time and thus should be performed only at the final scf cycles, see run lapw script in sec ) QTL partial charges only (generates file case.qtl for DOS calculations), set automatically by switch -qtl
142 124 CHAPTER 7. SCF CYCLE EECE EFG ALM CLM FERMI computes decomposition of electric field gradient (EFG), contributions from inside spheres (the total EFG is computed in lapw0), set automatically by switch -efg. this generates two files, case.radwf and case.almblm, where the radial wavefunctions and the A lm, B lm, C lm coefficients of the wavefunction inside spheres are listed. The file case.almblm can get very big. CLM charge density coefficients only Fermi energy only, this produces weight files for parallel execution and for the optics and lapwdm package, set automatically by switch -fermi. >>>: TOT and FOR are the standard options, QTL is used for density of states (or energy bandstructure) calculations, EFG for analysis, while FOURI, CLM are for testing only. if set to EECE, calculates the density for specified atoms and angular momentum only. Used for exact-exchange or hybrid-calculations, usually set automatically by runsp lapw -eece line 2: free format emin, ne, esepermin, eseper0, iqtlsave emin ne esepermin eseper0 iqtlsave lower energy cut-off for defining the range of occupied states, can be set termporarely to X by switch -emin X or -all X Y number of electrons (per unit cell) in that energy range LAPW2 tries to find the mean energies for each l channel, for both the valence and the semicore states. To define valence and semicore it starts at (EF - esepermin ) and searches for a gap with a width of at least eseper0 and defines this as separation energy of valence and semicore minimum gap width (see above). The values esepermin and eseper0 will only influence results if the option -in1new is used optional value, checks if the low-energy bandranges (below -2 Ry) are narrow (below 0.2 Ry) and stops (iqtlsave=1 = default) / does not stop (iqtlsave=0). You may have to switch it off for extreme pressures, because then you may have large band width even for semi-core states. line 3: format(a5,f10.5) efmod, eval efmod determines how E F is determined ROOT E F is calculated and k space integration is done by root sampling (this can be used for insulators, but for metals poor convergence is found) TEMP E F is calculated where each eigenvalue is temperature broadened using a Fermi function with a broadening parameter of eval Ry. The total energy is corrected corresponding to T=0K. (e.g. eval=0.002 Ry gives good total energy convergence, but has no physical justification) TEMPS E F is calculated where each eigenvalue is temperature broadened using a Fermi function with a broadening parameter of eval Ry. The total energy is corrected by -TS corresponding to the temperature specified by eval (e.g. eval=0.002 Ry corresponds to about 40 C) GAUSS E F is calculated as above but a Gaussian smearing method is used with a width of eval Ry. (e.g. eval=0.002 gives good total energy convergence, but has no physical justification).
143 7.7. LAPW2 125 eval TETRA ALL E F is calculated and k space integration is done by the modified (if eval is.eq. 0) or standard (eval.ge. 100) tetrahedron-method (Blöchl 94). This standard scheme is recommended for optic. In this case the file case.kgen, consistent with the k-mesh used in lapw1, must be provided (see Sec. 7.5). This is the recommended option although convergence may be slower than with Gauss- or temperature-smearing. All states up to eval are used. This can be used to generate charge densities in a specified energy interval, can be set termporarely by switch -all X Y. when efmod is set to TEMP(S) (eval=0 will lead to room temperature broadening, Ry) or GAUSS, eval specifies the width of the broadening (in Ry), if efmod is set to ALL, eval specifies the upper limit of the energy window (in Ry; can be set termporarely by switch -all X Y), if efmod is set to TETRA, eval.ge. 100 specifies the use of the standard tetrahedron method instead of the modified one (see above). By default, TETRA will average over partially occupied degenerate states at EF with a degeneracy criterium D = 1.d-6. You can modify this by setting eval equal to your desired D (or 100+D). optional line 3a: free format (ONLY when EECE is set) nat rho number of atoms for which a specific density should be calculated optional line 3b: free format (ONLY when EECE is set) jatom rho, l rho jatom rho l rho index of atom for which a specific density should be calculated angular momentum l-value for which a specific density should be calculated >>>line 3b: must be repeated nat rho times line 4: format (121(I3,I2)) L,M LM values of lattice harmonics expansion (equ. 2.10), defined according to the point symmetry of the corresponding atom; generated in SYMMETRY, MUST be consistent with the local rotation matrix defined in case.struct (details can be found in Kara and Kurki-Suonio 81). CAUTION: additional LM terms which do not belong to the lattice harmonics will in general not vanish and thus such terms must be omitted. Automatic termination of the lm series occurs when a second 0,0 pair appears within the list. When you change the l, m list during an SCF calculation the Broyden-Mixing is restarted in MIXER. >>>line 4: must be repeated for each inequivalent atom Symmetry LM combinations , 4 0, 4 4, 6 0, 6 4,-3 2, 6 2, 6 6,-7 2,-7 6, 8 0, 8 4, 8 8,-9 2,-9 6,-9 4,-9 8,10 0, 10 4,10 8, 10 2, 10 6, M3 0 0, 4 0, 4 4, 6 0, 6 4, 6 2, 6 6, 8 0, 8 4, 8 8,10 0, 10 4,10 8, 10 2, 10 6, , 4 0, 4 4, 6 0, 6 4, 8 0, 8 4, 8 8,-9 4,-9 8,10 0, 10 4, M 0 0, 4 0, 4 4, 6 0, 6 4,-3 2,-7 2,-7 6, 8 0, 8 4, 8 8,-9 2,-9 6,10 0, 10 4,10 8 M3M 0 0, 4 0, 4 4, 6 0, 6 4, 8 0, 8 4, 8 8,10 0, 10 4,10 8 Table 7.50: LM combinations of Cubic groups (3 (111)) direction, requires positive atomic index in case.struct. Terms that should be combined (Kara and Kurki-Suonio 81) must follow one another.
144 126 CHAPTER 7. SCF CYCLE Symmetry Coordinate axes Indices of Y ±LM crystal system 1 any ALL (±l,m) triclinic -1 any (±2l,m) 2 2 z (±l,2m) monoclinic M m z (±l,l-2m) 2/M 2 z, m z (±2l,2m) z, 2 y, (2 x) (+2l,2m), (-2l+1,2m) orthorhombic MM2 2 z, m y, (2 x) (+l,2m) MMM 2 z, m y, 2 x (+2l,2m) 4 4 z (±l,4m) tetragonal -4-4 z (±2l,4m), (±2l+1,4m+2) 4/M 4 z, m z (±2l,4m) z, 2 y, (2 x) (+2l,4m), (-2l+1,4m) 4MM 4 z, m y, (2 x) (+l,4m) -42M -4 z, 2 x (m=xy yx) (+2l,4m), (-2l+1,4m+2) 4MMM 4 z, m z, m x (+2l,4m) 3 3 z (±l,3m) rhombohedral -3-3 z (±2l,3m) 32 3 z, 2 y (+2l,3m), (-2l+1,3m) 3M 3 z, m y (+l,3m) -3M -3 z, m y (+2l,3m) 6 6 z (±l,6m) hexagonal -6-6 z (+2l,6m), (±2l+1,6m+3) 6/M 6 z, m z (±2l,6m) z, 2 y, (2 x) (+2l,6m), (-2l+1,6m) 6MM 6 z, m y, (m x) (+l,6m) -62M -6 z, m y, (2 x) (+2l,6m), (+2l+1,6m+3) 6MMM 6 z, m z, m y, (m x) (+2l,6m) Table 7.51: LM combination and local coordinate system of non-cubic groups (requires negative atomic index in case.struct) line 5: free format GMAX max. G (magnitude of largest vector) in charge density Fourier expansion. For systems with short H bonds larger values (e.g. GMAX up to 25) could be necessary. Calculations using GGA (potential option 13 or 14 in case.in0) should also employ a larger GMAX value (e.g. 14), since the gradients are calculated numerically on a mesh determined by GMAX. When you change GMAX during an scf calculation the Broyden-Mixing is restarted in mixer. line 6: A4 reclist FILE writes list of K-vectors into file case.recprlist or reuses this list if the file exists. The saved list will be recalculated whenever GMAX, or a lattice parameter has been changed. NOFILE always calculate new list of K-vectors 7.8 SUMPARA (summation of files from parallel execution) sumpara is a small program which (in parallel execution of WIEN2k) sums up the densities (case.clmval *) and quantities from the case.scf2 * files of the different parallel runs Execution The program sumpara is executed by invoking the 2 commands as follows: x sumpara -d [-up/-dn/-du] and then sumpara sumpara.def # of proc where # of proc is the numbers of parallel processors used. It is usually called automatically from lapw2para or x lapw2 -p Dimensioning parameters
145 7.9. LAPWDM LAPWDM (calculate density matrix) This program was contributed by: J.Kuneš and P.Novák Inst. of Physics, Acad.Science, Prague, Czeck Republic Please make comments or report problems with this program to the WIEN-mailinglist. we will communicate the problem to the authors. If necessary, lapwdm calculates the density matrix needed for the orbital dependent potentials generated in orb. Optionally it also provides orbital moments, orbital and dipolar contributions to the hyperfine field (only for the specified atoms AND orbitals). It calculates the average value of the operator X which behaves in the same way as the spin-orbit coupling operator: it must be nonzero only within the atomic spheres and can be written as a product of two operators - radial and angular: X = X r (r) X ls ( l, s) X r (r) and X ls ( l, s) are determined by RINDEX and LSINDEX in the input as described below: RINDEX=0 LSINDEX=0: the density matrix is calculated (this is needed for LDA+U calculations) RINDEX=1 LSINDEX=1: <X> is number of electrons inside the atomic sphere (for test) RINDEX=2 LSINDEX=1: <X> is the < 1/r 3 > expectation value inside the atomic sphere RINDEX=1 LSINDEX=2: <X> is the projection of the electronic spin inside the atomic sphere (must be multiplied by g=2 to get the spin moment) RINDEX=1 LSINDEX=3: <X> is the projection of the orbital moment inside the atomic sphere (in case of SO-calculations WITHOUT LDA+U) RINDEX=3 LSINDEX=3: <X> is the orbital part of the hyperfine field at the nucleus (for a converged calculation at the very end) RINDEX=3 LSINDEX=5: <X> is the spin dipolar part of the hyperfine field at the nucleus (for a converged calculation at the very end) To use the different operators, set the appropriate input. More information and extentions to operators of similar behavior may be obtained directly from P. Novák (2006). (RINDEX=3 includes now an approximation to the relativistic mass enhancement and LSINDEX=5 includes nondiagonal terms) lapwdm needs the occupation numbers, which are calculated in lapw2. Note: You must not use ROOT in case.in2 for that purpose Execution The program lapwdm is executed by invoking the command: x lapwdm [ -up/dn -p -c -so -hf] or lapwdm lapwdm.def Dimensioning parameters The following parameters are used (collected in file param.inc):
146 128 CHAPTER 7. SCF CYCLE FLMAX constant = 3 LMAX highest l of wave function inside sphere (consistent with lapw1) LABC highest l of wave function inside sphere where SO is considered LOMAX max l for local orbital basis NRAD number of radial mesh points Input A sample input for lapwdm is given below top of file: case.indm Emin cutoff energy 1 number of atoms for which density matrix is calculated index of 1st atom, number of L s, L1 0 0 r-index, (l,s)-index bottom of file Interpretive comments on this file are as follows: line 1: free format emin lower energy cutoff (usually set to very low number). line 2: free format natom number of atoms for which the density matrix is calculated line 3: free format iatom, nl, l iatom nl l index of atom for which the density matrix should be calculated number of l-values for which the density matrix should be calculated l-values for which the density matrix should be calculated line 3 is repeated natom times t line 4: free format, optional RINDEX, LSINDEX RINDEX 0-3, as described in the introduction to lapwdm LSINDEX0-5, as described in the introduction to lapwdm 7.10 LCORE (generates core states) lcore is a modified version of the Desclaux (69, 75) relativistic LSDA atomic code. It computes the core states (relativistically including SO, or non-relativistically if NREL is set in case.struct) for the current spherical part of the potential (case.vsp). It yields core eigenvalues, the file case.clmcor with the corresponding core densities, and the core contribution to the atomic forces Execution The program lcore is executed by invoking the command:
147 7.10. LCORE 129 lcore lcore.def or x lcore [-up -dn] For the spin-polarized case see fcc Ni on the distribution tape. If case.incup and case.incdn are present for spin-polarized calculations, different core-occupation ( open core approximation for 4f states or spin-polarized core-holes) for both spins are possible Dimensioning parameters The following parameter is listend in file param.inc: NRAD number of radial mesh points Input Below is a sample input (written automatically by lstart) for T io 2 (rutile), one of the test cases provided with the WIEN2k package. In case of a open core calculation (eg. for 4f states) you may need spin-polarized case.inc files in order to define different configurations for spin-up and dn. Create two files case.incup and case.incdn with the corresponding occupations. The runsp lapw script will automatically copy the corresponding files to case.inc top of file: case.inc # of orbitals, shift of potential, print switch 1,-1,2 n (principal quantum number), kappa, occup. number 2,-1,2 2s 2,-2,4 2p 2, 1,2 2p* # of orbital of second atom 1,-1,2 1s 0 end switch bottom of file Interpretive comments on this file are as follows: line 1: free format nrorb, shift, iprint nrorb shift iprint number of core orbitals shift of potential for positive eigenvalues (e.g. for 4f states as core states in lanthanides) optional print switch to reduce (0) or increase (1) printing to case.outputc line 2: free format n, kappa, occup n principle quantum number kappa relativistic quantum number (see Table 6.6) occup occupation number (including spin), fractial occupations supported >>>: line 2 is repeated for each orbital (nrorb times; see line 1) >>>: line 1 and 2 are repeated for each inequivalent atom. Atoms without core states (e.g. H or Li) must still include a 1s orbital, but with occupation zero. line 3: free format
148 130 CHAPTER 7. SCF CYCLE 0 zero indicating end of job 7.11 MIXER (adding and mixing of charge densities) In mixer the electron densities of core, semi-core, and valence states are added to yield the total new (output) density (in some calculations only one or two types will exist). Proper normalization of the densities is checked and enforced (by adding a constant charge density in the interstitial). As it is well known, simply taking the new densities leads to instabilities in the iterative SCF process. Therefore it is necessary to stabilize the SCF cycle. In WIEN2k this is done by mixing the output density with the (old) input density to obtain the new density to be used in the next iteration. Several mixing schemes are implemented, but we mention only: 1. straight mixing as originally proposed by Pratt (52) with a mixing factor Q ρ new (r) = (1 Q)ρ old (r) + Qρ output (r) 2. a Multi-Secant mixing scheme contributed by L. Marks (see Marks and Luke 2008), in which all the expansion coefficients of the density from several preceding iterations (usually 6-10) are utilized to calculate an optimal mixing fraction for each coefficient in each iteration. It is very robust and stable (works nicely also for magnetic systems with 3d or 4f states at EF, only for ill-conditioned single-atom calculations you can break it) and usually converges at least 30 % faster than the old BROYD scheme. 3. Two new variants on the Multi-Secant method including a rank-one update (see Marks 2013) which appear to be 5-10% faster and equally robust. At the outset of a new calculation (for any changed computational parameter such as k-mesh, matrix size, lattice constant etc.), any existing case.broydx files must be deleted (since the iterative history which they contain refers to a different incompatible calculation). If the file case.clmsum old can not be found by mixer, a PRATT-mixing with mixing factor (greed) 1.0 is done. Note: a case.clmval file must always be present, since the LM values and the K-vectors are read from this file. The total energy and the atomic forces are computed in mixer by reading the case.scf file and adding the various contributions computed in preceding steps of the last iteration. Therefore case.scf must not contain a certain iteration-number more than once and the number of iterations in the scf file must not be greater than 999. For LDA+U calculations case.dmatup/dn and for onsite-hybrid-dft (switch -eece) case.vorbup/dn files will be included in the mixing procedure. With the new mode MSR1a (or MSECa) (contributed by L. Marks) atomic positions will also be mixed and thus optimized. This scheme can (unfortunately not in all cases) be a facter or 2-3 faster then the traditional optimization using min lapw Execution The program mixer is executed by invoking the command: mixer mixer.def or x mixer [-eece] A spin-polarized case will be detected automatically by x due to the presence of a case.clmvalup file. For an example see fccni (sec. 10.2) in the WIEN2k package.
149 7.11. MIXER Dimensioning parameters The following parameters are collected in file param.inc, : NCOM NRAD NSYM traptouch number of LM terms in density number of radial mesh points order of point group minimum acceptable distance between atoms in full optimization model Input Below a sample input (written automatically by lstart) is provided for T io 2 (rutile), one of the test cases provided with the WIEN2k package top of file: case.inm MSR1 0.d0 YES (PRATT/MSEC1/3/MSR1/a bg charge (+1 for additional e), NORM 0.2 MIXING GREED Not used, retained for compatibility only nbroyd nuse ## VLSOW, SLOW, FAST bottom of file Interpretive comments on this file are as follows: line 1: (A5,*) switch, bgch, norm switch MSEC1 Multi-Secant scheme (Marks and Luke 2008) MSEC2 similar to MSEC1 (above), but mixes the higher LM values inside spheres by an adaptive PRATT scheme. This leads to a significant reduction of programsize and filesize (case.broyd*) for unitcells with many atoms and low symmetry (factor 10-50) with only slighly worse mixing performance. MSEC3 Similar to MSEC1, but with updated scaling, regularization and other improvements. MSEC4 similar to MSEC3 (above), but mixes only the L=0 LM value MSR1 Recommended. A Rank-One Multisecant that is slightly faster than MSEC3 in most cases. For MSR1a see later. MSR2 similar to MSR1 (above), but mixes only the L=0 LM value MSR1a Similar to MSR1, but in addition it optimizes the atomic positions simultaneously (see Sect ) PRATT Pratt scheme with a fixed greed PRAT0 Pratt scheme with a greed restrained by previous improvement, similar to MSEC3 bgch Background charge to apply to the cell (e.g. use +1 if the system contains an additional electron or -1 to screen a core hole if it is not neutralized by an additional valence electron) norm YES Charge densities are normalized to sum of Z NO Charge densities are not normalized line 2: free format
150 132 CHAPTER 7. SCF CYCLE greed mixing greed Q. Essential for Pratt, rather less important for MSEC1. In the first iteration using Broyden s scheme: Q is automatically reduced by the program depending on the average charge distance :DIS andthe relative improvement in the last cycle. In case that the scf cycle fails due to large charge fluctuations, this can be further reduced but this can lead to stagnation. One should rarely reduce this below line 3 (optional): (free format) f pw, f clm f pw Not used, retained for input compatibility. f clm Not used, retained for input compatibility. line 4 (optional): (free format) nbroyd, nuse nbroyd Not used, retained for input compatibility. nuse For all Multisecant methods: Only nuse steps are used during modified broyden (this value has some influence on the optimal convergence. Usually 6-10 seems reasonable and 8 is the default). line 5 (optional line): (free format) trust VSLOW For very difficult cases, where divergence (like spin-polarized systems or with many TM atoms) or endless oszillations occur. SLOW FAST For easy cases to accelarate (also MSR1a). In addition, mixer reads a mixing factor from file.pratt or.msec, which can be used during scf/msr1a optimizations or at the very beginning to push convergence. You can create it using echo 0.2 >.pratt These files will be removed automatically once they are used. For additional documentation consult the README file in SRC mixer.
151 8 Programs for analysis, calculation of properties, and geometry optimization Contents 8.1 AIM BerryPI BROADENING DIPAN ELAST FILTVEC FSGEN IRelast IRREP JOINT KRAM LAPW LAPW LAPW MINI NMR OPTIC OPTIMIZE QTL SPAGHETTI TELNES TETRA XSPEC AIM (atoms in molecules) This program was contributed by: 133
152 134 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION Javier D. Fuhr and Jorge O. Sofo Instituto Balseiro and Centro Atomico Bariloche S. C. de Bariloche - Rio Negro, Argentina and Please make comments or report problems with this program to the WIEN-mailinglist. we will communicate the problem to the authors. If necessary, This program analyses the topology of the electron density according to Bader s Atoms in molecules theory. For more information see Bader 2001 and Sofo and Fuhr The original code has been significantly speeded-up by L.Marks There are some new optional keywords in the input (usually not needed, more for testing) and also more debugging output. All changes are described in $WIENROOT/SRC aim/notes.txt. Basically it performs two different tasks, namely searching for critical points (CP) and/or determination of the atomic basins with an integration of the respective charge density. It is important that you provide a good charge density, i.e. one which is well converged with respect to LMMAX in the CLM-expansion (you may have to increase the default LM-list to LM=8 or 10) and with as little core-leakage as possible (see lstart, sect. 6.4), otherwise discontinuities appear at the sphere boundary Execution The program aim is executed by invoking the command: aim aim.def or aimc aim.def or x aim [-c ] Dimensioning parameters The following parameters are listed in file param.inc: LMAX2 NRAD NSYM highest L in in LM expansion of charge and potential number of radial mesh points order of point group Input The input file contains SWITCHES, followed by the necessary parameters until an END-switch has been reached. Examples for critical-point searches and charge-integration are given below: top of file: case.inaim CRIT 1 # index of the atom (counting multiplicity) ALL # TWO/THRE/ALL /FOUR # x,y,z nshells (of unit cells) END bottom of file Interpretive comments on this file are as follows:
153 8.1. AIM 135 line 1: A4 CRIT Keyword to calculate critical points: A4 KEY TWO, THRE, ALL, or FOUR defines the starting point for the CP search to be in the middle of 2, 3 or 4 atoms. ALL combines option TWO and THRE together. line 4: free format nxsh, nysh, nzsh specifies the number of nearest neighbor cells (in x,y,z direction) where atomic positions are generated. lines 1-4 can be repeated with different atoms or KEYs line 5: A4 END specifies end of job. In case.outputaim the critical points are marked with a label :PC :PC a1 a2 a3 l1 l2 l3 c lap rho iat1 dist1 iat2 dist2 where a1,a2,a3 are the coordinates of the CP in lattice vectors; l1 l2 l3 are the eigenvalues of the Hessian at the CP; c is the character of the CP (-3, -1, 1 or 3); lap is the Laplacian of the density at the CP (lap=l1+l2+l3) and rho is the density at the CP (all in atomic units). In case of a bond critical point (c=-1) also the nearest distances (dist1, dist2) to the two nearest atoms (iat1, iat2) are given. For convenience run extractaim lapw case.outputaim (see ) and get in the file critical points ang a comprehensive list of the CP (sorted and unique) with all values given in Å, e/å 3,... (instead of bohr) top of file: case.inaim SURF 3 atom in center of surface (including MULT) theta, 40 points, from zero to pi phi step along gradient line, rmin, check initial R for search, step (a.u) nshell IRHO "INTEGRATE" rho WEIT WEIT (surface weights from case.surf), NOWEIT radial points outside min(rmin,rmt) END bottom of file Interpretive comments on this file are as follows: line 1: A4
154 136 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION SURF Keyword to calculate the Bader surface.: free format ntheta, thmin, thmax ntheta number of theta directions for the surface determination. This (and nphi) determines the accuracy (and computing time). thmin starting angle for theta thmax ending angle for theta. If you have higher symmetry, you can change the angles thmin=0, thmax=π and use only the irreducible part, i.e. when you have a mirror plane normal to z (see case.outputs), restrict thmax to π/2. line 4: free format nphi, phimin, phimax line 5: free format h0, frmin, nstep line 6: free format r0, dr0 line 7: free format nxsh, nysh, nzsh line 8: A4 nphi number of phi directions for the surface determination phimin starting angle phimax ending angle. (see comments for theta to reduce phi from the full 0 2π integration). h0 step in real space to follow the gradient ( 0.1) frmin defines the radius, for which the routine assumes that the search path has entered an atom, given as rmin = frmin * rmt ( ) nstep number of steps between testing the position being inside or outside of the surface ( 2-8). r0 initial radius for the search of the surface radius ( 1.5) dr0 step for the search of the surface radius( 0.1) specifies the number of nearest neighbor cells (in x,y,z direction) where atomic positions are generated. IRHO integrate function on unit 9 (usually case.clmsum) inside previously defined surface (stored in case.surf).
155 8.2. BERRYPI 137 line 9: A4 WEIT specifies the use of weights in case.surf. line 9: free format npt specifies number of points for radial integration outside the MT ( 30) line 8: A4 END specifies end of job. 8.2 BerryPI (Modern theory of polarization) This program was contributed by: S.J. Ahmed, J. Kivinen, B. Zaporzan, L. Curiel, S. Pichardo, O. Rubel Thunder Bay Regional Research Institute, Ontario, Canada Computer Physics Communications 184, (2013) Sources available from: Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. This program calculates the spontaneous polarization, Born effective charges or piezoelectric constants using the Berry phase approach. More details about its usage are given in Chapter 5.8. It consists of a set of Python scripts (requires Python 2.7 and the NumPi library) and uses wien2wannier for the calculation of overlap integrals. The main steps of a berrypi -knx:ny:nz call include: x kgen -fbz generate a k-mesh in the full Brillouin zone write inwf Prepare the input for w2w with the occupied band range write win case Create the input file for w2w win2nnkp.py case Generate the nearest neighbor list of k-points x lapw1 Calculate wavefunctions for the new k-list x w2w Calculate the overlap matrix S mn (k j, k j+1 ) x lapwso and x w2waddsp (only in case of SO) mmn2pathphase.py case x Calculate the Berry phase along x-axis
156 138 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION 8.3 BROADENING (apply broadening to calculated spectra) This program was contributed by: Joachim Luitz IAST Austria Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. The broadening program can be used in conjunction with the TELNES3 or the xspec program to broaden theoretical spectra by applying a lorentzian broadening for core and valence life times and a gaussian broadening for spectrometer broadening Execution Execution The program broadening is executed by invoking the command: broadening broadening.def or x broadening Input broadening needs one input file - case.inb. When running TELNES3 this input file is automatically created from settings given in case.innes. GaN ELNES dummy
157 8.4. DIPAN 139 line value explanation 1 GaN... Title (of no consequence for the calculation) 2 ELNES ABS EMIS Type of input spectrum 3 NC C1 C2 specification of input file: NC number of columns to read, C1 and C2 column to broaden (only in ELNES mode) 4 SPLIT XINT1 XINT2 split energy, XINT1 2 relative intensities of spectra in C1 and C2 5 GA GB core hole lifetime of the two edges 6 W WSHIFT W: type of valence broadening (1: linear with E/10, 2: Muller like E 2 ), edge offset 7 S Spectrometer broadening FWHM in ev 8 dummy dummy keyword for compatibility with lorentz 9-11 E0, E1, E2 quadratic energy dependent broadening (only used for type ELNES and EMIS when selecting valence broadening type W=2) 8.4 DIPAN (Dipolar anisotropies) This program was contributed by: P. Novák Inst. of Physics, Acad.Science, Prague, Czeck Republic Please make comments or report problems with this program to the WIEN-mailinglist. we will communicate the problem to the authors. If necessary, This program calculates the magnetic dipolar hyperfine field and the dipolar magnetocrystalline anisotropy by a direct lattice summation over the magnetic moments of all sites. According to Wikipedia B = µ 0µ [3( nˆr)ˆr n] (8.1) 4πr3 where ˆr = r/r. n = M/M is direction of magnetization. µ 0 is permeability of free space; µ 0 = 4π10 7 H/m. B is the dipolar field in T. µ is magnetic dipolar moment in Am 2 = J/T, assumed to be parallel to n. r is in m. We want to express µ in Bohr magnetons µ B = J/T and r in atomic units for length a 0 (Bohr radius) a 0 = m. Inserting in (1) gives B = µ(µ B) 3 [3( nˆr)ˆr n]. (8.2) r(a.u.) Total dipolar field acting on atom i is given by the lattice sum B i = j µ j rj 3 [3( n ˆr j ) ˆr j n]. (8.3)
158 140 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION Dipolar anisotropy energy is given by the sum E an = 1 2V B j µ j (8.4) j when the sum is over atoms in the unit cell, V is the unit cell volume, Factor 1/2 appears because of the double summation. Expressing B j in T, µ j in µ B and V in (a.u.) 3 gives E an (J/m 3 ) = V (a.u.) 3 B j (T) µ j (µ B ) (8.5) j Execution The program dipan is executed by invoking the command: dipan dipan.def or x dipan Dimensioning parameters The following parameters are listed in files dipan.f: NATO NDIF number of inequivalent atoms in unit cell total number of atoms in unit cell Input An example is given below: top of file: case.indipan Rmax (a.u.), ipr (printing option) Magnetic moment of 1s atom (Y) in mu_b Magnetic moment of 2nd atom (Co(2c)) Magnetic moments of 3rd atom (Co(3g)) in mu_b Volume in a.u.**(-3) 2 ndir: numder of magnetization directions first direction for the magnetization second direction bottom of file Interpretive comments on this file are as follows: line 1: free format Rmax, IPR Rmax max distance (bohr) for lattice summation. Vary it for convergence check. IPR Print switch. IPR=2 produces very large files case.outputdipan and case.nn dipan line 2: free format mm Magnetic moment (µ B ) of first atom
159 8.5. ELAST 141 line 2 must be repeated for every non-equivalent atom in the unit cell line 3: free format VOLUME Unit cell volume in bohr**3 (grep :VOL case.scf) line 4: free format NDIR number of magnetization directions for which the dipolar contributions will be calculated. For NDIR > 1 the differences E an (dir i ) E an (dir j ) are also calculated. line 5: free format h,k,l direction of magnetization line 5 must be repeated NDIR times 8.5 ELAST (Elastic constants for cubic cases) This program was contributed by: original author: Thomas Charpin Lab. Geomateriaux de l IPGP, Paris, France (In September 2001 we received the sad notice that Thomas Charpin died in a car accident). modified by Ferenc Karsai Institute for MaterialsChemistry TU Vienna Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. This package calculates elastic constants for cubic crystals. It is described in detail by the author in Charpin Execution The package is driven by three scripts: init elast: It prepares the whole calculation and should be run in a directory with a valid case.struct and case.inst file. It creates the necessary subdirectories elast, elast/eos, elast/tetra, elast/rhomb, elast/result, the templates for tetragonal and rhombohedral distortion and initializes the calculations using init lapw. elast setup: It should be run in the elast directory, generates the distorted struct-files and eos.job, rhomb.job and tetra.job. These scripts must be adapted to your needs (spinpolarization, convergence,...) and run. elast setup can be run several times (for different distortions,...).
160 142 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION ana elast: Once all calculations are done, change into elastresult and run this script. The final results are stored in elastresultoutputs. genetempl, setelast, anaelast: These three small programs are called by the above scripts. The following modifications of init elast, elast setup and ana elast prepare input files for calculations of elastic constants at different pressures and analyze the results: init elast pressure: As in the case of init elast the script is called in the working directory with a valid case.struct file and requires an input file case.inelastp1 (a template can be found at $WIENROOT/SRC templates/template.inelastp1). The script creates the directory elast/ with the necessary subdirectories pressure x/ according to the number x of pressure changes in the case.inelastp1 input file and the templates for isotropic, tetragonal and rhombohedral (trigonal) distortions at each pressure (pressure 1/eos, pressure 1/tetra, pressure 1/rhomb, pressure 2/eos,...). In each pressure x/ directory a file called z pressure.dat is created with the lattice constant at each pressure given in case.inelastp1. In contrast to init elast the calculations are initialized using init lapw in batch mode and the necessary parameters are set in case.inelastp1. The following small programs and scripts are utilized by init elast pressure: iniel pressure reader.pl, iniel pressure in2reader.pl, genetempl elast setup pressure: Similar to elast setup this script has to be run in the elast directory and requires the input file elast.inelastp2 (a template can be found at $WIENROOT/SRC templates/elast.inelastp2). It creates the distorted struct files and the pressure x/eos.job, pressure x/rhomb.job, pressure x/tetra.job and pressure x/runjob.x files in each directory pressure x. The three scripts eos.job, rhomb.job and tetra.job can either be started separately or together by runjob.x. The number of structure changes per pressure and the calculational parameters are set in elast.inelastp2. The following small programs and scripts are utilized by elast setup pressure: elast setup input.pl, setelast pressure ana elast pressure: Once all calculations are done, this script (in contrast to ana elast) has to be run in the elast directory. It requires the pressure x/z pressure.dat files created by init elast pressure. The final results for a given pressure are stored in pressure x/elast/result/outputs. Additionally the collective results for all pressure are stored in the directory elast results. If the script is called with the option plot (eg. ana elast pressure --plot) then postscript files for the fits using gnuplot are created in the pressure x/results/outputs directory. The following small programs and scripts are utilized by ana elast pressure: anaelast pressure Input Below are examples for case.inelastp1 and elast.inelastp2: top of file: case.inelastp RMT_reduction XC_PBE V_xc_potential -6 CORE_separation 9 RKMAX NUMBER_of_k-points 15 GMAX NM SPIN NM INST bottom of file
161 8.5. ELAST 143 Interpretive comments on this file are as follows: line 1: free format RMT RMT reduction by X % OLD RMT values taken from case.struct file in working directory line 2: free format V xc Exchange-correlation potential line 3: free format E sep Energy seperation for core and valence states line 4: free format RKMAX RKMAX value line 5: free format k-mesh Number of k-points in full BZ line 6: free format GMAX GMAX value line 7: free format SPIN NM non magnetic SPIN spin polarized line 8: free format INST OLD case.inst file is taken from working directory NEW new case.inst file is created line 9: Empty line line 10-x: free format a, p a p lattice constant in a.u. at pressure p (determined from e.g. a previous volume optimization...) pressure p written in pressure x/z pressure.dat The elast.inelastp2 file looks like: top of file: elast.inelastp iso 0 tet 0 trig
162 144 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION 2 ec spin.false. parallel.true bottom of file Interpretive comments on this file are as follows: line 1-3 (optional): free format distortion, n distortion if this line is given then the specified distortions will be calculated iso isotropic distortion tet tetragonal distortion trig trigonal(rhombohedral) distortion n number of structure changes n for a given type of distortion; the exact changes in the lattice constant are given on the following n lines (free format, lines 4-8 in the example above) 0 default values are taken ( 10%, 9%,..., 1%,0%,1%,...,9%,10% - 21 values) > 0 change in the lattice constant in % line 9 (optional): free format ec energy convergence criterion (if this line is missing then default value of is used) line 10 (optional): free format spin.false. no spin polarization (default).true. spin polarization (runsp lapw used instead of run lapw in eos.job, tetra.job and rhomb.job) line 11 (optional): free format parallel.false. default.true. if.machines exists in the elast/ directory then it will be copied into pressure x/eos, pressure x/tetra, pressure x/rhomb directories
163 8.6. FILTVEC FILTVEC (wave function filter / reduction of case.vector) filtvec reduces the information stored in case.vector files by filtering out a user-specified selection of wave functions. Either a fixed set of band indices can be selected which is used for all selected k-points (global selection mode), or the band indices can be selected individually for each selected k-point (individual selection mode). The complete wave function and band structure information for the selected k-points and bands is transferred to case.vectorf. The information on all other wave functions in the original file is discarded. The structure of the generated case.vectorf file is identical to that of the original case.vector file. Hence, it should be possible to use case.vectorf as substitutes for case.vector anywhere in the WIEN program package. (This has only been tested for lapw7.and filtvec.) To filter vector files from spinpolarized calculations, filtvec has to be run separately for both the spin-up and the spin-down files. filtvec has not yet been adapted for w2web Execution The program filtvec is executed by invoking the command: filtvec filtvec.def or filtvecc filtvec.def or x filtvec [-c] [-up dn] [-hf] In accordance with the file handling for lapw1 and lapw7 the input vector file case.vector is assumed to be located in the WIEN scratch directory, while the reduced output vector file case.vectorf is written to the current working directory. See filtvec.def for details Dimensioning parameters The following parameters are listed in file param.inc (r/c): NKPT LMAX LOMAX number of k-points maximum number of L values used (as in lapw1) maximum L value used for local orbitals (as in lapw1) The parameter LMAX and LOMAX must be set precisely as in lapw1; all other parameters must not be chosen smaller than the corresponding parameters in lapw1.
164 146 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION Input Two examples are given below. The first uses global selection mode; the second individual selection mode. I. Global Selection Mode top of file # number of k-points, k-points # number of bands, band indices end of file Interpretive comments on this file are as follows. line 1: line 2: free format kmax ik(1)... ik(kmax) free format nmax ie(1)... ie(nmax) Number of k-point list items, followed by the list items themselves. Positive list items mean selection of the k-point with the specified index; negative list items mean selection of a range of k-points with indices running from the previous list item to the absolute value of the current one. E.g. the sequence 2-5 stands for 2, 3, 4, and 5. Number of band index items, followed by the list items themselves. Again, positive list items mean selection of a single band index; negative list items mean selection of a range of band indices. II. Individual Selection Mode top of file : # number of k-points # k-point, number of bands, band indices # k-point, number of bands, band indices end of file Interpretive comments on this file are as follows. line 1: line 2: free format kmax free format ik nmax ie(1)... ie(nmax) the number of individual k-points to be selected. This number must be followed by any text, e.g. SELEC- TIONS or simply :, to indicate individual selection mode. First the index of the selected k-point, then the number of band index items, followed by the list items for the current k-point themselves. Positive list items mean selection of the band with the specified index; negative list items mean selection of a range of band indices running from the previous list item to the absolute value of the current one. E.g. the sequence 3-7 stands for 3, 4, 5, and 7. This input line has to be repeated kmax-times.
165 8.7. FSGEN FSGEN (Fermi-surface generation) Unfortunately there is no really versatile tool for Fermi surface generation or analyzing FS properties. We have collected here a series of small programs together with some description on how to proceed to generate 2D-Fermisurfaces within WIEN. As usually, you have to run an scf cycle and determine a good Fermi-energy. Good means here a Fermi-energy coming from a calculation with a dense k-mesh. You should than create a mesh within a plane of the BZ, where you want to plot the FS. Some utility programs like sc fs mesh, (fcc, bcc, cxz mon and hex are also available) may help you here, but only some planes of the BZ have been implemented so far. Please check these simple programs and modify them according to your needs. Copy the generated k-mesh fort.2 to case.klist. Run lapw1 with this k-mesh. Run spaghetti with input-options such that it prints the bands which intersect EF to case.spaghetti ene (line 10, see sec. 8.20) Edit case.spaghetti ene and insert a line at the top: NX, NY, x-len, y-len, NXinter, NYinter, Invers, Flip where NX, NY are the number of points in the two directions x-len, y-len are the length of the two directions of the plane (in bohr 1, you can find this in case.spaghetti ene) NXinter, NYinter: interpolated mesh, e.g. 2*NX-1 Invers: 0/1: mirrors x,y FLIP: 0/1: flips x,y to y,x Run spagh2rho < case.spaghetti ene to convert from this format into a format which is compatible with the case.rho file used for charge density plotting. It generates files fort.11, fort.12,... (for each band separately) and you should use your favorite plotting program to generate a contourplot of the FS (by using a contourlevel = 0). Alternatively you can use for plotting: Run fsgen lapw 11 xx save filename, which is a small shell script that can plot all fermi surfaces using the data-files fort.11, fort.12,... fort.xx generated in the previous steps. It requires the public domain package pgplot and the contour-plot program plotgenc. (The latter can be obtained from unsupported/, but you must have installed the pgplot library before.) 8.8 IRelast (Elastic constants for cubic, hexagonal, tetragonal, orthorhombic, monoclinic and rhombohedral cases) This program was contributed by: author: Morteza Jamal Ghods City-Tehran, Iran m Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. This package calculates elastic constants for cubic, hexagonal, orthorhombic, tetragonal, monoclinic and rhombohedral symmetry, respectively. It replaces previous versions on our unsupported software page.
166 148 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION The package is driven by the following scripts: set elast lapw: It prepares the whole calculation and should be run in a directory with a valid case.struct file. It finds the symmetry (S= C(cubic), H(hexagonal), T(tetragonal), O(orthorhombic), M(monoclinic) or R(rhombohedral) of the structure defined in case.struct and calls S set elast lapw. It creates the necessary subdirectories elast-constant, elast-constant/c11, elast-constant/c22,... and copies information of the present working directory into those new directories. command init lapw gets information to produce auto init lapw for automatic initialization. Then it gets the options for running the scf-cycle in the job files using S command run lapw. Finally, it generates the distorted structfiles and symm.job files, where symm stands for CUBIC, HEX, TETRA, ORTHO, MONO, and RHOM, using the S setupc11, S setupc22,... programs.. modifyjob lapw: allows you to edit and modify the previously created symm.job files. This step is not necessary when you have specified proper commandline options previously. calljob lapw : will execute all produced job files in elast-constant/c11/case, elast-constant/c22/case,... sequentially, but eventually you may run all those jobs by yourself on different machines in parallel, as these steps can take quite some time. Once all calculations are done: cal elast lapw: calls all S ana elast lapw and S ana elastc lapw scripts and determines the elastic constants C ij as well as the Voigt, Reuss, Hill, Bulk, Shear and Young modulus and the Poisson ratio (using data from the auxiliary program S InverseELC). Using data from the auxilliary programs S InverseELC and MassRho, S ana elast lapw calculate the Sound Velocity and the Debye temperature. The main output files are case.output elastic and INVELC-matrix, which contains the elastic compliance constants (invers of the elastic constants matrix). Finally, S ana elastorder lapw will check the sensitivity of the results to the order of the polynomial fit (stored in file output-order) and, for monoclinic crystals, the TWS program which transforms the elastic constants from WIEN2k to STANDARD Cartesian coordinates (in file STDELC-matrix). When you know your symmetry, you can simply call the corresponding series of scripts (S = C, H, T, O, M or R): S set elast lapw S modifyjob lapw S calljob lapw S ana elast lapw After a first run you may check your results using more datapoints (more or different displacements). This can be done conveniently by S setupcxx, where XX = 11, 12,..., which should be run in the corresponding elast-constant/cxx/case directory. When you specify in addition to new datapoints also your old displacements, these old results will be automatically taken into account in the analysis without recalculating them. On the other hand, when you want to change some computational parameters (RKmax, k- mesh, XC-potential) you can call command init lapw after S setupcxx and then modify your symm.job file specifying set answscf=no and a modified savename (eg. pbe rkm8). After these preparations, you can rerun symm.job and S ana elast lapw and check if your elastic constants are converged with respect to computational parameters. Additional information can be found in $WIENROOT/SRC IRelast/guide.
167 8.10. JOINT IRREP (Determine irreducible representations) This program was contributed by: Clas Persson Condensed Matter Theory Group,Department of Physics, University of Uppsala, Sweden Please make comments or report problems with this program to the WIEN-mailinglist. we will communicate the problem to the authors. If necessary, This program determines the irreducible representation for each eigenvalue and all your k-points. It is in particular useful to analyse energy bands and their connectivity. You need a valid vector file, but no other input is required. The output can be found in case.outputir and case.irrep. For nonmagnetic SO calculations you must set IPR=1 in case.inso. The output of this program is needed when you want to draw bandstructures with connected lines (instead of dots ). It will not work in cases of non-symmorphic spacegroups AND k-points at the surface of the BZ. See also $WIENROOT/SRC irrep/readme Execution The program irrep is executed by invoking the command: irrep [up/dn]irrep.def or x irrep [-so -up/dn -hf] Dimensioning parameters The following parameters are listend in file param.inc: LOMAX max. no. of local orbital. should be consistent with lapw1 and lapwso NLOAT number of different types of LOs MSTP max. step to describe k as a fraction MAXDG max. no. of degenerate eigenfunctions MAXIRDG max. no. of degenerate irr. representations FLMAX size of flag (FL) array (should be 4) MAXIR max. no. of irreducible representations NSYM max. no. of symmetry operations TOLDG min. energy deviation of degenerate states, in units of Rydberg 8.10 JOINT (Joint Density of States) This program was contributed by:
168 150. This program carries out the BZ integration using the momentum matrix elements case.symmat calculated before by optic. The interband or the intraband contributions to the imaginary part of the dielectric tensor (ɛ 2 ) can be computed. Alternatively, the DOS or the joint DOS can be derived. The output in case.joint can be plotted with any xy-plotting package or opticplot lapw or Curve lapw. Warning: Negative values for ɛ 2 may occur due to negative weights in Blöchl s tetrahedron method. For optional XMCD calculations (see OPTICS) an integration of the Brillouin zone is carried out using the momentum matrix elements from case.symmat1up and case.symmat2up (if both edges are present, otherwise only from case.symmat1up). The broadened and unbroadened spectra are written in files case.xmcd and case.rawxmcd: in these files, the first coloumn is the energy mesh, the second and third coloumns the left and right polarized absorption spectra, the fourth column the XMCD and the last is the XAS. For L 2,3, M 2,3, and M 4,5 edges, the broadened and unbroadened spectra for the single edges (useful for the application of Carra s and Thole s sum rules) are stored in case.broad1 and case.broad2 and case.raw1 and case.raw2, respectively, where 1 and 2 are refererred to the higher and lower energy core state Execution The program joint is executed by invoking the command: joint joint.def or x joint [-up dn] [-hf] Dimensioning parameters The following parameter is listend in files param.inc: NSYM order of point group MG0 number of columns (usually 9) Input An example is given below: top of file: case.injoint : LOWER,UPPER,upper-valence BANDINDEX : EMIN DE EMAX FOR ENERGYGRID IN ryd ev : output units ev / ryd XMCD : omitt these 4 lines for non-xmcd : core energies in Ry (grep :2P case.scfc) : core-hole broadening (ev) for both core states 0.1 : spectrometer broadening (ev) 4 : SWITCH 2 : NUMBER OF COLUMNS
169 8.10. JOINT : BROADENING (FOR DRUDE MODEL - switch 6,7) bottom of file Interpretive comments on this file are as follows: line 1: free format b1, b2, b3 lower, upper and (optional) upper-valence band-index (Setting b3 may allow for additional analysis (restricting the occupied bands from b1- b3) and in big cases it will reduce memory requirements. Otherwise set b3 equal b2) line 2: free format emin, de, emax Energy window and increment in Ry (emin must not be negative) line 3: free format units ev output in units of ev Ry output in units of Ry line 4: optional line for XMCD, must be omitted for normal optic; free format XMCD keyword for XMCD calculation, requires 3 more lines line 4xmcd: must be omitted for normal optic; free format E core1, E core2 lower and higher core energies (in Ry, get them using eg. grep :2P case.scf ) line 4xmcd: must be omitted for normal optic; free format broad core1, broad core2 lifetime broadening (ev) of lower and higher core state line 4xmcd: must be omitted for normal optic; free format broad spectrometer (Gaussian) broadening (ev) line 4+: free format switch 0 joint DOS for each band combination 1 joint DOS as sum over all band combinations 2 DOS for each band 3 DOS as sum over all bands 4 imaginary part of the dielectric tensor (ɛ 2 ) 5 imaginary part of the dielectric tensor for each band combination 6 intraband contributions: number of free electrons per unit cell assuming bare electron mass (calculated around E F ± 10 de as defined in input line 4), plasma-frequency
170 152 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION 7 in addition to switch 6 the contributions from different bands to the plasma frequency are analyzed. line 5: free format ncol number of columns line 6: free format broadening x,y,z broadening parameters (in units defined in line 3) for Drude-model The band analysis for all options (switches 0, 2, 5, and 7) has been improved: For each tensor component additional files are created, where each column contains the contributions from a single band or band combination. The file names are e.g..im eps xx 1,.Im eps xx 2, or.jdos 1 etc. where the number of files depend on the number of bands/band combinations. Warning: The number of band combinations might be quite large! 8.11 KRAM (Kramers-Kronig transformation) This program was contributed by: Kramers-Kronig analysis is carried out for the actual number of columns contained in the case.joint[up dn] file. For each real component its imaginary counterpart is created and vice versa. All dielectric tensor components can be found in file case.epsilon[up dn]. The real and imaginary parts of the optical conductivity (in /s) are written to file case.sigmak[up dn]. In addition, file case.absorp contains the real parts of the optical conductivity (in 1/(Ωcm) and the absorption coefficients. The loss function is also calculated (case.eloss), where for the previously calculated Plasma-frequency the intraband contributions can be added. Please note, that for spin-polarized calculations, the Kramers-Kronig analysis is NOT really additive, i.e. most quantities (like ɛ 1 ) cannot be obtained by simply adding the spin-up and dn results to get the total contribution (see equations in Ambrosch 06). Thus, one should add up both spin contributions of ɛ 2 (in case.jointup and case.jointdn) using addjoint-updn lapw (this will produce case.joint) before calling (non-spinpolarized) x kram. The 3 sumrules are also checked and written to case.sumrules. The output in case.epsilon[up dn] and case.sigmak[up dn] can be plotted with any xyplotting package, opticplot lapw or the OPTIC -task in w2web Execution The program kram is executed by invoking the command: kram kram.def or x kram [-up dn]
171 8.12. LAPW Dimensioning parameters The following parameters are listed in files param.inc: MAXDE maximum number of points in energy mesh MPOL fixed at Input An example is given below: top of file: case.inkram gamma for Lorentz broadening (in units selected in joint) 0.0 energy shift (scissors operator) (in units selected in joint) 1 add intraband contributions? yes/no: 1/ plasma frequencies (for each column in case.injoint) 0.20 Gammas for Drude terms (for each column in case.injoint) bottom of file Interpretive comments on this file are as follows: line 1: free format EGAMM Lorentz broadening (in energy units selected in joint) line 2: free format ESHIFT Energy shift (scissors operator) (in energy units selected in joint) line 3: free format INTRA 0 Intraband contributions are not added 1 Intraband contributions are added (requires plasma-frequencies calculated by joint using switch 6 ) ) line 4: free format EPL Plasma-frequencies (calculated by joint using SWITCH=6 for all columns) line 5: free format EDRU Broadening for Drude terms (for all columns) 8.12 LAPW3 (X-ray structure factors) This program calculates X-ray structure factors from the charge density by Fourier transformation. You have to specify interactively valence or total charge density (because of the different normalization of case.clmsum and case.clmval) and a maximum sinθ/λ value.
172 154 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION Execution The program lapw3 is executed by invoking the command: lapw3 lapw3.def or lapw3c lapw3.def or x lapw3 [-c ] Dimensioning parameters The following parameters are listend in file param.inc r or param.inc c : LMAX2 NCOM NRAD highest L in in LM expansion of charge and potential number of LM terms in density number of radial mesh points 8.13 LAPW5 (electron density plots) This program generates the charge density (or the potential) in a specified plane of the crystal on a two dimensional grid which can be used for plotting with an external contour line program of your choice. Depending on the input files one can generate valence (case.clmval) or difference densities (i.e. crystalline minus superposed atomic densities) using the additional file (case.sigma). In spinpolarized cases one can produce up-, dn- and total densities but also spin densities (difference up-dn). It is also possible to plot total densities (case.clmsum), Coulomb (case.vcoul), exchange-correlation (case.r2v) or total (case.vtotal) potentials, but in those cases the file lapw5.def has to be edited and you must replace case.clmval by the respective filename. The file case.rho contains in the first line npx, npy, xlength, ylength; and then the density (potential) written with: write(21,11) ((charge(i,j),j=1,npy),i=1,npx) 11 format(5e16.8) In order to get 3D-data for plotting with xcrysden, you can also use the script prepare xsf lapw (see Sect ). A recent extension by L.D. Marks allows to calculate STM immages (constant current) according to the Tersoff-Hamman approximation. Before doing this, you have to run lapw2 with a suitable energy window around the Fermi energy, which should correspond to the experimental bias voltage (x lapw2 -all EMIN EMAX. The output contains the z-position (height) of the tip, i.e. the position where the density has the specified value. It is strongly recommended that you use Run Programs Tasks Electron density plots from w2web, see the TiC example in Fig Execution The program lapw5 is executed by invoking the command: lapw5 lapw5.def or lapw5c lapw5.def or x lapw5 [-c -up dn]
173 8.13. LAPW Dimensioning parameters The following parameters are listend in file param.inc: LMAX2 NCOM NRAD NPT00 NSYM highest L in in LM expansion of charge and potential number of LM terms in density number of radial mesh points number of radial mesh points beyond RMT order of point group Input An example is given below. You may want to use XCRYSDEN by T.Kokalj to generate this file (see sect ) top of file: case.in # origin of plot: x,y,z,denominator # x-end of plot # y-end of plot # x,y,z nshells (of unit cells) # nx,ny RHO # RHO/DIFF/OVER; ADD/SUB or blank ANG VAL NODEBUG # ANG/ATU, VAL/TOT, DEBUG/NODEBUG NONORTHO # optional line: ORTHO NONORTHO GAUSS # this and the following lines are for STM mode # vibrational tensor STM 4.0D-5 3 # STM mode, density-level, axis (3=z-axis) SEMPER # optional output format for semper7 code FAST # optional, useful for a first crude check bottom of file Interpretive comments on this file are as follows: line 1: free format ix,iy,iz,idv The plane and section of the plot is specified by three points in the unit cell, an origin of the plot, an x-end and an y-end. The first line specifies the coordinates of the origin, where x=ix/idv,... in fractional units of the lattice vectors (except fc, bc and c lattices, where the lattice vectors of the conventional cell are used). Note the special meaning for STM mode described below. line 2: free format ix,iy,iz,idv coordinates of x-end line 3: free format ix,iy,iz,idv coordinates of y-end (The two directions x and y must be orthogonal to each other unless NONORTHO is selected). Since it is quite difficult to specify those 3 points for a rhombohedral lattice, an auxiliary program rhomb in5 is provided, which creates those points when you specify 3 atomic positions which will define your plane. You can find this program using Run Programs Other Goodies from w2web. The most convenient way to specify this plane (for a more complex structure) is using XCrysDen, where you can simply click on 3 atoms which will span the plane.
174 156 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION line 4: free format nxsh, nysh, nzsh specifies the number of nearest neighbor cells (in x,y,z direction) where atomic positions are generated (needs to be increased for very large plot sections, otherwise some atoms are not found in the plot) line 5: free format npx, npy specifies number of grid points in plot. npy=1 produces a file case.rho onedim containing the distance r (from the origin) and the respective density, which can be used in a standard x-y plotting program. line 6: format (2a4) switch, addsub switch RHO charge (or potential) plots, no atomic density is used (regular case) DIFF difference density plot (crystalline - superposed atomic densities), needs file case.sigma (which is generated with LSTART, see section 6.4) OVER superposition of atomic densities, needs file case.sigma addsub NO (or blank field): use only the file from unit 9 ADD adds densities from units 9 and 11 (if present), e.g. to add spin-up and down densities. SUB subtracts density of unit 11 (if present) from that of unit 9 (e.g. for the spin-density, which is the difference between spin-up and down densities). line 7: format (3a4) iunits, cnorm, debug iunits ATU density (potential) in atomic units e/a.u. 3 (or Ry) ANG density in e/å 3 (do not use this option for potentials) cnorm determines normalization factor VAL used for files case.clmval, r2v, vcoul, vtotal TOT used for files case.clmsum debug DEBU debugging information is printed (large output) line 8 (optional): free format noorth1 ORTHO (default) enforces directions to be orthogonal NONORTdirections can be arbitrary; use this option only if your plotting program supports non orthogonal plots (e.g. for XCRYSDENS). line 9 (this and the following lines are optional for the STM mode): free format VIBRATIONGAUSS suggested mode of vibrational smearing line 10: free format V11,V12,V22,V13,V23,V33 the size matrix components of the vibration tensor in units of distance squared, where the units are either ANG or ATU as defined earlier
175 8.14. LAPW7 157 line 11: free format MODE, level, axis MODE STM enables STM mode level the density level (typically e /ang 3 ). If this value is inappropriately chosen, the code will terminate with a statement: Cannot Bracket, sorry. axis the axis normal to the surface (e.g. 3 for z-axis). Note that in STM mode the z-coordinate specified in the first 3 lines is used as a starting value for the search of the z-position where the density has the value of level. This starting z-value has to be in the interstitial (vacuum) region. line 12 (optional): free format SEMPER this keyword puts the output in a format readable by the semper7 code (exchange of x,y order). line 13 (optional): free format FAST this keyword performs a fast approximate calculation for checking if your input (in particular the density level) is reasonable. In order to plot total densities or potentials (see cnorm as above) you have to create lapw5.def using x lapw5 -d, then edit lapw5.def and insert proper filenames (case.clmval, case.r2v, case.vcoul, case.vtotal) for units 9 and 11, and finally run lapw5 lapw5.def LAPW7 (wave functions on grids / plotting) lapw7 generates wave function data on spatial grids for a given set of k-points and electronic bands. lapw7 uses the wave function information stored in case.vector (or in reduced (filtered) form in case.vectorf which can be obtained from case.vector by running the program filtvec). Depending on the options set in the input file case.in7(c) one can generate the real or imaginary part of the wave functions, it s modulus (absolute value) or argument, or the complex wave function itself. For scalar-relativistic calculations both the large and the small component of the wave functions can be generated (only one at a time). The wave functions are generated on a grid which is to be specified in the input file(s). The grid can either be
176 158 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION any arbitrary list of points (to be specified free-formatted in a separate file case.grid) or any n-dimensional grid (n = 0...3). The operating mode and grid parameters are specified in the input file case.in7(c). As output lapw7 writes the specified wave function data for further processing e.g. for plotting the wave functions with some graphical tools such as gnuplot in raw format to case.psink. For quick inspection, a subset of this data is echoed to the standard output file case.outputf (the amount of data can be controlled in the input). In case, lapw7 is called many times for one and the same wave function, program overhead can be reduced, by first storing the atomic augmentation coefficients A lm, B lm (and C lm ) to a binary file case.abc. For the spin-polarized case two different calculations have to be performed using either the spin-up or the spin-down wave function data as input. It should be easy to run lapw7 in parallel mode, and/or to apply it to wave function data obtained by a spin-orbit interaction calculation. None of these options have been implemented so far. Also, lapw7 has not yet been adapted for w2web. Please note: lapw7 requires an LAPW basis set and does not work with APW+lo yet Execution The program lapw7 is executed by invoking the command: lapw7 lapw7.def or lapw7c lapw7.def or x lapw7 [-c] [-up dn] [-sel] [-hf] With the -sel option lapw7 expects data from the reduced (filtered) wave function file case.vectorf, otherwise the standard wave function file case.vector is used. The reduced vector file case.vectorf is assumed to resist in the current working directory, while the standard vector file case.vector (which may become quite large) is looked for in the WIEN scratch directory. For details see lapw7.def Dimensioning parameters The following parameters are listed in file param.inc (r/c): NRAD NSYM LMAX7 LOMAX number of radial mesh points order of point group maximum L value used for plane wave augmentation maximum L value used for local orbitals The meaning of LMAX7 is the same as that of LMAX2 in lapw2 and that of LMAX-1 in lapw1. Rather than being an upper bound it directly defines the number of augmentation functions to be used. It may be set different to LMAX2 in lapw2 or LMAX-1 in lapw1, but it must not exceed the latter one. Note that, the degree of continuity of the wave functions across the boundary of the muffin tin sphere is quite sensitive to the choice of the parameter LMAX7. A value of 8 for LMAX7 turned out to be a good compromise Input A sample input is given below. It shows how to plot a set of wave functions on a 2-dim. grid top of file D ORTHO # mode O(RTHOGONAL) N(ON-ORTHOGONAL) # x, y, z, divisor of origin # x, y, z, divisor of x-end # x, y, z, divisor of y-end
177 8.14. LAPW # grid points and echo increments NO # DEP(HASING) NO (POST-PROCESSING) RE ANG LARGE # switch ANG ATU AU LARGE SMALL 1 0 # k-point, band index bottom of file Interpretive comments on this file are as follows. line 1: A3,A1 mode flag mode the type of grid to be used ANY An arbitrary list of grid points is used 0D,1D,2D or 3D An n-dim. grid of points is used. n = 0, 1, 2, or 3. flag orthogonality checking flag (for n-dim. grids only) N The axes of the n-dim. grid are allowed to be non-orthogonal. O or The axes of the n-dim. grid have to be mutual orthogonal. blank line 2: free format (for n-dim. grids only) ix iy iz idiv Coordinates of origin of the grid, where x=ix/idv etc. in units of the conventional lattice vectors. line 3: free format (for n-dim. grids with n > 0 only) ix iy iz idiv Coordinates of the end points of each grid axis. This input line has to be repeated n-times. line 4: free format (not for 0-dim. grids) np... npo... In case of an n-dim. grid, first the number of grid points along each axis, and then the increments for the output echo for each axis. Zero increments means that only the first and last point on each axis are taken. In case of an arbitrary list of grid points, the total number of grid points and the increment for the output echo. Again a zero increments means that only the first and last grid point are taken. Hence, for n-dim. grids, altogether, 2 n integers must be provided; for arbitrary lists of grid points two intergers are expected. line 5: format(a3) tool DEP NO post-processing of the wave functions Each wave function is multiplied by a complex phase factor to align it (as most as possible) along the real axis (the so-called DEP(hasing) option). No post-processing is applied to the wave functions. line 6: format(a3,1x,a3,1x,a5) switch iunit whpsi switch RE IM the type of wave function data to generate The real part of the wave functions is evaluated. The imaginary part of the wave functions is evaluated.
178 160 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION iunit whpsi ABS ARG PSI ANG AU or ATU The absolute value of the wave functions is evaluated. The argument the wave functions in the complex plane is evaluated. The complex wave functions are evaluated. the physical units for wave function output Å units are used for the wave functions. Atomic units are used for the wave functions. the relativistic component to be evaluated LARGE The large relativistic component of wave function is evaluated. SMALL The small relativistic component of wave function is evaluated. line 7: free format iskpt iseig iskpt iseig The k-points for which wave functions are to be evaluated. Even if the wave function information is read from case.vectorf, iskpt refers to the index of the k-point in the original case.vector file! If iskpt is set to zero, all k-points in case.vector(f) are considered. The band index for which wave functions are to be evaluated. Even if the wave function information is read from case.vectorf, iseig refers to the band index in the original case.vector file! If iseig is set to zero, all bands (for the selected k-point(s)) which can found in case.vector(f) are considered. line 8: format(a4) this line is optional handle augmentation coefficient control flag SAVE or Augmentation coefficients are stored in case.abc). No wave function data is generated in this case. This option is only allowed if a single STOR(E) wave function is selected in the previous input line. READ Previously stored augmentation coefficients are read in (from or case.abc). This option is only allowed if the same single wave function as the one who s augmentation coefficients are stored in case.abc REPL(OT) is selected in the previous input line. anythingaugmentation coefficients are generated from the wave function information else in case.vector(f) MINI (Geometry minimization) This program is usually called from the script min lapw and performs movements of the atomic positions according to the calculated forces (please read Sec ). It generates a new case.struct file which can be used in the next geometry/time step. Depending on the input options, mini helps to find the equilibrium positions of the atoms or performs a molecular dynamics simulation (which might take very long time). For finding the equilibrium positions different methods are available. We recommend PORT, a reverse-communication trust-region Quasi-Newton method from the Port library (http: // Gay 1983), which was implemented by L.D.Marks edu). It minimizes the total energy and NOT the forces (using the forces as derivative of E vs. atomic positions). In cases when energy and forces are not compatible, eg. because of numerical noise due to limited scf convergence, small RKmax or crude k-mesh, PORT may fail. An interesting alternative is a sophisticated modified steepest-descent method (NEW1), which minimizes the
179 8.15. MINI 161 forces (does not use the total energy). Eventually a damped Newton dynamics is also available. The forces are read from a file case.finm, while the history of the geometry optimization or MD is stored in case.tmpm One can constrain individual positions in case.inm or define linear constrains for several positions using case.constraint (thanks to B.Yanchitsky (Kiev, for details see comments in the SRC templates/template.constraint file). In case of calculations with linear constrains one should use NEW1 (in case.inm). When constraining individual positions and using PORT, one should after modifications in case.inm rerun x pairhess -copy (which copies.minpair to.minrestart and.min hess) Execution The program mini is executed by invoking the command: mini mini.def or x mini Dimensioning parameters The following dimensioning parameters are collected in the file param.inc: MAXIT NRAD NCOM NNN NSYM maximum number of geometry steps number of radial mesh points number of LM terms in density number of neighboring atoms for nn order of pointgroup Input Two examples are given below; one for a PORT geometry optimization, and one for molecular dynamics using a NOSE thermostat: Input for geometry optimization: top of file: xxx.inm PORT (PORT/NEWT tolf step0 (a4,2f5.2)) ( 1..3:delta, 4:BO/eta(1=friction zero)) ( 1..3=0 constraint) bottom of file Interpretive comments on this file are as follows. line 1: format(a4,2f5.2) MINMOD Modus of the calculation PORT Geometry optimization with reverse-communication trust-region Quasi-Newton routine from the Port library. Recommended option. NEW1 Performs geometry optimization with sophisticated steepest-descent method with automatic adaptation of stepsize (still experimental, but when PORT fails, an interesting alternative) NEWT Performs geometry optimization with damped Newton scheme according to
180 162 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION TOLF STEP0 BFGS R τ+1 m = Rm τ + η m (Rm τ Rm τ 1 ) + δ m Fm τ where Rm τ and Fm τ are the coordinate and force at time step τ. When the force has changed its direction from the last to the present timestep (or is within the tolerance TOLF), η m will be set to 1 η m. Please see also the comments in Sect Performs geometry optimization with the variable metric method of BFGS. This option works only when a quadratic approximation is a good approximation to the specific potential surface. Obsolete. Force tolerance, geometry optimization will stop when all forces are below TOLF. Initial Trust-region radius. Determines size of first geometry step. line 2: free format DELTA(1-3) ETA For PORT (and BFGS): Precondition parameters: rescales the gradient and thus determines the size of the geometry steps For NEWT/NEW1: x,y,z-delta parameters. Determines speed of motion. Good values must be found for each individual system. They depend on the atomic mass, the vibrational frequencies and the starting point (see Sect ). DELTA(i) = 0 constrains the corresponding i-th coordinate (for PORT: after setting a DELTA(i)=0, also rerun pairhess to set a proper Hessian). The delta-x,y,z correspond to the global coordinates (the same as the positions in case.struct and the forces :FGL from case.scf). Whenever you change these DELTA(i) you must remove file case.tmpm! For NEWT: damping (friction) parameter. ETA=1 means no friction, ETA=0 means no speed from previous time steps PORT: changes the strength of the bonds when running pairhess and ZWEIGHT is negative (see the pairhess description), otherwise not used NEW1: ETA is not used >>> line 2: must be repeated for every atom Input for Molecular dynamics: top of file: nbc.inm NOSE (NOSE/MOLD (a4)) (Masse, delta t, T, nose-frequency) bottom of file Interpretive comments on this file are as follows. line 1: format(a4,f5.2) MINMOD MOLD NOSE Modus of the calculation Performs next molecular dynamics timestep Performs next molecular dynamics timestep using a NOSE thermostat line 2: free format
181 8.16. NMR 163 MASS TIMESTEP Atomic mass of i th atom Time step of MD (in atomic units, depends on highest vibrational frequencies) TEMP Simulation Temperature (K) NOSF Nose-frequency >>>line 2: must be repeated for every atom 8.16 NMR (chemical shielding) This program was contributed by: Robert Laskowski Inst.Materials Chemistry TU Vienna A-1060 Vienna, AUSTRIA Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. This program calculates the orbital contribution to the NMR (chemical) shielding (the total shielding for insulators). It will first calculate the perturbation of the wave functions due to the magnetic field (first order perturbation theory) and the resulting current. This induced current is then integrated (via the Biot-Savart law) to obtain the magnetic shielding at a nucleus. For details see Laskowski,Blaha 2012, 2012a, 2013, 2014). The program does not need to be called by the user, but it is interfaced with the script x nmr lapw (all details can be found in sect. 5.6), where the different modes/options can be selected as switches. It can run in k-point as well as in mpi-parallel mode. It does not have its own input file, but a modified case.in1 is necessary, which needs to be generated by x nmr lapw -mode in1. We need an extended basis set with several local orbitals (up to very high energies) for all l + 1 states, where l refers to the maximal chemical l of the specific atom (l=1 for C, but 2 for Fe,..). In addition ALL eigenvalues must be calculated, which increases the cpu-time of lapw1 as compared to a normal scf-calculation. In addition lapw1/2 and nmr is run for 7 different k-meshes, an unshifted one as well as plus/minus shifted meshes in x, y and z direction OPTIC (calculating optical properties) This program was contributed by:
182 164 theoretical background is described in detail in Ref. Abt 1994 and Ambrosch-Draxl 06 (Please cite the latter when publishing optics results!). The calculation of optical properties requires a dense mesh of eigenvalues and the corresponding eigenvectors. For that purpose start kgen and generate a fine k-mesh (with many k-points). Run lapw1 and then lapw2 with the option FERMI (Note: You must also put TETRA / with value=101. for metallic systems case.in2) in order to generate the weight-file. After the vector-file has been generated by lapw1 run optic in order to produce the momentum matrix elements. Then the program joint carries out the BZ integration and computes the imaginary part of the complex dielectric tensor. In order to obtain the real part of the dielectric tensor kram may be executed which uses the Kramers-Kronig relations. The program optic generates the symmetrized squared momentum matrix elements M i =< n k p. e i n k > 2 between all band combinations for each k-point given in the vector-file and stores them in case.symmat. For the orthogonal lattices the squared diagonal components can be found in the file case.mat diag. For non-orthogonal systems all 6 components (M j ) M k can be calculated according to the symmetry of the crystal. In systems without inversion symmetry the complex version opticc must be executed. The matrix elements (and the imaginary part of the dielectric tensor) are given per spin in case of the spin-polarized calculation and as a sum of both spin directions if the calculation is nonspinpolarized. Due to spin-orbit coupling imaginary parts of the nondiagonal elements may occur in spinpolarized cases. Thus in general, up to 9 components can be calculated at the same time. Since version WIEN2k 11.1 an option for the calculation of XMCD (X-ray magnetic circular dichroism) has been added by Lorenzo Pardini Please cite Pardini et al when using XMCD and check the paper for further details. In the case of the XMCD calculation, the momentum matrix elements in the dipole approximation between the selected core state and conduction states are stored in case.symmat1up (higher energy core state, eg. L 3 ) and case.symmat2up (lower energy core state, eg. L 1 ) for each k-point and every band. For K, L 1, and M 1 edges, only case.symmat1up is written, since in these cases there is only one edge, whereas both case.symmat1up and case.symmat2up are written for the remaining cases. XMCD calculation can be only performed for system with spin-polarized AND spin-orbit set up. In order to calculate XMCD and x-ray absorption spectra, eigenvalues must be evaluated over a mesh in the whole Brillouin zone; for that porpouse, the following procedure should be followed: copy case.struct to case.ksym (cp case.struct case.ksym) and remove all the symmetry operations but the identity; generate a k-mesh in the whole Brilouin zone (x kgen -so); change TOT to FERMI in case.in2c; set IPRINT=1 in case.inc to activate core-wavefunction output; for metallic systems, put TETRA with value 101; execute runsp lapw -so -s lapw1 -e lcore;
183 8.17. OPTIC 165 run optic: x optic -c -so -up; run joint: x joint -up. You must not use p-1/2 relativistic LOs in LAPWSO, since this basis is not supported on OPTICS yet Execution The program optic is executed by invoking the command: optic(c) optic.def or x optic [-c -up dn -so -p -hf] Recommended procedure for spin-orbit coupling: In order to get the correct matrix elements, the files case.vectorso[up dn] have to be used. For that purpose the following procedure is recommended: run SCF cycle: run[sp] lapw -so generate a fine k-mesh for the optics part: x kgen [-so (if case.ksym has been created by symmetso) ] change TOT to FERMI in case.in2c execute run[sp] lapw -so -s lapw1 -e lcore with this fine k-mesh run optic: x opticc -so [-up] run joint: x joint [-up] run kram: x kram [-up] In cases of non-spinpolarized spin-orbit calculations WITHOUT inversion symmetry one must do some tricks and mimick a spinpolarized calculation: cp case.vsp case.vspup cp case.vsp case.vspdn cp case.vectorso case.vectorsoup x lapw2 -fermi -so -c cp case.weight case.weightup cp case.weight case.weightdn x optic -so -up x joint -up Due to the paramagnetic weight files (which are normalized to 2 electrons per band instead of one) all your results (joint/sigma...) must be divided by a factor of two. Note: In spin-polarized cases with spin-orbit only one call to optic, joint and/or kram (either up or down) is necessary, since the spins are not independent any more and both vector-files are used at the same time Dimensioning parameters The following dimensioning parameters (listed in param.inc r and param.inc c) are used: LMAX LOMAX NRAD NSYM highest l+1 in basis function inside sphere (reducing LMAX to 4 or 5 may dramatically speed-up optics for large cases, but of course the matrix elements will be truncated and do not have full precision) highest l for local orbital basis (consistent with input in case.in1) number of radial mesh points order of point group
184 166 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION Input An example is given below: top of file: case.inop : NKMAX, NKFIRST : EMIN, EMAX, NBvalMAX XMCD 1 L23 : optional line: for XMCD of 1st atom and L23 spectrum 2 : number of choices (columns in *symmat) 1 : Re xx 3 : Re zz OFF : ON/OFF writes MME to unit bottom of file Interpretive comments on this file are as follows: line 1: free format nkmax, nkfirst maximal number of k-points, number of k-point to start calculation line 2: free format emin, emax absolute energy range (Ry) for which matrix elements should be calculated nbvalmax optional input. Setting this to the number of occupied bands (see case.output2) will reduce cpu-time of optics (for large cases, MM only between occupied and empty bands) line 3: optional line, must be omitted for normal optic; free format XMCD fixed keyword to indicate XMCD calculation. You should also use NCOL=6 natom atom number (from case.struct file) for which XMCD should be calculated edge specify the edge: must be K, L1, L23, M1, M23 or M45 line 3+: free format ncol number of choices (columns in case.symmat) line 4+: free format icol column to select. Choices are: 1... Re < x >< x > 2... Re < y >< y > 3... Re < z >< z > 4... Re < x >< y > 5... Re < x >< z > 6... Re < y >< z > 7... Im < x >< y > 8... Im < x >< z > 9... Im < y >< z > Options 7-9 apply only in presence of SO, options 4-6 only in nonorthogonal cases.
185 8.18. OPTIMIZE 167 line 5: free format IMME, NATOMS (optional input) IMME NATOMS OFF/ON; optionally prints unsquared momentum matrix elements to unit 4 number of atoms for which the opt. matrix elements should be calculated (The index of the atoms is read in the next line). Please note, that since we need the squared matrix elements, the sum of ɛ 2 using atom 1 and atom 2 separately is NOT the same as using atom 1 and 2 together, since we miss crossterms. Nevertheless this can be a useful option to analyze the origin of certain peaks in ɛ 2. I recommend to repeat this analysis for all possible combinations, and also for a list of all atoms, since this shows the effect of the interstitial (and crossterms involving the interstitial). line 6: (optional) free format IATOMS List of NATOMS atoms for which the opt. matrix elements should be calculated (see above) OPTIMIZE (Volume, c/a or 2-4 dimensional lattice parameter optimization) This program generates a series of new struct files corresponding to different volumes, c/a ratios, or otherwise different lattice parameters (depending on your input choice) from an existing struct file (either case initial.struct or case.struct). (When case initial.struct is not present, it will be generated from the original case.struct. Furthermore it produces a shell script optimize.job. You may modify this script and execute it. Further analysis of the results (at present only equilibrium volume or c/a ratio are supported in w2web) allows to find the corresponding equillibrium parameters (see Sec.5.3.1) Execution The program optimize is executed by invoking the command: optimize optimize.def or x optimize Input You have to specify interactively which task should be performed (volume, c/a, b/a optimization, or full optimization for tetragonal, orthorhombic or monoclinic structure), how many cases you want to do and how large the change (+/- xx %) should be for each case QTL (calculates special partial charges and population matrices) This program was contributed by:
186 168 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION P. Novák and J.Kuneš Inst. of Physics, Acad.Science, Prague, Czeck Republic Please make comments or report problems with this program to the WIEN-mailinglist. we will communicate the problem to the authors. If necessary, qtl creates the input for calculating total and projected density of states of selected atoms (with a limit of 28 different atoms) and selected l-subshells. It thus provides similar data as lapw2 -qtl, but it allows for additional options. In particular it supports calculation of DOS projected on relativistic states p 1/2, p 3/2, d 3/2, d 5/2, f 5/2, f 7/2, DOS projected on states in a rotated coordinate system and DOS projected on individual f states. qtl also allows to calculate population matrix and energy resolved population matrix. Comparing to lapwdm population matrix, the matrix created by qtl may contain also the cross terms between different orbital and spin numbers and it can be energy resolved. Important option of the qtl is the symmetrization that makes the calculation longer, but must be switched on whenever the quantities, which are not invariant are calculated. Detailed description may be found in QTL - technical report by P. Novák. The calculation is based on the spectral decomposition of a density matrix on a given atomic site and its transformation to the required basis. The output is written to case.qtl [up/dn]. For the DOS calculation the file case.qtltext [up/dn] is created in which the ordering of partial charges is given. Please note, that in contrast to case.qtl [up/dn] from x lapw2 -qtl the total partial charge of an atom is NOT multiplied with its multiplicity and contains only the sum of the requested l,m terms (eg. s,p,d) and thus not all contributions. Also the interstital charge will usually be NOT correct Execution The program qtl is executed by invoking the command: x qtl [ -up/dn -so -p -hf] or qtl qtl.def Input A sample input (a default is created automatically during init lapw for case.inq is given below top of file: case.inq Emin Emax 2 number of selected atoms iatom1 qsplit1 symmetrize loro nl1 p d iatom2 qsplit2 symmetrize loro nl2 s p d f new axis z bottom of file Interpretive comments on this file are as follows:
187 8.19. QTL 169 Table 8.93: Possible values of QSPLIT and their interpretation QSPLIT meaning -2 DOS in basis according to ISPLIT from case.struct -1 DOS in relativistic j, l, s, m j > basis 0 DOS in relativistic j, l, s, m j > basis, summed over m j 1 DOS in l, m l > basis (no symmetry) 2 DOS in basis of real orbitals (no symmetry) 3 axial symmetry 4 hexagonal symmetry 5 cubic symmetry 6 user written unitary transformation 88 population matrix, no < l l > crossterms corresponds to ISPLIT=88 99 full population matrix including < l l > crossterms (as ISPLIT=99) line 1: free format emin,emax energy window line 2: free format natom number of atoms selected for calculation (max. 28, if more are needed you have to run qtl in junks ) line 3: free format iatom, QSPLIT, symmetrize, loro iatom QSPLIT symmetrize loro line 4: free format Nl(iatom), (l(iatom,i),i=1,nl(iatom)) Nl l line 5: free format hz, kz, lz integer, index of atom integer, analog of ISPLIT in case.struct: see below integer, =0 (no symmetrization), 1 (symmetrization) integer =0 original coord. system preserved =1 (new z axis) =2 (new z and x axes) number of orbital numbers selected for calculation orbital numbers selected for calculation for atom iatom real*8, direction of new axis z (if loro=1,2) Lines starting from line 3 are repeated for each selected atom. Line 5 only appears when calculation in new coordinate system is required (loro 0). Axis z in this system is along hz,kz,lz (in units of the lattice vectors, need not be normalized). If not only the z axis, but also the x axis need to be specified, then loro must be equal to 2 and additional line hx, kx, lx (real*8) giving the direction of the new axis x, perpendicular to the new axis z must appear. For relativistic splitting (QSPLIT=0,-1) this rotation is ignored and z points along the direction of magnetization as defined in case.inso. Indices of selected atoms, as well as the orbital numbers, must form an ascending sequence. For QSPLIT=6 (unitary transformation prepared by user) the unitary matrices are read as in WIEN2k 07 qtl: For the i-th atom selected for qtl calculation, they are stored in case.cf$i and ordered according to increasing l. The unitary transformation matrix must rotate from the standard lms -basis to the desired one. A few examples (e.g. jjz, lms, or e g t 2g ) are supplied with
188 170 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION the code in $WIENROOT/SRC templates/template.cf * and must be copied to case.cf$i. For less common cases these must be generated by hand Output The results in file case.qtl[up/dn] are written in the same format as lapw2 file case.qtl[up/dn] and thus they may be directly used by tetra. The data for the interstital DOS correspond to n = nat + 1 (nat is number of atom types). The ordering of densities for all selected atoms is summarized in the file case.qtltext[up/dn]. The qtltext file that corresponds to the input data given above is: Ordering of DOS in QTL file for: HoMnO3 (Munoz) atom 1 ordering of projected DOS p,px,py,pz, real basis d,dz2,d(x2-y2),dxy,dxz,dyz, real basis atom 3 ordering of projected DOS s p,pxy,pz, axial basis d,dz2,d(x2-y2),d(yz+xz),dxy, axial basis f,a2,[x(t1)+y(t1)],z(t1),[ksi(t2)+eta(t2)],zeta(t2), axial basis A2=xyz x(t1)=x(x2-3r2/5) y(t1)=y(y2-3r2/5) z(t1)=z(z2-3r2/5) ksi(t2)=x(y2-z2) eta(t2)=y(z2-y2) zeta(t2)=z(x2-y2) Data for interstital DOS correspond to atom index 8 The output for the population matrix integrated over energy is written to case.dmat [up/dn] that has the same format as analogous file calculated by lapwdm SPAGHETTI (energy bandstructure plots) This program generates an energy bandstructure plot (postscript file case.spaghetti ps and xmgrace file case.bands.agr) using the eigenvalues printed in case.output1 or case.outputso (with switch -so) or case.energy (with switch -enefile). Using the SCF potentials one runs x lapw1 -band with a special k-mesh (case.klist band) along some high-symmetry lines (some sample inputs can be found in SRC templates/*.klist or you create your own k-mesh using Xcrysden). As an option, one can emphasize the character of the bands by additionally supplying corresponding partial charges (file case.qtl which can be obtained using x lapw2 -qtl -band, see 7.7). This will be called band-character plotting below, in which each energy is drawn by a circle whose radius is proportional to the specified character of that state. It allows to analyze the character of bands (see also figures 3.12 and 3.13). The file case.bands.agr can be opened directly with xmgrace. Within xmgrace, all features of the plot, such as the plot range, the plot size, line properties (style, thickness and color), axis properties, labels, etc. can easily be changed by either using the menu (submenus of the Plot menu) or double-klicking on the corresponding part of the figure. The size of the characters for a band-character plot can be changed in the menu Plot / Graph appearance / Z normalization. The figures can directly be printed or exported in eps, jpg, png and other formats, via the menus File / Print setup and File / Print.
189 8.20. SPAGHETTI 171 C.Persson has modified this program and it allows now also to draw connected lines. For this purpose it uses the irreducible representations (from file case.irrep produced by program irrep together with a table of compatibility relations to decide which points should be connected (non-crossing rule!). (Note: This option will NOT work on the surface of the BZ for non-symmorphic spacegroups, because the corresponding group-theory has not been implemented.) The presence of incompatible case.irrep or case.qtl files (from a previous run or qtls from a DOS calculation) may crash spaghetti. In such cases it is necessary to remove these files explicitly. It is strongly recommended that you use Run Programs Tasks Bandstructure from w2web Execution The program spaghetti is executed by invoking the command: spaghetti spaghetti.def or x spaghetti [-up dn] [-so] [-p] [-hf] [-enefile] The -p switch directs spaghetti to use the case.output1 * files of a k-point parallel lapw Input An example is given below: top of file: case.insp ### Figure configuration # paper offset of plot # xsize,ysize [cm] # major ticks, minor ticks # character height, font switch # line width, line switch, color switch ### Data configuration # energy range, energy switch (1:Ry, 2:eV) # Fermi switch, Fermi-level (in Ry units) # number of bands for heavier plotting 1, # jatom, jtype, size of heavier plotting bottom of file Interpretive comments on this file are as follows: line 1: free format test test line must start with ###. Begin of figure description. This tests also if you use the new input (different from WIEN97 or early WIEN2k versions) line 2: free format xoffset, yoffset xoffset yoffset x offset (in cm) of origin of plot y offset (in cm) of origin of plot line 3: free format xsize,ysize xsize plotsize in x direction (cm)
190 172 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION ysize plotsize in y direction (cm) line 4: free format eincr, mtick eincr mtick energy increment where y-axis labels are printed (major ticks) number of minor ticks of y-axis line 5: free format charh, font charh scaling factor for size of labels font 0 no text 1 Times and Symbol 2 Times,Times-Italic and Symbol 3 Helvetica, Symbol, and Helvetica-Italic 4 include your own fonts in defins.f line 6: free format linew, ilin, icol linew line width ilin 0 dots or open circles 1 lines 2 lines and open circles 3 lines and filled circles icol 0 black 1 one-color plot 2 three-color plot 3 multi-color plot 4 multi-color plot,one color for each irred. representation line 7: free format test test line must start with ###. Begin of data description. line 8: free format emin, emax, iunits emin emax iunits energy minimum of plot energy maximum of plot 1 energies in Ry (internal scale) 2 energies in ev with respect to E f line 9: free format iferm, efermi iferm 0 no line at EF 1 solid line at EF 2 dashed line at EF 3 dotted line at EF
191 8.21. TELNES3 173 efermi Fermi energy (Ry); can be found in the respective case.scf file. If set to 999., E f is not plotted (and iunits=2 cannot be used) line 10: free format nband1, nband2 lower and upper band index for bands which should show bandcharacter plotting (if case.qtl is present and the proper switch is set, see below). In addition the corresponding x and y coordinates are written to file case.spaghetti ene (which can be used for plotting with an external xy-plotting program). line 11: free format jatom, jcol, jsize jatom jcol jsize If a case.qtl file is present, jatom indicates the atom whose character (selected by jcol) is used for band-character plotting (dots are replaced by circles with radii proportional to the corresponding weight, requires ilin=0,2,3). If set to zero or if case.qtl is not present, bandcharacter plotting does not occur. specifies the column to be used in the respective QTL-file. 1 means total, 2... s, 3... p,... The further assignment depends on the value of ISPLIT set in case.struct. (ignored for jatom=0). The description can be found in the header of case.qtl. size factor for radii of circles used in band-character plotting if line 11 is repeated, one can average the QTLs for different atoms (but with identical jcol and jsize) TELNES3 (calculation of energy loss near edge structure) This program was contributed by: Kevin Jorissen and Cécile Hébert Ecole Polytechnique Federale de Lausanne Please make comments or report problems with this program to the WIEN-mailinglist. we will communicate the problem to the authors. If necessary, The TELNES3 program calculates the double differential scattering cross section (DDSCS) on a grid of energy loss values and impulse transfer vectors. This double differential cross section is integrated to yield a differential cross section, which is written to file. The differential cross section is either a function of energy (ELNES integrated over impulse transfer q); or a function of impulse transfer (ELNES integrated over energy loss E), which shows the angular behavior of scattering. The DDSCS is calculated as described in a forthcoming publication by K. Jorissen, C. Hebert, and J. Luitz. (The Ph.D. thesis of K. Jorissen ( also describes the formalism onto which TELNES3 is built in great detail.) This formalism allows calculation of relativistic EELS including transitions of arbitrary order (i.e., non-dipole transitions). It takes into account the relative orientation between sample and beam. If this is not
192 174 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION necessary (because the crystal is isotropic, or the sample is polycrystalline), the formula may be integrated over 4π, simplifying the calculation. Both scenarios are implemented in TELNES3. A note to our faithful fans from the early days: it used to be necessary to play such tricks as recompiling lapw2 with lxdos=3 ; to create k-meshes without symmetry ; and to edit case.struct and set ISPLIT to 99. This is no longer necessary. Just sit back, relax, and press the buttons in w2web. The integration with the package qtl will do the job Execution Execution The program telnes3 is executed by invoking the command: telnes3 telnes3.def or x telnes3 [-up -dn] Input TELNES3 requires one input file - case.innes. We recommend using InnesGen TM of w2web to create this input file in a clear and intuitive way. If you wish to manually edit the file, please refer to the following description. Please note that input files created for TELNES2 may or may not work with TELNES3, depending on which optional keywords were used. There isn t a shred of compatibility with the old TELNES program. The file case.innes consists of two parts: a first block with required input, and a second block with optional input. In fact, the second part may be omitted altogether. The simplest input file looks like this: Graphite C K edge of first atom. 1 (atom) 1, 0 (n, l core) 285 (E-Loss of 1st edge in ev) 300 (energy of the incident electrons in kev) (the energy mesh) (collection semiangle, convergence semiangle, both in mrad) 10 1 (NR, NT, defining the integration mesh in the detector plane) 0.8 (spectrometer broadening in ev) END This first part of the file is not formatted and contains the following information:
193 8.21. TELNES3 175 line value explanation 1 Graphite... Title (of no consequence for the calculation) 2 1 Atom number as given in case.struct (the index which numbers inequivalent atoms) main and orbital quantum number n and l of the core state; eg. 1 0 stands for 1 s energy of the edge onset in ev (here for the C K edge) beam energy in kev energy mesh given as E min E max E step ; all values in ev. 0.0 is the edge threshold detector collection semiangle and microscope convergence semiangle in mrad parameters NR and NT which determine the mesh used for sampling the distribution of Q-vectors allowed by collection and convergence angles spectrometer broadening FWHM in ev 10 END keyword telling the program that there is no more input to read. Optional keywords and values must be inserted before this line! There are many other parameters that control the calculation, most of which are set to reasonable default values. To use these advanced parameters, add corresponding keywords before the END keyword. We recommend using InnesGen TM of w2web to create this input file. Currently, the keywords listed below may be used. Although only the first four characters of each keyword are read, we recommend using the full keyword for clarity. VERBOSITY n eg. : 1 Specifies how much output you ll get. n must be 0 (only basic output; default), 1 (medium output) or 2 (full output, including more technical information). ATOMS n1 n2 eg. : 1 3 (default : 1 0 == 1 mult(natom) ) The atom number on line 2 (see above) corresponds to a class of equivalent atoms in case.struct. Equivalent positions n1 to n2 will contribute to the spectrum (default : sum over all atoms in the equivalency class). Since all equivalent atoms have identical electronic structure up to a symmetry operation, this will simply yield a prefactor (n2-n1+1) for the orientation averaged spectrum, but as each equivalent atom has a different orientation with respect to the beam, this setting will influence the shape of an orientation sensitive spectrum. DETECTOR POSITION theta_x theta_y eg. : (default : 0 0) By default, the detector is aligned with the incoming beam - i.e., source, sample, and detector are connected by a straight line. This card shifts the detector in a plane perpendicular to the incoming beam. The shift is expressed as an angle in mrad. If one draws a line between source and sample, and another line from the sample to the center of the detector aperture, these 2 lines will form an angle of theta 2 x + theta 2 y mrad. MODUS m eg. : angles (default is energy)
194 176 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION The output is a spectrum as a function of energy if m=energy. The output is a spectrum as a function of impulse transfer/scattering angle if m=angle. SPLIT splitting energy eg. : 2.7 If the initial state has an orbital quantum number larger than 0, it will generate two superposed edges: one corresponding to j = l 1/2, and one corresponding to j = l + 1/2 (eg., for the 2p initial state we have a L3 and a L2 edge). The splitting energy sets the energy separation of the two edges and should be given in ev (here, L3 is at the energy specified in the beginning of case.innes, and L2 is 2.7 ev higher). By default (keyword omitted), the splitting energy is calculated by the program. It is generally quite accurate. BRANCHING RATIO branching ratio eg. : 1.4 The branching ratio is a scaling factor (eg., here the ratio of intensities L3/L2 would be set to 1.4). By default (keyword omitted), the branching ratio is set to its statistical value of (2l + 2)/2l. NONRELATIVISTIC This key tells the program not to use the relativistic corrections to the scattering cross section. This option generates spectra identical to output of the old TELNES program. This produces incorrect results in many cases. By default, relativistic calculations are done. INITIALIZATION make_dos write_dos eg. N N (default : Y Y) make_rot.mat. write_rot.mat eg. Y N (default : Y Y) TELNES3 needs many ingredients for its calculations, and this key defines how it gets two of them: the density of states, and the rotation matrices (used for transforming q-vectors from one atom to an equivalent atom). The first entry says whether or not the ingredient has to be calculated (Y : calculate; N : read from file), and the second entry says whether or not the ingredient has to be written to file (Y : write; N : don t write). If make dos=y, a file case.qtl must be present from which the dos will be calculated. If make dos=n, then either a file case.dos or a file case.xdos containing the (x)dos must exist. If make rot.mat=n, a file case.rotij containg the rotation matrices must exist. If write rot.mat=y, a file case.rotij is written. If write dos=y, a file case.dos or case.xdos is written. The calculation of the rotation matrices is computationally negligible, but it is recommended to write the xdos to file and not calculate it over and over again. QGRID qmodus eg. L (U by default) theta_0 eg (no default value) ) A collection angle α and convergence angle β allow scattering angles up to α + β and a corresponding set of Q-vectors. This set (a disk of radius α + β) is sampled using a discrete mesh. Three types of meshes are implemented : U a uniform grid, where each Q-vector samples an equally large part of the disk. Sampling is set up by drawing NR equidistant circles inside the big circle, and choosing (2i 1)NT points on circle i, giving NR 2 NT points in total.
195 8.21. TELNES3 177 L a logarithmic grid with NR circles. The distance between circles increases exponentially. There are (2i 1)NT points on circle i, and NR 2 NT points in total. Circle i is at radius theta 0 e ((i 1)dx), where dx depends on NR, α and β. 1 a one dimensional logarithmic mesh; there are NR circles at exponential positions, and only one point on each circle (so NR points in total). This means we sample a line in the detector*beam plane. An economic way of getting spectra as a function of scattering angle in cases with symmetric scattering. The line specifying theta 0 is to be omitted for the U grid. ORIENTATION SENSITIVE g1 g2 g3 (eg ) (no default value) This key tells the program not to average over sample to beam orientations, but to use the particular sample to beam orientation defined by the three Euler angles (to be given in degrees). The Euler angles (0,0,0) means that the electron beam is parallel to the c-axis of the crystal and the 3 angles rotate with respect to the x-, y- and z-axes, respectively. Most likely, this option needs larger NR (and NT). If the ORIENTATION SENSITIVE key is not set, the program will average over all orientations (default). SELECTION RULE type (eg. : q) (default : n) The formula for the DDSCS contains an exponential factor in q, which we expand using the Rayleigh expansion. We identify each term in the expansion by the order lambda of the spherical Bessel function j λ (q) it contains. This key keeps some terms and discards others. This can be useful to eliminate unwanted transitions ; to study a spectrum in greater detail ; or simply to speed up the calculation significantly. Possible settings for type are : m : use lambda = 0 only d : use lambda = 1 only q : use lambda = 2 only o : use lambda = 3 only n : no selection rule, calculate all transitions 0-3 : all transitions up to lambda (eg., 1 means lambda = 0 and 1). LSELECTION RULE type (eg. : q) (default : d) Whereas the previous key selects transitions by the order of the interaction potential, this key selects them by the L-character of the final states. Possible settings for type are (the orbital momentum of the initial state being denoted with l): m : L=l d : L=l +/- 1 q : L=l +/- 2 o : L=l +/- 3 n : no selection rule, calculate all transitions 0-3 : L-l <= type
196 178 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION. EXTEND POTENTIALS Rmax sampling lmax refine (e.g.: ) (no defaults) Calculate matrix elements beyond the muffin tin radius up to r = rmax (in Bohr units). Refine the radial grid by a factor refine (1 means default sampling density). This is done by evaluating the potential as given in case.vtotal, which must be present for this type of calculation, and reexpanding it in spherical harmonics, using an angular grid with step of sampling degrees, and expanding up to l=lmax. Currently, users should keep lmax to 0 and almost certainly refine to 1.0. However, advanced users can play around with the software and tweak it to do interesting things if they wish. TELNES3 only requires the spherical potential l=0. FERMI ENERGY Ef (e.g. 0.75) Manually set the Fermi energy to Ef (needs to be given in Rydberg units). (The default behavior is to get Ef from the header of case.qtl.) CORE WAVEFUNCTION filename (e.g. case.cwf) Read the wave function of the initial state from file. (Default behavior is to calculate it instead.) FINAL STATE WAVEFUNCTION filename (e.g. case.finalwf) Read the radial wave functions of the final state from file. (Default behavior is to calculate it instead.) RELATIVISTIC Itype (e.g. 1) Determines which flavor of relativity to use : 0 means nonrelativistic (as in TELNES), 1 means fully relativistic (default), 2 means using the contracted q-vector (only valid for dipole transitions ; as in TELNES2). NOHEADERS Don t put headers in output files. This can be helpful if your plotting program doesn t like the headers. (Gnuplot doesn t mind them.) DOSONLY Don t calculate the EELS spectrum halt the program after the calculation of the density of states is finished. NBTOT nb (e.g. 200 )
197 8.21. TELNES3 179 Arrays for the DOS are first allocated at some initial size, and then reallocated at larger size if necessary. Unfortunately, these reallocation routines appear unstable in some circumstances. This card allows the user to set an array size manually and avoid the need to reallocate (nb is the number of bands). However, very large systems may lead the system to run out of memory and cause a crash. The following cards are not yet activated (placeholders): TABULATE, SPIN The following cards are no longer active and must be removed or renamed: XQTL, WRONG Practical considerations A typical ELNES calculation consists of the following steps: initialize (init lapw) and converge a SCF calculation (run lapw) provide a suitable case.innes file if more excited states are needed than given by the SCF calculation, raise the upper energy limit in case.in1 and run x lapw1 create the case.qtl file using x qtl -telnes calculate the EELS spectrum using x telnes3. It is generally a smart move to make the program calculate the DOS on the biggest energy grid you wiill ever need, save this to file, and simply read it from file for all future calculations (INITIALIZATION key). The same should be done for calculations using EXTEND POTENTIAL (use CORE WAVEFUNCTION key to save to file). This saves time. (In case of disk space problems, once the case.qtl file has been created, the case.vector files can be deleted. Similar, the case.qtl file can be deleted or compressed once the case.dos file exists.) add broadening to the spectrum using x broadening. If you wish, editing the case.inb file allows tweaking of the broadening. study the output (case.elnes or case.broadspec are the place to start). if you wish to do more calculations, save the current results using save eels -d calculation1. Edit case.innes and run x telnes3 again. This sequence can conveniently be executed using w2web by simply clicking one button after the other Files TELNES3 uses a lot of files. Many output files are only written if VERBOSITY is set to a high level. Many input files are required only for certain input settings in case.innes. We list here all files possibly used by TELNES3 (and listed in telnes3.def). Each filename is followed by I or O (input/output), a short description of the file content, and a comment on when the file is used. case.innes (I). Defines the ELNES calculation. Always read. case.struct (I). Defines the crystal. Always read. case.vsp (I). Spherical component of the crystal potential. Read unless core and final state wavefunctions are read from file. case.vtotal (I). Total crystal potential (can be generated by lapw0). Read if EXTEND POTENTIAL is used. case.rotij (I). Rotation matrices that transform q-vectors between equivalent atoms. Read if INITIALIZATION tells the program to do so. case.dos (IO). l-resolved density of states. Read or written depending on INITIALIZATION settings.
198 180 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION case.xdos (IO). lm,l m -resolved density of states. Read or written depending on INITIALIZATION settings; only if the calculation is orientation resolved. case.qtl (I). contains partial charge components and Fermi energy. Read if DOS needs to be calculated (INITIALIZATION) or if Fermi energy is not specified using FERMI. case.inc (I). Specifies core states. Only read if core states are calculated. case.kgen (I). contains k-mesh to sample the Brillouin Zone. Read if DOS needs to be calculated. case.outputelnes (O). Main log file. Always written. Content depends on VERBOSITY. case.elnes (O). Total spectrum. Always written. case.sdlm (O). Partial (l,m) spectra. Written if verbosity > 0. case.ctr (O). (l,m,l m ) crossterms. Written if verbosity > 0 and calculation is orientation sensitive. case.corewavef (O). Contains core wavefunctions. Written if core wavefunctions were calculated and verbosity > 1. case.final (O). Contains APW radial basis functions for final states at selected energies. Written if verbosity > 1. case.ortho (O). Contains scalar products of initial and final states. Written if verbosity > 1. case.matrix (O). Proportionality between partial DOS and spectrum for each l-value. Written if verbosity > 0 and MODUS is energy. case.cdos (O). Selected (l,m,l m ) cross-dos terms. Written if calculation is orientation sensitive and verbosity > 1 or INITIALIZATION causes DOS to be written to file. case.sp2 (O). Integrated cross sections as a function of collection angle for all l-values. Written if calculation is orientation sensitive, MODUS is set to angle and verbosity > 1. case.angular (O). Differential cross section as a function of scattering angle for all l-values. Written if calculation is orientation sensitive, MODUS is set to angle and verbosity > 1. case.inb (O). Settings for the broadening program. Always written. case.eelstable (O). Placeholder. Not currently used. telnes3.def (I). List of files used by TELNES3. Always read. telnes3.error (O). Error file containing current error message; empty after successful calculation. Always written TETRA (density of states) This program calculates total and partial density of states (DOS) by means of the modified tetrahedron method (Blöchl et al 1994). Please note, the tetrahedron method will not work with just one k-point and tetra will automatically switch to a Gaussian broadening scheme (with default broadening of 0.01 Ry). The broadening schemes can also be selected by input (see below), but is not recommended for small unit cells. It uses the partial charges in case.qtl generated by the programs lapw2 (switch QTL) or qtl and generates the DOS in states/ry(cell (files case.dos1/2/3/...) and in states/ev(cell (with respect to the Fermi energy; files case.dos1/2/3ev). In spin-polarized calculations the DOS is given in states/ry/spin (or states/ev/spin). Alternatively and for the total DOS only, you can use the switch -enefile which does not require case.qtl, but uses case.energy and case.scf2 (in case of parallel lapw1 use cat case.energy 1 case.energy 2... case.energy ). Please note: The total DOS is equal to the sum over the atoms of the total-atomic DOS (inside spheres) and the interstitial-dos. (Thus in the total-atomic DOS the multiplicity of an atom is considered). On the other hand, in the partial (lm-like) DOS the multiplicity is not considered and one obtains the total-atomic DOS as a sum over all partial DOS times the multiplicity. The m-decomposed DOS (e.g. p z, p y, p x ) is given with respect to the local coordinate system for each atom as defined by the local rotation matrix (see Appendix A), unless you have used x qtl
199 8.22. TETRA 181 to generate the case.qtl and specified a specific coordinate system in case.inq (see Chapter 8.19). You can also direct tetra to sum-up some partial DOS components into a single DOS. This is for instance useful to sum over the different positions of one element. Using the switches -rxes E1 E2 it is possible to generate a weight-file, where each k-point is weighted according to its contribution to the DOS in the energy range E1-E2. This weight-file case.rxes can be used using the switch -rexs to calculate the DOS with these weights. This option might be useful to simulate the E-dependency of RXES spectra, or in general calculate a DOS of regions around selected k-points only. The density of states in files case.dos1/2/3/... or case.dos1/2/3/...ev can be plotted by dosplot2 lapw (see ). It is strongly recommended that you use Run Programs Tasks Density of States from w2web Execution The program tetra is executed by invoking the command: tetra tetra.def or x tetra [-up dn -enefile -so -hf -rxes -rxesw E1 E2] Dimensioning parameters The following parameters are listed in file param.inc: MG LXDOS max. number of DOS cases usually 1, except for cross-dos when using TELNES.2 = 3 (not needed anymore for TELNES3) Input The required input file case.int can optionally be created using the w2webinterface or the configure int lapw script (see 5.2.9). An example is given below: top of file: case.int TiO2 # Title # EMIN, DE, EMAX for DOS, GAUSS-Broad 7 N # NUMBER OF DOS-CASES, G/L/B broadening 0 1 tot # jatom, doscase, description 1 2 Ti-s 1 3 Ti-p 1 4 Ti-px 1 5 Ti-py 1 6 Ti-pz 2 1 O-tot SUM: 1 2 # NUMBER OF SUMMATIONS, max-nr-of summands 2 3 # this sums dos-cases 2+3 from the input above bottom of file Interpretive comments on this file are as follows: line 1: free format title
200 182 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION line 2: free format emin, delta, emax, broad emin, delta, emax broad specifies the energy mesh (in Ry) where the DOS is calculated. (emin should be set slightly below the lowest valence band; emax will be checked against the lowest energy of the highest band in case.qtl, and set to the minimum of these two values; delta is the energy increment. Gauss-broadening factor. Must be greater than delta to have any effect. line 3: free format ndos, Bmethod, broadening ndos Bmethod G L B broadening specifies the number of DOS cases to be calculated. It should be at least 1. The corresponding output is written in groups of 7 to respective case.dosx files optional input (can be omitted) to select instead of the tetrahedron method: Gaussian broadening Lorentzian broadening both, Gauss and Lorentzian broadening parameters in Ry, typically below/around 0.01 (optional, specify two numbers for B) line 4: (2i5,3x,a6) jatom, jcol, description jatom jcol description specifies for which atom the DOS is calculated. 0 means total DOS, jatom = nat + 1 means DOS in the interstitial, where nat is the number of inequivalent atoms. When spin-orbit is included, jatom = nat + 1 gives total spin-up/dn DOS in a spinpolarized SO calculation, but is meaningless in a non-spinpolarized SO case. specifies the column to be used in the respective QTL-file. 1 means total, 2... s, 3... p,... The further assignment depends on the value of ISPLIT set in case.struct (see sec. 4.3); the respective description can be found in the header of case.qtl. text used for further identification. >>>:line 4 is repeated ndos times line 5: optional line (free format) SUM, nsum, isummax SUM the keyword SUM directs tetra to add-up some partial DOS specified in the lines above and produce case.dossum and case.dossumev. nsum number of summations as specified below (max 7). isummax max number of summands in the lines below. line 6: optional line (free format) iline1 iline2... iline1,2,.. gives the DOS-cases which should be summed up (max isummax cases).
201 8.23. XSPEC 183 >>>:line 6 is repeated nsum times 8.23 XSPEC (calculation of X-ray Spectra) This program calculates near edge structure of x-ray absorption or emission spectra according to the formalism described by Neckel et al.75, Schwarz et al. 79 and 80. For a brief introduction see below. It uses the partial charges in case.qtl. This file must be generated separately using lapw2. Partial densities of states in case.dos1ev are generated using the tetra program. Spectra are calculated for the dipole allowed transitions, generating matrix elements, which are multiplied with a radial transition probability and the partial densities of states. Unbroadened spectra are found in the file case.txspec, broadened spectra in the file case.xspec. Other generated files are: case.m1 (matrix element for the selection rule L+1) and case.m2 (matrix element for the selection rule L-1) and case.corewfx (radial function of the core state). The calculation is done with several individual programs (initxspec, tetra, txspec, and lorentz). which are linked together with the c-shell script xspec. It is strongly recommended that you use Run Programs Tasks X-ray spectra from w2web Execution Execution of the shell script xspec The program xspec is executed by invoking the command: xspec xspec.def or x xspec [-up -dn] Sequential execution of the programs Besides calculating the X-ray spectra in one run using the xspec script, calculations can be done by hand, i.e. step by step, for the sake of flexibility. initxspec This program generates the appropriate input file case.int, according to the dipole selection rule, for the subsequent execution of the tetra program. The program initxspec is executed by invoking the command: initxspec xspec.def or x initxspec [-up -dn] tetra The appropriate densities of states for (L+1) and (L-1) states respectively are generated by execution of the tetra program. The program tetra is executed by invoking the command: tetra tetra.def or x tetra [-up -dn] txspec This program calculates energy dependent dipole matrix elements. Theoretical X-ray spectra are generated using the partial densities of states (in the case.dos1ev file) and multiplying them with the corresponding dipole matrix elements. The program txspec is executed by invoking the command: txspec xspec.def or x txspec [-up -dn] lorentz The calculated spectra must be convoluted to account for lifetime broadening and for a finite resolution of the spectrometer before they can be compared with experimental spectra. In the lorentz program a Lorentzian is used to achieve this broadening. The program lorentz is executed by invoking the command: lorentz xspec.def or x lorentz [-up -dn]
202 184 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION If you want orientation sensitive XSPEC (like p-parallel and p-normal spectra, you may change in case.int the column-number to eg. p x or p z and rerun the last tree steps of the script above mnually Dimensioning parameters The following dimensioning parameters are collected in the files param.inc of SRC txspec and SRC lorentz: IEMAX0 NRAD LMAX maximum number of energy steps in the spectrum (SRC lorentz) number of radial mesh points highest l+1 in basis function inside sphere (consistent with input in case.in1) Input Two examples are given below; one for emission spectra and one for absorption spectra: Input for Emission Spectra: top of file: case.inxs NbC: C K (Title) 2 (number of inequivalent atom) 1 (n core) 0 (l core) 0,0.5,0.5 (split, int1, int2) -20,0.1,3 (EMIN,DE,EMAX in ev) EMIS (type of spectrum, EMIS or ABS) 0.35 (S) 0.25 (gamma0) 0.3 (W) AUTO (generate band ranges AUTOmatically or MANually (E0 in ev) (E1 in ev) (E2 in ev) bottom of file Input for Absorption Spectra: top of file: case.inxs NbC: C K (Title) 2 (number of inequivalent atom) 1 (n core) 0 (l core) 0,0.5,0.5 (split, int1, int2) -2,0.1,30 (EMIN,DE,EMAX in ev) ABS (type of spectrum) 0.5 (S) 0.25 (gamma0) bottom of file Interpretive comments on these files are as follows. line 1: free format TITLE Title line 2: free format NATO Number of the selected atom (in case.struct file)
203 8.23. XSPEC 185 line 3: free format NC principle quantum number of the core state line 4: free format LC azimuthal quantum number of the core state The table below lists the most commonly used spectra: line 5 free format Spectrum n l K 1 0 L II,III 2 1 M V 3 2 Table 8.116: Quantum numbers of the core state involved in the x-ray spectra SPLIT, INT1, INT2 split in ev between e.g. L II and L III spectrum (compare with the respective core eigenvalues), INT1 and INT2 specifies the relative intensity between these spectra. Values of 0, 0.5, 0.5 give unshifted spectra. line 6: free format EMIN, DE, EMAX minimum energy, energy increment for spectrum, maximum energy; all energies are in ev and with respect to the Fermi level EMIN and EMAX are only used as limits if the energy range created by the lapw2 calculation (using the QTL switch) is greater than the selected range. line 7: Format A4 TYPE EMIS X-ray emission spectrum ABS X-ray absorption spectrum (default) line 8: free format S broadening parameter for the spectrometer broadening. For absorption spectra S includes both experimental and core broadening. Set S to zero for no broadening. line 9: free format GAMMA0 broadening parameter for the life-time broadening of the core states. Set GAMMA0 to zero to avoid lifetime broadening of the core states. line 10: free format W broadening parameter for the life-time broadening of valence states. Set W to zero to avoid lifetime broadening of the valence states. line 11: format A4
204 186 CHAPTER 8. ANALYSIS, PROPERTIES AND OPTIMIZATION BANDRA AUTO MAN band ranges are determined AUTOmatically (default) band ranges have to be entered MANually line 12: free format E0 Emission spectra: onset energy for broadening, E0, generated automatically if AUTO was set in line 10 Absorption spectra: not used line 13: free format E1 Emission spectra: onset energy for broadening, E1, generated automatically if AUTO was set in line 10 Absorption spectra: not used line 14: free format E2 Emission spectra: onset energy for broadening, E2, generated automatically if AUTO was set in line 10 Absorption spectra: not used
205 9 Utility Programs Contents 9.1 symmetso pairhess eigenhess patchsymm afminput clmcopy structeditor Visualization Unsupported software symmetso This program helps to setup spin-orbit calculations in magnetic systems. Since SO may break symmetry in certain spacegroups, it classifies your symmetry operations into operations A, which do not invert the magnetization (identity, inversion, rotations with the rotation axis parallel to magnetization), B, which invert it (mirror planes) and C, which change the magnetization in some 187
206 188 CHAPTER 9. UTILITY PROGRAMS other way. (Note: magnetization is a result of a circular current, or equivalently, an axial vector resulting from a vector product ẑ ˆx ŷ). symmetso will keep all A-type and throw away all C-type symmetry operations. Depending on the presence of inversion symmetry it will keep (inversion is present) or remove the B-type operations. Finally, symmetso uses the remaining symmetry operations to check/generate equivalent atomic positions (it can happen that some equivalent atoms become non-equivalent after inclusion of SO interaction). In essence, it reads your case.struct and case.inso (for the direction of magnetization) files and creates an ordered case.struct orb file with proper symmetry and equivalent atoms. It also generates a file case.ksym, which is a struct file with valid operations to generate a proper k-mesh using x kgen -so. In addition proper input files case.in1, case.in2, case.inc, case.vspup/dn, case.vnsup/dn, case.clmsum, case.clmup/dn are generated, so that you can continue with runsp -so without any further changes Execution The program symmetso is executed by invoking the command: symmetso symmetso.def or x symmetso [-c] Usually it is called from the script initso lapw and thus needs not to be invoked manually. 9.2 pairhess creates an approximate hessian matrix (in.minpair) for structure minimization using the PORT option. It uses a harmonic model with exponentially decaying bond strenght and in many cases reduces the number of geometry steps during min lapw significantly. It is described in detail in Rondinelli et al For its usage see the comments in sect Execution The program pairhess is executed by invoking the command: pairhess pairhess.def or x pairhess [-copy] The switch -copy copies.minpair to.minrestart and.min hess, which are needed in min lapw.
207 9.2. PAIRHESS Dimensioning parameters The following parameters are used in param.inc: NATMAX NEIGMAX max. number of atoms) max number of neighbours Input pairhess uses an optional input file case.inpair, which is needed only for an experienced user for better tailoring of certain default parameters. An example is given below: top of file: case.inpair (Rmax, Decay, ReScale) (Cutoff, Diag, mode) 0.2 (ZWEIGHT Interpretive comments on this file are as follows: line 1: free format RMAX Maximum distance (a.u.) for considering neighbors is good. DECAY Exponential decay applied to neighbors when calculating the pairwise bond strenghts is reasonable. RESCALE A scaling term to multiply the pairwise hessian by. This number is rather important; 0.25 appears to be best for a system with soft modes, 0.35 for a stiffer system. You can save substantial time by adjusting RESCALE so it is approximately correct using a.min hess from a previous run (adjust until numbers for similar multiplicities are similar), or by adjusting the frequencies (see also eigenhess). line 2: free format CUTOFF When the weighting (via an exponential decay) becomes smaller than this number the pairwise bonds are ignored. DIAG The value to multiply a unitary matrix by, this is added to the hessian estimate MODE 0: Spring model; [1: harmonic model; not so good] line 3: free format ZWEIGHT Atomic number weight for bonds of form exp(-z*zweight). Values of are reasonable. The default is 0.1; a negative number (e.g. -1) turns this off.
208 190 CHAPTER 9. UTILITY PROGRAMS 9.3 eigenhess This program was contributed by: Laurence Marks Dept. Materials Science and Engineering Northwestern University Evanston, USA Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. This program analyses / manipulates.min hess, which was created by a structural minimization using min lapw and the PORT option. In particular, such an analysis can yield approximate vibrational frequencies and corresponding eigenmodes, which eventually can give a hint about a dynamically unstable structure (imaginary frequencies). Some more description is given in $WIENROOT/SRC pairhess/readme. The program eigenhess is executed by invoking the command: x eigenhess 9.4 patchsymm performs a symmetry check on the positions and produces a new struct file case.struct new. It is useful in case something went wrong during min lapw (rounding errors of positions) or the cif/amc file did not have enough digits (eg. 1/3 was prepresented by only). The file case.outputpatch gives information on how parameters changed Execution The program patchsymm is executed by invoking the command: patchsymm patchsymm.def or x patchsymm
209 9.6. CLMCOPY afminput This program creates the inputfile case.inclmcopy st for the program clmcopy, which copies spin-up densities of atom i to spin-down densities of the related antiferromagnetic atom j and vice versa in an anti-ferromagnetic system. It uses a symmetry operation to find out how and which atomic densities must be interchanged and how the Fourier coefficients of the density transform. It is based on the ideas of Manuel Perez-Mato (Bilbao, Spain). See $WIENROOT/SRC afminput/afminput test for several examples. The best way is to supply a file case.struct supergroup, which is the struct file of the nonmagnetic supergroup. If the two spacegroups are TRANSLATIONENGLEICH, it will find out automatically the proper symmetry operation. Please note, this automatic way works only when the coordinate system remains identical. In some cases sgroup may interchange eg. the y and z axis. In such cases reverse this change, both, for the lattice parameters as well as for all positions, set NSYM=0 and run init lapw again (ignoring any suggestion of sgroup). If the two spacegroups are KLASSENGLEICH (i.e. have the same number of symmetry operations), you will be asked to supply a translation which transforms the AF atoms into each other. A typical example would be bcc Cr: the bcc supergroup and the AF subgroup (simple cubic) have both 48 symmetry operations and the proper translation is (0.5,0.5,0.5). Finally, if you don t give case.struct supergroup, you have to supply a symmetry operation (rotation + non-primitive translation) as input. For bcc Cr or the famous NiO-AFII structure this would be simply Please see the comments in sect on how to proceed in detail for AFM calculations and find further examples in SRC afminput Execution The program afminput is executed by invoking the command: afminput afminput.def or x afminput Dimensioning parameters The following parameters are used: NCOM LMAX number of LM components in the density (in param.inc) max l for LM expansion of the density (in param.inc). 9.6 clmcopy This program generates the spin-dn density (case.clmdn) from a given spin-up density (case.clmup) according to rules and symmetry operations in case.inclmcopy (generated earlier by afminput) for an AFM calculation. Please see the comments in sect on how to proceed in detail for AFM calculations.
210 192 CHAPTER 9. UTILITY PROGRAMS Execution The program clmcopy is executed by invoking the command: clmcopy clmcopy.def or x clmcopy Dimensioning parameters The following parameters are used in param.inc: NCOM NRAD NSYM number of LM components in the density number of radial mesh points number of symmetryoperations Input An example is given below: top of file: case.inclmcopy NUMBER of ATOMS to CHANGE 1 2 INTERCHANGE these ATOMS SYMMETRY OPERATION NUMBER of LM to CHANGE SIGN 3 4 INTERCHANGE these ATOMS SYMMETRY OPERATION NUMBER of LM to CHANGE SIGN Interpretive comments on this file are as follows: line 1: free format NATOM Number of atoms for which rules for copying the density will be defined line 2: free format N1, N2 Interchange spin-up and dn densities of atoms N1 and N2 line 3-5: free format SYM Symmetry operation for atom N1 to rotate into N2 (without translational part)
211 9.7. REFORMAT 193 line 6: free format NLM Number of LM values, for which you have to change the sign when swapping up and dn-densities line 7ff: free format L1,M1,L2,M2,Fac NLM pairs of L1,M1 (spin-up), which change into L2,M2 (spin-dn) and the respecting CLMs are multiplied by Fac Lines 2-7ff have to be repeated NATOM times. line 8-10: free format SYM0 Symmetry operation (one of the operations of the NM-supergroup missing in the AFM-subgroup (transfers spin-up into spin-dn atom) 9.7 reformat To produce a surface plot of the electron density using rhoplot lapw (which is an interface to gnuplot), data from the file case.rho created by lapw5 must be converted using reformat The sources of the program reformat.c are supplied in SRC reformat. 9.8 hex2rhomb and rhomb in5 hex2rhomb interactively converts the positions of an atom from hexagonal to rhombohedral coordinates (needed in case.struct). rhomb in5 interactively helps to generate input case.in5 for density plots with lapw5 for rhombohedral systems. It defines a plane as needed in the input file when you specify 3 atoms of that plane. The sources of these programs are supplied in SRC trig. 9.9 plane plane helps to generate case.in5 for density plots with lapw5 (for orthogonal and hex lattices only). The plane will be specified by 3 atoms and you need an auxiliary file plane.input, which contains: a,b,c x0,y0,z0 x1,y1,z1 x2,y2,z2 xl,yl P # lattice parameters # position of atom (fractional coordinates), which will be centered in the plot # position of atom, which will be below the centered atom # position of atom, which will show to the left # lenght (in bohr) of plot in x and y direction. # defines lattice, either P (cartesian coordinates) or H (hexagonal) supported The source of this program is supplied in SRC trig.
212 194 CHAPTER 9. UTILITY PROGRAMS 9.10 add columns add columns reads a sequence of pairs of 2 numbers (form stdin), adds them together and prints the sum to stdout. If you have two columns of numbers in 2 files (eg. in colup and coldn) you can add them using: paste colup coldn add columns > col The source of this program is supplied in SRC trig clminter clminter interpolates the density in case.clmsum/up/dn to a new radial mesh as defined in case.struct new. This utility is useful when you run a structural minimization (min lapw), some atoms start to overlap and you have to reduce RMT (the size of the atomic spheres) of certain atoms. In such a case: save the calculations generate case.struct new with modified RMTs x clminter in spinpolarized case repeat this line with -up and -dn switches cp case.struct new case.struct cp case.clmsum new case.clmsum eventually copy also case.clmup/dn files) run lapw; (it will probably take some iterations until you reach scf again, but it should be much faster than starting with init lapw) Note: Please be aware the the total energy will change with modified RMT (by some constant) and you must not compare energies comming from different RMTs (but most likely you can determine the constant shift by repeating (at least) ONE calculation with identical structure but different RMTs). The source of this program is supplied in SRC trig eosfit Small program to calculate the Equation of States (EOS; Equilibrium volume V 0, Bulk modulus B 0 and it s derivative B 0. The Murnaghan (1944), the Birch-Murnaghan and the EOS2 equation of states are supported. It relies on the file case.vol (containing lines with volume, E-tot, usually created from w2web using Volume optimization ), or alternatively is called from eplot lapw using case.analysis (see and 5.3.1). The sources are supplied in SRC eosfit eosfit6 Nonlinear least squares fit (using PORT routines) for a parabolic fit of the energy vs. 2-4 dim. lattice parameters. It requires case.ene and case.latparam, usually generated by parabolfit lapw. It can optionally produce case.enefit, which contains energies on a
213 9.14. SPACEGROUP 195 specified grid for plotting purposes (in 2D same format as case.rho, which can be used in contourplot programs). (See 5.3.1). The sources are supplied in SRC eosfit spacegroup This program was contributed by: Vaclav Petricek Institute of Physics Academy of Sciences of the Czech Republic Na Slovance Praha (Prague) 8 Czech Republic Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. Interactive program to generate equivalent positions for a given spacegroup and lattice. The program is also used internally from w2web to generate positions when selecting spacegroups in the StructGen join vectorfiles This program was contributed by: Phillipp Wissgott Institute of Solid State Physics TU Vienna Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. Interactive program to combine parallel vector and energy files (case.vector xx and case.energy xx) into single files (case.vector and case.energy). Executed by: x join vectorfiles [-up/-dn/-so/-soup/-sodn] [-c] case number of parallel files to join 9.16 arrows This program was contributed by:
214 196 CHAPTER 9. UTILITY PROGRAMS Evgeniya Kabliman Institute for MaterialsChemistry TU Vienna Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. Small program which together with Xcrysden allows to display the forces acting on all atoms or the differences between two structures using arrows which indicate the movement of the atoms. The recommended sequence to visualize forces is: Prepare (copy) a struct and scf file with the initial structure using the names case initial.struct and case initial.scf. View case initial.struct in Xcrysden and File/Save as xsf-structure with the name case initial.xsf. x arrows View the resulting case forces.xsf using: xcrysden --xsf case forces.xsf. Switch on Display/Forces and adjust the length of the arrows in Modify/Force-settings. while differences between the inital and relaxed structure can be viewed by: Prepare (copy) two struct files with the initial and the relaxed structure using the names: case initial.struct and case final.struct. View case initial.struct in Xcrysden and File/Save as xsf-structure with the name case initial.xsf. x -delta arrows View the resulting case delta.xsf using: xcrysden --xsf case delta.xsf. Switch on Display/Forces and adjust the length of the arrows in Modify/Force-settings xyz2struct xyz2struct reads atomlabel,x,y,z -data from case.xyz and writes them into xyz2struct.struct. You may have to edit the xyz-file and insert a few lines at the top: ANG(default)/BOHR; F/C (fractional or cart. coordinates) and L (lattice information, see example) a,b,c lattice parameters, or when L was specified a scaling constant and the bravais matrix. Since xyz data contain no symmetry information, all atoms with the same label will be treated as equivalent. The nuclear charges ZZ will not be given and you have to insert them manually or use w2web-structgen. It is executed using: xyz2struct < case.xyz (I recommend this program only for cases with many non-equivalent atoms and (almost) no symmetry. If you have spacegroup-information it is probably easier to use StructGen and copy/paste of the positions). A proper case.xyz file looks like:
215 9.18. CIF2STRUCT 197 ang B C or BOHR F L B C cif2struct cif2struct reads structural data in cif-format from case.cif and writes them into case.struct. It is executed using: cif2struct case.cif or cif2struct case.txt or x cif2struct [-txt] The required cif files can be for example be obtained from Cystallographic databases (e.g. the Inorganic Crystal Structure DataBase ICSD) or from other programs (when transfered from MS-Windows, make sure to habe it in Unix-mode, not in Dos-mode ; eventually use dos2unix ). Alternatively, cif2struct can work with case.txt, which contains the following data: a # a..ang, b..bohr # shift of origin # a,b,c,angles R-3c # spacegroup-symbol (see \STRUCTGEN{}) Al # atom-name # atomic position O # # Tmaker Tmaker creates a struct-file init.struct from a file datastruct, which can be created by the script makestruct lapw. It is executed using: Tmaker It was contributed by Morteza Jamal(m 9.20 struct2cif struct2cif creates a cif-file case.cif from case.struct. It is executed using: x struct2cif or struct2cif struct2cif.def It was contributed by F. Boucher and L.D.Marks In order to work properly, the case.struct file should have a spacegroup label included. There is also a similar program struct2xyz available.
216 198 CHAPTER 9. UTILITY PROGRAMS 9.21 struct2poscar struct2poscar creates the files case.poscar and case.xyz from case.struct. case.poscar and case.xyz are files which are used by the package dftd3 when periodic boundary conditions are switched on or off, respectively. It is executed using: x struct2poscar or struct2poscar struct2poscar.def 9.22 conv2prim conv2prim creates the file case prim.struct which corresponds to the primitive cell of the conventional unit cell specified by case.struct. It is executed using: x conv2prim or conv2prim conv2prim.def 9.23 fleur2wien fleur2wien converts the FLEUR-file which contains the exchange-correlation potential (case.potential) into the WIEN2k-format (case.r2v(dn)). The FLEUR-file case.lattice harmonics, which contains the linear combinations of spherical harmonics, is also necessary. If the FLEUR and WIEN2k Bravais matrices are not the same, then the FLEUR direct Bravais matrix has to be specified at the beginning of case.lattice harmonics below the keyword bravais (a, b, c lattice parameters specified at the 1st, 2nd, 3rd lines, respectively). It is executed using: x fleur2wien or fleur2wien fleur2wien.def 9.24 StructGen of w2web The new StructGen helps to generate the master input file case.struct. It has the following additional features: automatic conversion from/to Å and Bohr Use spacegroup information (in conjunction with the spacegroup program (see 9.14 to generate equivalent positions) built in calculator to carry out simple arithmetic operations to specify the position pameters (of the equivalent atoms).) supercell This program helps to generate supercells from a regular WIEN2k-struct file. It asks interactively for the name of the original struct file and the number of cells in x, y, and z direction. (Only integers are allowed, thus no rotations by 45 o like sqrt(2) x sqrt(2) cells are supported yet).
217 9.26. STRUCTEDITOR 199 If symmetry permits, one can change the target lattice to P, B or F centered lattices, which allows to increase the number of atoms in these supercells by a factor of 2, 4, 8,... Rhombohedral (R) lattices are converted automatically into H (hexagonal) lattices, which are 3 times larger than the original cell. If the target lattice is P, one can add some vacuum in each direction for surface slabs (or chains or isolated molecules) and also add a top -layer (repeat the atoms with z=0 at z=1). You can define an optional shift in x,y,z direction for all the atoms in the cell. (This might be useful if you want to arrange the atoms in a certain way, eg. you may want to create a surface slab such that it is centered around z=0.5 (and not z=0), so that plotting programs (xcrysden) produce nicer pictures of the structure. For the experienced user a much more flexible (but also more complicated) tool is available, namely the structeditor package (see Sect.9.26). Please note: You cannot make calculations with these supercells (except for surfaces) unless you modify the created supercell-struct file. You must break the symmetry by introducing some distortions (e.g. for a frozen phonon) or replace one atom by an impurity/vacancy, Execution The program supercell is executed by invoking the command: supercell or x supercell 9.26 structeditor This program was contributed by: Robert Laskowski Please make comments or report problems with this program to the WIEN-mailinglist. If necessary, we will communicate the problem to the authors. This package helps to manipulate structures. Usually one would start from an appropriate (simple) case.struct file, and this tool allows to add or manipulate atoms (with or without symmetry considerations), or generate arbitrary supercells or surfaces. It is commandline driven and targeted for the more experienced user, who knows what he wants to do and is just looking for a convenient tool. It consists of a couple of octave (matlab) routines and some fortran code, thus it requires octave (the free matlab version) and for visualization the xcrysden program. A more extended documentation and some examples can be found in $WIENROOT/SRC structeditor/doc, but the most important command helpstruct lists all available functions: a2adist * calculates distance between atoms mina2adist * calculates minimum distance between atoms addatom * adds an atom to the structure addeqatom * adds an atom and all equivalent
218 200 CHAPTER 9. UTILITY PROGRAMS copyatom getaname getar0 getazz loadstruct makeconventional makeprimitive makesupercell makesurface mergestruct movealla replaceatom replaceeqatoms rescale_c rescale_c_2 rescale_c_3 rmatom rmeqatoms rotateall rotateatomlist rotatethreedim savestruct shiftatomlist showequivalent showstruct smultatom sshift * creates a copy of an atom * converts atomic number into atomic symbol * calculates r0 from atomic number * converts atomic name into atomic number * reads Wien2k structfile * convestrs structure into the conventional form * converts structure to the primitive form * creates supercell * creates surface * merges two structures * moves all atoms with vector vec * replaces an atom with other atom * replaces an atom and all equivalent with other atoms * rescales c for surface cell (vacume in the midle) * rescales c for surface cell (vacume above) * rescales c for surface cell (vacume audside) * removes an atom * removes an atom and all equivalent * rotates all atoms around z with a given angle * rotates specified atoms around z with a given angle * rotates specified atom around vector with given angle * saves crystal structure * shifts specified atoms by a vector * outputs list of equivalent atoms * displays structure (using DX) * creates symmetry equivalent positions * symmetric shifts of equivalent atoms You can get then specific help on a particular function using eg.: help makesurface. PS: It is also fairly trivial to construct new functions starting from already existing ones or by combining them in a convenient way Execution The structeditor is invoked within the octave environment and a typical sequence of commands could be: octave s=loadstruct( GaN.struct ) # make an orthorhombic supercell and visualize it a=[1 0 0; 1 1 0; 0 0 2] sout=makesupercell (s,a); showstruct(sout); # save it as test.struct savestruct (sout, test.struct ); # get help on all commands helpstruct # get help on the command makesupercell help makesupercell
219 9.27. VISUALIZATION Visualization BALSAC balsac (Build and Analyze Lattices, Surfaces and Clusters) was written by Klaus Hermann (Fritz-Haber Institut, Berlin). It provides high quality postscript files. In SRC balsac-utils we provide the following interface programs to convert from WIEN2k to balsac: str2lat to convert case.struct to case.lat (the BALSAC lat file). str2plt to convert case.struct to case.plt (the BALSAC plt file for one unit cell). outnn2plt to convert case.outputnn to case.plt (the BALSAC plt file for one unit cell). You have to select one atom (central atom) and than all nn-atoms are converted into the plt file. In addition converters to the xyz-format (str2xyz, outnn2xyz) for other plotting programs are also available. For an example see figure 3.1 For scientific questions concerning BALSAC please contact Klaus Hermann at Balsac is available from: Garching Innovation GmbH, Mrs. M. Pasecky Hofgartenstr. 8, D Munich, Germany Tel.: , Fax.: web: XCrysDen XCrysDen (Kokalj 1999) is a render and analysis package. It has the following features (see also render and analyze (distances, angles) the crystal structure generate k-mesh for bandstructure plots generate input and render 2D charge densities generate input and render 3D charge densities generate input and render Fermi surfaces render changes between two structures (original and relaxed) with the help of the arrows program (see 9.16) XCrysDen is available from: Tone Kokalj Jozef Stefan Institute, Dept. of Physical and Organic Chemistry Jamova 39, SI-1000 Ljubljana, Slovenia Tel.: , Fax:
220 202 CHAPTER 9. UTILITY PROGRAMS Figure 9.1: 3D electron density in TiC generated with XCrysDen 9.28 Unsupported software On our website you can find a link to Unsupported software goodies, where references to various software packages are given. Most of those packages are contributions from WIEN2k-users and you may check this site from time to time if you find some useful tools for you. In case you develop some goodies yourself and want to share this development with the WIEN2k community, please send an to and we will add it to this page.
221 10 How to run WIEN2k for selected samples Three test cases are provided in the WIEN2k package. They contain the two starting files case.struct and case.inst and all the output so that you can compare your results with them. The test cases are the following (where the names correspond to what was called CASE in the rest of this User s Guide) TiC Fccni TiO2 We recommend to run these test cases (in a different directory) and compare the output to the provided one. All test cases are setup such that the CPU-time remains small (seconds). For real production runs the value of RKMAX in case.in1 must be increased and a better (denser) k-mesh should be used. In addition we provide a subdirectory example struct files were various more complicated struct files can be found TiC The TiC example is described in detail in chapter 3 (Quickstart) Fcc Nickel (spin polarized) Ferromagnetic Nickel is a test case for a spin-polarized calculation. Ni has the atomic configuration 1s 2, 2s 2, 2p 6, 3s 2, 3p 6, 3d 8, 4s 2 or [Ar] 3d 8, 4s 2. We treat the 1s, 2s, 2p and 3s as core states, and 3p (as local orbital), 3d, 4s and 4p are handled as valence states. In a spin-polarized calculation the file structure and the sequence of programs is different from the non-spin-polarized case (see 4.5.2). Create a new session and its corresponding directory. Generate the structure with the following data (we can use a large sphere as you will see from the output of nn): 203
222 204 CHAPTER 10. EXAMPLES Title fcc Ni Lattice F a 6.7 bohr b 6.7 bohr c 6.7 bohr α, β, γ 90 Atom Ni, enter position (0,0,0) and RMT = 2.3 Initialize the calculation using the default RKmax and use 3000 k-points (a ferromagnetic metal needs many k-points to yield reasonably converged magnetic moments). Allow for spin-polarization. Start the scf cycle (runsp lapw) with -cc (in particular for magnetic systems charge convergence is often the best choice). At the bottom of the converged scf-file (Fccni.scf) you find the magnetic moments in the interstital region, inside the sphere and the total moment per cell (only the latter is an observable, the others depend on the sphere size). :MMINT: MAGNETIC MOMENT IN INTERSTITIAL = :MMI001: MAGNETIC MOMENT IN SPHERE 1 = :MMTOT: TOTAL MAGNETIC MOMENT IN CELL = Rutile (T io 2 ) This example shows you how to optimize internal parameters and do a k-point parallel calculation. Create a new session and its corresponding directory. Generate the structure with the following data (we use a smaller O sphere because Ti-d states are harder to converge then O-p): Title TiO2 Spacegroup P 4 2/mnm (136) a bohr b bohr c bohr α, β, γ 90 Atom Ti, enter position (0,0,0) and RMT = 2.0 Atom O, enter position (0.3,0.3,0) and RMT = 1.6 StructGenshould automatically add the equivalent positions. Initialize the calculation using RKmax=6.5 in tio2.in1 st and use 100 k-points and a shift in kgen. If you have more cpus available (a parallel machine or simply a couple of PCs with a common NFS filesystem, for details see 5.5), you can use Execution Run scf, activate the parallel button and start scf in w2web. This will create and open a.machines file and you should insert lines with the proper names of your PCs (possibly use 9 (or 3) processors since we have 9 k-points, ). Save this file and click on Execution Run scf, activate -fc 1.0 for force-convergence and start scf to submit the scf-cycle. Alternatively at the command-line you can use the UNIX command cp $WIENROOT/SRC_templates/.machines. and edit this file. You would start the scf-cycle (in background) simply by typing run_lapw -p -fc 1.0 &
223 10.4. SUPERCELL CALC 205 During the scf-cycle monitor tio2.dayfile and check convergence (:ENE, :DIS, :FGL002), either using Utils/Analysis in w2web, or grep :ENE tio2.scf. You should see some convergence of :FGL002 and then a big jump in the final cycle, when the valence-force corrections are added. Only the last force (including this correction) is valid. Since this force is quite large, you can now optimize the position of the O-atom: Start the structure minimization in w2web using Execution mini.positions. This will generate TiO2.inM, and you can try option PORT with tolf=1.0 (instead of 2.0), otherwise stay with the default parameters. Repeat Execution mini.positions and start the minimization. Alternatively you can use min_lapw -p which is identical to: min_lapw -j run_lapw -I -fc 1 -p This will create TiO2.inM automatically, call the program min, which generates a new struct file using the calculated forces, and continues with the next scf cycle. It will continue until the forces are below 1 mry/bohr (TiO2.inM) and the final results are not saved automatically but can be found in the current calculation. You should watch the minimization (:ENE, :FGL002, :POS002) using the file TiO2.scf mini, which contains the final iteration of each geometry step (see also Sec.5.3.2). If the forces in this file oscillate from plus to minus and seem to diverge, or if they change very little, you can edit TiO2.inM (change the method, reduce or increase the stepsize), and remove TiO2.tmpM (contains the history of the minimization and is used to calculate the velocities of the moving atoms). (This should not be neceaasry for the rutile example, but may occur in more complex minimizations. See comments in Sec ). The final structural parameter of the O-atom should be close to x=0.304, which compares well with the experimental x= Supercell calculations on TiC This example shows you how to create a supercell of TiC, which could be used to simulate a TiC-surface or vacancies, impurities or core-holes for X-ray absorption / ELNES spectroscopy. I ll describe the procedure using Unix and WIEN2k commands in an xterm, but of course you can do the same in w2web. Create a new directory, copy the original TiC struct file into it and run supercell program: mkdir super cd super cp../tic/tic.struct. x supercell Specify TiC.struct, a 2x2x2 supercell, F lattice (this will create a cell with 16 atoms, you can also create 32 or 64 atom cells using B or P lattice type. Note: surfaces require a P supercell). cp TiC_super.struct super.struct and edit this file to make some changes. You could eg.
224 206 CHAPTER 10. EXAMPLES delete an atom (to simulate a vacancy) replace an atom by another element (impurity) label an atom (put a 1 in the 3rd column next to the element name) to make this atom unique (needed eg. for core-holes) displace an atom (for phase transitions or phonons) Note: it is important to make at least one of these chages. Otherwise the initialization will restore the original unit cell (or the calculations will fail later on because symmetry is most likely not correct) Run init lapw. You will see that nn complains and finds a new set of equivalent atoms (originally all atoms were non-equivalent, but nn finds that some atoms have identical neighbors, thus should be in an equivalent set). Accept the automatically generated struct file and continue. Remember, supercells normally require less k-points than the original small cell. After the complete initialization you may in principle restore the original struct file (eg. without a displacement) in case you want to repeat the undistorted structure in supercell geometry. For a core-hole calculation you would now edit super.inc and remove one core electron from the desired atom and state (1s or 2p,...). In addition you should add the missing electron either in super.inm (background charge) or super.in2 (add it to the valence electrons). In the latter case, you should remove this extra electron AFTER scf and BEFORE calculation of the spectra. Once this has been done, you could start a scf-cycle (for impurities, vacancies,.. you should most likely also optimize the internal positions) Further examples Further examples can be found on our web-site: or
225 Part III Installation of the WIEN2k package and Dimensioning of programs 207
226
227 11 Installation and Dimensioning Contents 11.1 Requirements Installation of WIEN2k w2web Environment Variables Requirements WIEN2k is written in FORTRAN 90 and requires a UNIX operating system since the programs are linked together via C-shell scripts. It has been implemented successfully on the following computer systems: Intel and AMD based PCs running under Linux, IBM RS6000, HP, SGI, and Mac. Hardware requirements will change from case to case (small cases with 10 atoms per unit cell can be run on almost any PC under Linux), but we recommend a more powerful quad-core Intel-core2 PC with at least 4 GB (better 8-16GB GB) memory and plenty of disk space (a TB). For coarse grain parallization on the k-point level, a cluster of PCs with a Gb Ethernet is sufficient. Faster communication (Infiniband) is recommended for the fine grain (single k-point) parallel version. For Intel (AMD) based systems we recommend the Intel ifort compiler and the Intel mkl library (which includes blas, lapack and Scalapack) (see If you have installed ifort yourself on your local PC, don t forget to configure your environment properly. Add some thing like: source /opt/intel/11.0/074/bin/ifortvars.csh intel64 source /opt/intel/11.0/074/mkl/tools/environment/mklvarsem64t.csh to your.cshrc file (or similar statements for.bashrc). 209
228 210 CHAPTER 11. INSTALLATION AND DIMENSIONING Tcl/Tk-Toolkit (for Xcrysden only) MPI+SCALAPACK (for fine grain parallelization only) FFTW v.2 or 3 (mpi-version for fine grain parallelization only) Usually these packages should be available on modern systems. If one of these packages is not available it can either be installed from public domain sources (ask your computing center, use the WWW to search for the nearest location of these packages) or the corresponding configuration may be changed (e.g. using vi instead of emacs). Brief installation instructions for mpich and fftw are given below. None of the principal components of WIEN2k requires these packages, only w2web needs them Installation tips for mpich and fftw (either version or 3.3) This is only a brief guidance, you may need some Linux experience for this. Download the mpich1.2.7p1 and fftw /or fftw-3.3 sources from and (Please note, the fftw-3.x versions are incompatible with fftw-2.x, but both interfaces are available in WIEN2k using the -DFFTW2 or -DFFTW3 compiler option (in FOPT/FPOT during siteconfig lapw) unzip and untar the downloaded file Change into the expanded directories and configure the compilation. Define your fortran compiler (setenv FC ifort, or export FC=ifort) and use./configure prefix=/pathname to configure compilation. /pathname is the directory where the libraries should be installed (could be /opt/local or /usr/local or similar, you will have to specify this path again in the LDFLAGS). For fftw configuration add the enable-mpi switch. make make install (if you specified a system-directory like /usr/local you must have proper permissions for this step, eg. become root user) add the mpi-directory to your path (set path = ( /opt/mpich/mpich-1.2.7p1/bin $path )) Optionally, one can also use in the sequential (non-mpi) version of lapw0 and lapw2 the fftw routines. However, there is some speedup only when you use the MKL-fft routines, not the self-compiled fftw-binaries. The mkl-interface to fftw is not active by default, but you may have to compile it yourself. To do so (syntax for ifort12): cd $MKLROOT/interfaces/fftw2xf make libintel64 (or make libia32) in case you do not have icc installed, but use GNU-C (gcc) you must: edit makefile, and remove -D GNU from the line CC=gcc -D GNU (to remove additional from the object names) make libintel64 compiler=gnu add -DFFTW2 to FOPT in the Makefile of lapw0 and lapw2 add -lfftw2xf or -lfftw2xf gnu to R LIBS in the Makefile of lapw0 and lapw2 a similar procedure is available for fftw3 (just exchange above 2 by 3 in all statements) This may speedup the fft-parts of these programs a bit.
229 11.2. INSTALLATION OF WIEN2K Installation of WIEN2k Expanding the WIEN2k distribution The WIEN2k package comes as a single tar file (or you can download about 50 individual tar files separately), which should be placed in a subdirectory which will be your $WIENROOT directory (e.g../wien2k). In addition you can download three examples, namely TiC.tar.gz, TiO2.tar.gz and Fccni.tar.gz. Uncompress and expand all files using: tar -xvf wien2k 12.tar (skip this if you downloaded files separately) gunzip *.gz chmod +x./expand lapw./expand lapw You should have gotten the following directories:./src SRC_2Doptimize SRC_afminput SRC_aim SRC_arrows SRC_balsac-utils SRC_broadening SRC_cif2struct SRC_clmaddsub SRC_clmcopy SRC_dipan SRC_dstart SRC_elast SRC_eosfit SRC_eosfit6 SRC_filtvec SRC_fsgen SRC_hf SRC_initxspec SRC_irrep SRC_joint SRC_kgen SRC_kram SRC_lapw0 SRC_lapw1 SRC_lapw2 SRC_lapw3 SRC_lapw5 SRC_lapw7 SRC_lapwdm SRC_lapwso SRC_lcore SRC_lib SRC_lorentz SRC_lstart SRC_mini SRC_mixer SRC_nn SRC_optic SRC_optimize SRC_orb SRC_pairhess SRC_phonon SRC_qtl SRC_reformat SRC_sgroup SRC_spacegroup SRC_spaghetti SRC_structeditor SRC_sumhfpara SRC_sumpara SRC_supercell SRC_symmetry
230 212 CHAPTER 11. INSTALLATION AND DIMENSIONING SRC_symmetso SRC_telnes3 SRC_templates SRC_tetra SRC_trig SRC_txspec SRC_usersguide_html SRC_vecpratt SRC_w2web example_struct_files TiC TiO2 fccni Thus, each program has its source code (split into several files) in its own subdirectory. All programs are written in FORTRAN90 (except SRC sgroup and SRC reformat, which are in C). /SRC contains the users guide (in form of a postscript file usersguide.ps and as pdf-file usersguide.pdf), all c-shell scripts and some auxiliary files. /SRC usersguide html contains the html version of the UG. /Fccni, /TiC and /TiO2 contain three example inputs and the respective outputs. /example struct files contains a collection of various struct files, which could be of use especially for the less experienced user. /SRC templates contains various input templates. In addition to the expansion of the tar-files./expand lapw copies also all csh-shell scripts from /SRC to the current directory and creates links for some abbreviated commands Site configuration for WIEN2k At the end of expand lapw you will be prompted to start the script./siteconfig lapw When you start this script for the first time (file INSTALLDATE not present), you will be guided through the setup process. Later on you can use siteconfig lapw to redimension parameters, update individual packages and recompile the respective programs. During the first run, you will be asked to specify: your system; at this point system specific files (e.g. cputim.f will be installed. If your system is not listed, use the system generic, which should compile on any machine. your FORTRAN90 and C compilers; your compiler and linker options as well as the place for LAPACK and BLAS libraries. Depending on the system you selected, we have included some recommended compiler and linker options, which are known to work on our systems (use generic when you have problems here; see also sec ). On some systems it is required to specify LAPACK and BLAS libraries twice (i.e. R LIBS:-llapack lapw -lblas lapw -llapack lapw -lblas lapw). This generates Makefiles from the corresponding Makefile.orig in all subdirectories. configuration of parallel execution will ask whether your system is shared memory, so that default parameters can be set accordingly ( $WIENROOT/parallel options is the file where this information is stored). to configure parallel execution for distributed systems, specify the command to open a remote shell, which on most systems is rsh or ssh. You will then be asked wether you want to run fine-grained parallel. This is only possible if FFTW, MPI and SCALAPACK (included in newer mkl-versions) are installed on your system and requires a fast network (100Mb/s is not enough) or a shared memory machine. It pays off only for bigger cases (matrixsize > 5000).
231 11.2. INSTALLATION OF WIEN2K 213 You should define NMATMAX, i.e. the maximum matrixsize (number of basisfunctions). This value should be adjusted according to the memory of your hardware. Rough estimates are: NMATMAX= 5000 ==> 256MB (real, i.e. with inversion symmetry) NMATMAX=10000 ==> 1GB (real) (==> cells with about atoms/unitcell) If you choose it too large, lapw1 will start to page leading to inacceptable performance or a crash. NMATMAX will be automatically recuced (by 2) for complex (without inversion) cases and increased by NP E for mpi-parallel cases. Now you are prompted to compile all programs (this will be done using make) and the executables are copied to the $WIENROOT directory. Compilation might take quite some time. During compilation watch for error messages on the screen. If there are errors, you may need to change into the corresponding SRC * directory and examine file compile.msg for details. Common errors are wrong specification of compiler, linking or library options. In such cases, adopt the Makefile in this directory and recompile using make. Once you have proper options, correct them globally in siteconfig lapw and recompile. Later on you can use siteconfig lapw to change parameters, options or to update a package User configuration Each WIEN2k user should run the script userconfig lapw. This will setup a proper environment. The script userconfig lapw will do the following for you: set a path to WIEN2k programs set the stacksize to unlimited add aliases add environment variables ($WIENROOT, $SCRATCH) to your /.cshrc or /.bashrc file. Eventually you should also edit these files and set the $LD LIBRARY PATH variable (path where compiler-libs or blas-libraries are located). Note: This will work only when the csh, tcsh or bash-shell is your login shell. Depending on your settings you may have to add similar lines also in your.login file. If you are using a different login-shell, edit your startup files manually Performance and special considerations The script siteconfig lapw is provided for general configuration and compilation of the WIEN2k package. When you call this script for the first time and follow the suggested answers, WIEN2k should run on your system (see ). The codes in the individual subdirectories /SRC program are compiled using make. The file Makefile is generated during installation using Makefile.orig as template. In some directories the source files *.frc, *.F and param.inc r/c contain both, the real and complex (for systems without inversion symmetry) version of the code. You create the coresponding versions with make and make complex, respectively. (The *.frc and *.F files will then be preprocessed automatically). The fine-grained parallel versions lapw0 mpi; lapw1 mpi, lapw1c mpi, lapw2 mpi, lapw2c mpi are created using make para (lapw0) and make rp; make cp.
232 214 CHAPTER 11. INSTALLATION AND DIMENSIONING For timing purposes a subroutine CPUTIM is used in several programs and specific routines for IBM-AIX, HP-UX, DEC-OSF1, SGI and SUN are available. On other systems cputim generic.c should work. Most of the CPU time will be spent in lapw1 and (to a smaller extent) in lapw2 and lapw0. Therefore we recommend to optimize the performance for these 3 programs: Find out which compiler options (man name of compiler ) make these programs run faster. You could specify a higher optimization (-O3), or specify a particular processor architecture (-qarch=pwr5 or -R10000,...). Good performance depends on highly optimized BLAS (and much less on LAPACK) libraries. Whenever possible, replace the supplied libraries (SRC lib/blas lapw SRC lib/lapack lapw), by routines from your vendor (mkl for Intel or AMD processors, aclm for AMD, essl for IBM, sunperf for SUN, complib.sgimath on SGI,...). Because of the superior performance of the Intel-mkl library we recommend ifort/mkl instead of gfortan (or some other commercial f90 compiler). If such libraries are not available use the GOTO-library ( (Eventually you may try to optimize them yourself using the ATLAS system (see but this is no longer recommended. We provide an old ATLAS-BLAS for a Pentium3 with WIEN2k Global dimensioning parameters WIEN2k is written in Fortran 90 and all important arrays are allocated dynamically. The only important parameters left are NMATMAX and NUME, specifying the maximum matrixsize (should be adjusted to the memory of your hardware, see above) and the maximum number of eigenvalues (must be increased for unitcells with large number of electrons) Some less important parameters are still present and described in chapter dimensioning parameters of the respective section in chapter 6. We recommend to use siteconfig lapw for redimensioning and recompilation. In order to work properly, the parameter XXXX in the respective param.inc files must obey the following syntax: PARAMETER(XXXX=...) Note: between (, XXXX and = there must be no space Installation and Configuration of w2web General issues w2web requires perl, which should be available on most systems. (If not contact your system administrator or install it yourself from the WWW) When you start w2web for the first time on the computer where you want to execute WIEN2k (you may have to telnet, ssh,.. to this machine) with the command w2web [-p xxxx], you will be asked for a username/password (I recommend you use the same as for your UNIX login). You must also specify a port number (which can be changed the next time you start w2web). If the default port (7890) used to serve the interface is already in use by some other process, you will get the error message w2web failed to bind port port already in use!.
233 11.3. W2WEB 215 Then you will have to choose a different port number (between 1024 and 65536). Please remember this port number, you need it when connecting to the w2web server. Note: Only user root can specify port numbers below 1024! Once w2webhas been started, use your favorite WWW-browser to connect to w2web, specifying the correct portnumber, e.g. firefox where w2web runs:7890 On certain sites a firewall may block all high ports and one cannot connect to this machine. In these cases you can create a ssh-tunnel using the following commands: At your local host (the PC in front of you) connect to the w2web host (where you started w2web) using ssh -fnl 2000:w2web_host:7890 On your local host use a web browser and connect with: firefox Using Configuration you can further tailor the behaviour according to your wishes. In particular you can define new execution types to adjust to your queuing system. For example the line batch=batch < %f defines an execution type batch using the UNIX batch command. (w2web collects its commands in a temporary script and you can access it using %f). If you run on a machine with a queuing system (like loadleveler, sun-grid-engine, or pbs) you may define an execution type qsub=cat %f > w2web-job;qsub-wienjob_lapw The following scripts may serve as templates: qsub-wienjob lapw in $WIENROOT needs a master-job-template qsub-job0 lapw and examples for loadleveler and SGE are provided in $WIENROOT (you may need to adapt them! Other examples you can find on our FAQ-page on the web). Of course, with some small modifications you can define several execution types with eg. different number of processors or mpi vs. k-point parallel runs,... w2web saves several variables in startup files which are in the ( /.w2web) directory How does w2web work? w2web acts like a normal web-server - except that it runs on a user level port instead of the default http-port 80. It serves html-files and executes perl-scripts or executes system or user commands on the server host w2web-files in you home directory w2web creates on the first start of w2web on host hostname the directory.w2web/hostname in your home directory with the following content:.w2web/hostname/conf.w2web/hostname/logs.w2web/hostname/sessions
234 216 CHAPTER 11. INSTALLATION AND DIMENSIONING The configuration file conf/w2web.conf In this file various configuration parameters are stored by w2web. To restrict the access to certain IP addresses you can add lines like: deny=*.*.*.* allow= * The password file conf/w2web.users This file is created during the first run of w2web. If you remove this file, the next start of w2webwill activate the installation procedure again Using the https-protocol with w2web In order to use the https-protocol the perl-library Net::SSLeay in addition to the OpenSSL package must be installed on your system. Both are freely available. Then you must include a line with ssl=1 in w2web.conf. If you run w2web-server in ssl-mode you need a site certificate for your server. You may use the supplied certificate in $WIENROOT/SRC w2web/bin/w2web.pem (copy this file to your conf-directory and set the keyfile= /.w2web/<hostname>/conf/w2web.pem line in your w2web.conf). This certificate will not expire until 2015, but usually browsers will complain that they do not know the Certificate Authority who issued this certificate - if you don t like this message, you must buy a certificate from VeriSign, Thawte or a similar CA. Of course you must connect to https: instead of i.e. use: netscape where w2web runs: Environment Variables WIEN2k uses the following environment variables: WIENROOT base directory where WIEN2k is installed PDFREADER specifies program to read pdf files (acroread, xpdf,...) SCRATCH directory where case.vector and case.help?? are stored. On slow NFS-filesystems, a local scratch-directory could greatly enhance the performance. EDITOR path and name of your prefered editor STRUCTEDIT PATH path where the structeditor tool is located OCTAVE PATH path where the structeditor tool is located OCTAVE EXEC PATH path where octave looks for executables (structeditor) XCRYSDEN TOPDIR if this variable is set WIEN2k will activate all interface extensions to XCrysDen. USE REMOTE [0 1] determines whether parallel jobs are run in background (on shared memory machines) or using rsh. It is overridden by settings in $WIENROOT/parallel options MPI REMOTE [0 1] determines whether the mpirun command is issued on the master-node, or first an ssh to a remote node is done and there the mpirun command is issued. Usually, on many mpi-2 systems the first method is preferred, on mpi-1 the second.
235 11.4. ENVIRONMENT VARIABLES 217 WIEN GRANULARITY Default granularity for parallel execution. It is overridden by setting the granularity in the.machines file or in $WIENROOT/parallel options WIEN EXTRAFINE if set, the residual k-points are spread one by one over the processors. TASKSET [no command] specifies an optional command for binding a process to a specific core (like: taskset -c) In addition on some systems variables like: LD LIBRARY PATH path to libraries of compiler and math-libs OMP NUM THREADS on multi-core machines for parallelization in certain libraries (mkl, goto)
236 218 CHAPTER 11. INSTALLATION AND DIMENSIONING
237 12 Trouble shooting In this chapter hints are given for solving some difficulties that have occurred frequently. This chapter is by no means complete and the authors would appreciate further suggestions which might be useful for other users. Beside the printed version of the users guide, an online pdf version is available using help lapw. You can search for a specific keyword (use f keyword) and hopefully find some information. There is a mailing list for WIEN2k related questions. To subscribe to this list goto: and subscribe. You will then automatically be added to the mailing list and can post questions. Please make use of this list! If an error occurs in one of the SCF programs, a file program.error is created and an error message is printed into these files. The run lapw script checks for these files and will automatically stop if a non-empty error file occurs. Check the files case.dayfile (which is written by init lapw and run lapw), :log (where a history of all commands using x is given) and *.error for possible explanations. In several places the dimensions are checked. The programs print a descriptive error message and stop. case.outputnn: This file gives error messages if the atomic spheres overlap. But it should also be used to check the distances between the atoms and the coordination number (same distance). If inconsistencies exists, your case.struct file may contain an error. A check for overlapping spheres is also included in mixer and lapw1. case.outputd: Possible stops or warnings are: NO SYMMETRY OPERATION FOUND IN ROTDEF : This indicates that in your case.struct file either the positions of equivalent atoms are not specified correctly (only positive coordinates allowed!!) or the symmetry operations are wrong. case.output1: Possible stops or warnings are: NO ENERGY LIMITS FOUND IN SELECT : This indicates that E top or E bottom could not be found for some u l (r, E l ). Check your input if it happens in the zeroth iteration. Later, (usually in the second to sixth iteration) it may indicate that in your SCF cycle something went wrong and you are using a crazy potential. Usually it means that mixing of the charge densities was diverging and large charge fluctuations occured. Check previous charges for being physically reasonable (grep for labels :NTOxx :CTOxx :DIS :NEC01). Usually this happens when your input is not ok, or for very ill 219
238 220 CHAPTER 12. TROUBLE SHOOTING conditioned problems (very rare), or more likely, when Ghostbands appeared (or some states were missing) because of bad energy parameters in case.in1. You will probably have to delete case.broy* and case.scf, rerun x dstart and then change some calculational parameters. These could be: fixing some energy parameter (modify both, case.in1 and case.in1 orig or try the -in1orig switch if you have used -in1new); switch to a broadening method (TEMP with eg mry); or increase the k-mesh (magnetic metals); or reduce the mixing parameter in case.inm slightly (eg. to 0.1). In very difficult (magnetic) cases a PRATT mixing with eg mixing might be helpful at the beginning of the scf cycle (but later switch to MSEC1 again)! STOP RDC 22 : This indicates that the overlap matrix is not positive definite. This usually happens if your case.struct file has some error in the structure or if you have an (almost) linear dependent basis, which can happen for large RKMAX values and/or if you are using very different (extremely small and large) sphere radii R MT. X EIGENVALUES BELOW THE ENERGY emin : This indicates that X eigenvalues were found below emin. Emin is set in case.in1 (see sec ) or in case.klist generated by KGEN, see 6.3, 6.5). It may indicate that your value of emin is too high or the possibility of ghostbands, but it can also be intentional to truncate some of the low lying eigenvalues. If you don t find enough eigenvalues (e.g.: in a cell with 4 oxygens you expect 4 oxygen s bands at roughly -1 Ry) check the energy window (given at the end of the first k-point in case.in1 or in case.klist) and make sure your energy parameters are found by subroutine SELECT or set them by hand at a reasonable value. case.output2: Possible stops or warnings are: CANNOT BE FOUND : This warning, which could produce a very long output file, indicates that some reciprocal K-vector would be requested (through the k-vector list of lapw1), but was not present in the list of the K generated in lapw2. You may have to increase the NWAV, and/or KMAXx parameters in lapw2 or increase GMAX in case.in2. The problems could also arise from wrong symmetry operations or a wrong structure in case.struct. QTL-B VALUE : If larger than a few percent, this indicates the appearance of ghost bands, which are discussed below in section The few percent message (e.g up to 10 %) does not indicate a ghost band, but can happen e.g. in narrow d-bands, where the linearization reaches its limits. In these cases one can add a local orbital to improve the flexibility of the basis set. (Put one energy near the top and the other near the bottom of the valence band, see section 7.5.3). FERMI LEVEL not converged (or similar messages). This can have several reasons: i) Try a different Fermi-Method (change TETRA to GAUSS or TEMP in case.in2). ii) Count the number of eigenvalues in case.output1 and compare it with the number of valence electrons. If there are too few eigenvalues, either increase EMAX in case.klist (from 1.5 to e.g. 2.5) or check if your scf cycle had large charge oszillations (see SELECT error above) If the SCF cycle stops somewhere (especially in the first few iterations), it is quite possible, that the source of the error is actually in a previous part of the cycle or even in a previous (e.g. the zeroth) iteration. Check in the case.scf file previous charges, eigenvalues,... whether they are physically reasonable (see SELECT error above) Ghost bands Approximate linear dependence of the basis set or the linearization of the energy dependence of the radial wave functions (see section 2.2) can lead to spurious eigenvalues, termed ghost bands.
239 12.1. GHOST BANDS 221 The first case may occur in a system which has atoms with very different atomic sphere radii. Suppose you calculate a hydroxide with very short O-H bonds so that you select small R MT radii for O and H such as e.g. 1.0 and 0.6 a.u., respectively. The cation may be large and thus you could choose a large R MT of e.g. 2.4 a.u. However, this gives a four time larger effective RKmax for the cation than for H, (e.g when you select RKmax=4.0 in case.in1). This enormous difference in the convergence may lead to unphysical eigenvalues. In such cases choose lmax=12 in case.in1 (in order to get a very good re-expansion of the plane waves) and reduce R MT for the cation to e.g. 1.8 a.u. The second case can occur when you don t use a proper set of local orbitals. In this situation the energy region of interest (valence bands) falls about midway between two states with different principle quantum numbers, but with the same l-value (for one atom). Take for example Ti with its 3p states being occupied as (semi-core) states, while the 4p states remain mostly unoccupied. In the valence band region neither of those two states (Ti 3p, 4p) should appear. If one uses 0.2 Ry for the expansion energy E(1) for the p states of Ti, then Ti-p states do appear as ghost bands. Such a run is shown below for T io 2 (rutile). The lowest six eigenvalues at GAMMA fall between about and Ry. They are ghost bands derived from fictitious Ti-p states. The next four eigenvalues between and Ry correspond to states derived from O 2s states, which are ok, since there are four O s per unit cell, four states are found. The occurrence of such unphysical (indeed, unchemical!) ghostbands is the first warning that something went wrong. A more definite warning comes upon running LAPW2, where the corresponding charge densities are calculated. If the contribution to the charge density from the energy derivative of the basis function [the B lm coefficient in equ. 2.4,2.7] is significant (i.e. much more than 5 per cent) then a warning is issued in LAPW2. In the present example it reads: QTL-B VALUE.EQ !!!!!! This message is found in both the case.scf file and in case.output2. When such a message appears, one can also look at the partial charges (QTL), which are printed under these conditions to OUTPUT2, and always appear in the files case.helpxxx, etc., where the last digit refers to the atomic index. In the file below, note the E(1) energy parameter as well as the 6 ghost band energies around top of file:tio2.scf ATOMIC SPHERE DEPENDENT PARAMETERS FOR ATOM Titanium OVERALL ENERGY PARAMETER IS.2000 E( 0)= > E( 1)=.2000 E( 2)=.2000 E(BOTTOM)= E(TOP)= ATOMIC SPHERE DEPENDENT PARAMETERS FOR ATOM Oxygen OVERALL ENERGY PARAMETER IS.2000 E( 0)= E(BOTTOM)= E(TOP)=.670 K= :RKM : MATRIX SIZE= 599 RKM= 6.99 WEIGHT= 8.00 PGR: EIGENVALUES ARE: ******************************************************** NUMBER OF K-POINTS: 1
240 222 CHAPTER 12. TROUBLE SHOOTING :NOE : NUMBER OF ELECTRONS = :FER : F E R M I - ENERGY = :POS01: AT.NR. -1 POSITION = MULTIPLICITY= 2 LMMAX=10 LM= :CHA01: TOTAL CHARGE INSIDE SPHERE 1 = :PCS01: PARTIAL CHARGES SPHERE = 1 S,P,D,F,PX,PY,PZ,D-Z2,D-X2Y2,D-XY,D-XZ,D-YZ :QTL01: VXX VYY VZZ UP TO R :VZZ01: :POS02: AT.NR. -2 POSITION = MULTIPLICITY= 4 LMMAX=16 LM= :CHA02: TOTAL CHARGE INSIDE SPHERE 2 = :PCS02: PARTIAL CHARGES SPHERE = 2 S,P,D,F,PX,PY,PZ,D-Z2,D-X2Y2,D-XY,D-XZ,D-YZ :QTL02: VXX VYY VZZ UP TO R :VZZ02: :CHA : TOTAL CHARGE INSIDE CELL = :SUM : SUM OF EIGENVALUES = QTL-B VALUE.EQ !!!!!! NBAND in QTL-file: end of truncated file tio2.scf Next we show tio2.output2 for the first of the ghost bands at Ry. One sees that it corresponds mainly to a p-like charge, which originates from the energy derivative part Q(UE) of the Kohn-Sham orbital. Q(UE) contributes 40.1% compared with 8.5% from the main component Q(U). Q(UE) greater than Q(U) is a good indication for a ghost band part of file tio2.output QTL-B VALUE.EQ !!!!!! K-POINT: BAND # 1 E= WEIGHT= L= 0 L= 1 PX: PY: PZ: L= 2 DZ2: DX2Y2: DXY: DXZ: DYZ: L= 3 QINSID: Q(U) : Q(UE) : L= 0 L= 1 PX: PY: PZ: L= 2 DZ2: DX2Y2: DXY: DXZ: DYZ: L= 3 QINSID: Q(U) : Q(UE) : QOUT : bottom of truncated file Another file in which the same information can be found is tio2.help031, since the ghost band is caused by a bad choice for the Ti-p energy parameter: Top of file tio2.help K-POINT: BAND # 1 E= WEIGHT= L= L= PX: PY: PZ: L= DZ2: DX2Y2: DXY: DXZ: DYZ: L= L= L= L= bottom of truncated file Note again for L=1 the percentage of charge associated with the primary (APW) basis functions ul (8.5%) versus that coming from the energy derivative component (40.1%).
241 12.1. GHOST BANDS 223 If a ghost band appears, one should first analyze its origin as indicated above, then use appropriate local orbitals to improve the calculation and get rid of these unphysical states. Do not perform calculations with ghost-bands, even when the calculation converges. Good luck!
242 224 CHAPTER 12. TROUBLE SHOOTING
243 13 References Abt R., Ambrosch-Draxl C. and Knoll P Physica B Abt R PhD Theses, Univ.Graz Ahmed S.J., Kivinen J., Zaporzan B., Curiel L., Pichardo S. and Rubel O Comp. Phys. Commun. 184, Andersen O.K Solid State Commun. 13, Phys. Rev. B 12, 3060 Ambrosch-Draxl C., Blaha P., and Schwarz K Phys.Rev. B44, 5141 Ambrosch-Draxl C., Majewski J. A., Vogl P., and Leising G. 1995, PRB Ambrosch-Draxl C. and Sofo J., 2006 Comp. Phys. Comm. 175, 1 V.I. Anisimov, I.V. Solovyev, M.A. Korotin, M.T. Czyzyk, and G.A. Sawatzky, Phys. Rev. B 48, (1993). V.I. Anisimov, J. Zaanen, and O.K. Andersen, Phys. Rev. B 44, 943 (1991) Bader R. F. W. 2001: Blaha P. and Schwarz K Int. J. Quantum Chem. XXIII, 1535 Blaha P., Schwarz K., and Herzig P 1985 Phys. Rev. Lett. 54, 1192 Blaha P., Schwarz K., and Dederichs P 1988 Phys. Rev B 38, 9368 Blaha P., Schwarz K., Sorantin P.I. and Trickey S.B Comp. Phys. Commun. 59, 399 Blaha P., Sorantin P.I., Schwarz K and Singh D Phys. Rev. B 46, 1321 Blaha P., Hofstätter H., Koch R., Laskowski R. and Schwarz K. 2009, J.Comput.Phys. 229, 453. Blöchl P.E., Jepsen O. and Andersen O.K. 1994, Phys. Rev B 49, Boettger J.C. and Albers R.C Phys. Rev. B 39, 3010 Boettger J.C. and Trickey S.B Phys. Rev. B 29, 6425 Brooks M.S.S Physica B 130, 6 Charpin, T (see $WIENROOT/SRC/elast-UG.ps) Czyzyk M.T. and G.A. Sawatzky, Phys. Rev. B 49, (1994). 225
244 226 CHAPTER 13. REFERENCES Desclaux J.P Comp. Phys. Commun. 1, 216; note that the actual code we use is an apparently unpublished relativistic version of the non-relativistic code described in this paper. Though this code is widely circulated, we have been unable to find a formal reference for it Comp. Phys. Commun. 9, 31; this paper contains much of the Dirac-Fock treatment used in Desclaux s relativistic LSDA code. O. Eriksson, B. Johansson, and M.S.S. Brooks, J. Phys. C 1, 4005 (1989) Feldman J.L., Mehl M.J., and Krakauer H Phys. Rev. B 35, 6395 Gay David M., ALGORITHM 611 Subroutines for Unconstrained Minimization Using a Model/Trust-Region Approach, ACM Trans. Math. Software 9 (1983), pp Grimme S., Antony J., Ehrlich, S. and Krieg, H J. Chem. Phys. 132, Haas P., Tran F., Blaha P., Schwarz K. 2011, Phys.Rev. B 83, Hébert-Souche C., Louf P.-H., Blaha P., M. Nelhiebel, Luitz J., Schattschneider P., Schwarz K. and Jouffrey B.; The orientation dependent simulation of ELNES, Ultramicroscopy, 83, 9 (2000) L.L. Hirst, Rev. Mod. Phys. 69, 607 (1997) Hohenberg P. and Kohn W Phys. Rev. 136, B864 International Tables for X-Ray Crystallography 1964 Vol.1; The Kynoch Press, Birmingham UK Jansen H.J.F. and Freeman A.J Phys. Rev. B 30, Phys. Rev. B 33, 8629 King-Smith R.D., Vanderbilt D Phys. Rev. B 47, 1651 Koelling D.D J. Phys. Chem. Solids 33, 1335 Koelling D.D. and Arbman G.O J.Phys. F: Met. Phys. 5, 2041 Koelling D.D. and Harmon B.N J. Phys. C: Sol. St. Phys. 10, 3107 Kohler B., Wilke S., Scheffler M., Kouba R. and Ambrosch-Draxl C Comp.Phys.Commun. 94, 31 Kohn W. and Sham L.J Phys. Rev. 140, A1133 Kokalj A J.Mol.Graphics and Modelling 17, 176 Koller D., Tran F. and Blaha P Phys. Rev. B 85, Krimmel H.G., Ehmann J., Elsässer C., Fähnle M. and Soler J.M. 1994, Phys.Rev. B50, 8846 Kuneš J, Novák P., Schmid R., Blaha P. and Schwarz K. 2001, Phys. Rev. B64, Kara, M. and Kurki-Suonio K Acta Cryst A37, 201 Laskowski R. and Blaha P. 2012a, Phys. Rev. B 85, Laskowski R. and Blaha P. 2012b, Phys. Rev. B 85, Laskowski R., Blaha P., and Tran F. 2013, Phys. Rev. B 87,
245 227 Liberman D., Waber J.T., and Cromer D.T. 1965, Phys. Rev. 137A, 27 A.I. Liechtenstein, V. I. Anisimov, J. Zaanen, Phys. Rev. B 52, R5467 (1995) Luitz J., Maier M., Hébert C., Schattschneider P., Blaha P., Schwarz K., Jouffrey B Eur. Phys J. B 21, MacDonald A. H., Pickett, W. E. and Koelling, D. D J. Phys. C 13, 2675 Madsen G. K. H., Blaha P, Schwarz K, Sjöstedt E and Nordström L 2001, Phys. Rev. B64, Marks L. D., and Luke R. 2008, Phys. Rev. B 78, Marks L. D. 2013, J. Chem. Theory Comput., 9, 2786 Mattheiss L.F. and Hamann D.R Phys. Rev. B 33, 823 Mattsson A., Armiento R., Paier J., Kresse G., Wills J. and Mattsson T 2008 J. Chem. Phys. 128, Meyer-ter-Vehn J. and Zittel W Phys. Rev. B37, 8674 Moruzzi V.L., Janak J.F., and Williams A.R Calculated Properties of Metals (Pergamon, NY) Murnaghan F.D., Proc.Natl.Acad.Sci. USA 30, 244 (1944) Neckel A., Schwarz K., Eibler R. and Rastl P Microchim.Acta, Suppl.6, 257 Nelhiebel M., Louf P. H., Schattschneider P., Blaha P., Schwarz K. and Jouffrey B.; Theory of orientation sensitive near-edge fine structure core-level spectroscopy, Phys.Rev. B59, (1999) Novak P see $WIENROOT/SRC/novak lecture on spinorbit.ps Novák P., Boucher F., Gressier P., Blaha P. and Schwarz K Phys. Rev. B 63, Novák P see $WIENROOT/SRC/novak lecture on ldaumatrixelements.ps and Novak P see $WIENROOT/SRC/Bhf 3.ps and Paier J., Marsman M., Hummer K., Kresse G., Gerber I. C. and Ángyán J. G., J. Chem. Phys. 124, (2006) Ortenzi L., Mazin I., Blaha P. and Boeri L. 2012, Phys. Rev. B (in print) Pardini L., Bellini V., Manghi F. and Ambrosch-Draxl C. 2011, Comp.Phys.Commun. 183, 628 (2012) Perdew J.P, Chevary J.A., Vosko S.H., Jackson K.A., Pederson M.R., Singh D.J., and Fiolhais C Phys.Rev.B46, 6671 Perdew J.P. and Wang Y. 1992, Phys.Rev. B45, Perdew J.P., Burke S. and Ernzerhof M. 1996, Phys.Rev.Let. 77, 3865 Perdew J.P., Kurth S., Zupan J. and Blaha P. 1999, Phys.Rev.Let. 82, 2544 Perdew J.P. et al. 2008, Phys. Rev. Let. 100,
246 228 CHAPTER 13. REFERENCES Perdew,J.P. et al., 2009, Phys. Rev. Lett. 103, and 106, (E) (2011). Pratt G.W Phys. Rev. 88, 1217 Ray A.K. and Trickey S.B Phys. Rev. B24, 1751; erratum 1983, Phys. Rev. B28, 7352 Reshak A. and Jamal M. 2013, J. Alloys and Compounds, 555, 362 Resta R., Posternak M. and Baldereschi A Phys. Rev. Lett. 70, 1010 Rondinelli JM, Beng Bin and Marks LD. 2007, Comp. Mater. Sci. 40, (also: Los Alamos archive, physics/ ( Schwarz K., Neckel A and Nordgren J, J.Phys.F:Metal Phys. 9, 2509 (1979) Schwarz K., and Wimmer E, J.Phys.F:Metal Phys. 10, 1001 (1980) Schwarz K. and Blaha P.: Lecture Notes in Chemistry 67, 139 (1996) Schwarz K., P.Blaha and Madsen, G. K. H. Comp.Phys.Commun. 147, 71 (2002) Singh D., Krakauer H., and Wang C.-S Phys. Rev. B34, 8391 Singh, D Phys. Rev. B40, 5428 Singh D. 1991, Phys.Rev. B43, 6388 Singh D. and Nordström L 2006, Plane waves, pseudopotentials and the LAPW method, 2 nd edition, Springer, New York Sjöstedt E, Nordström L and Singh D. J Solid State Commun. 114, 15 Sofo J and Fuhr J 2001: $WIENROOT/SRC/aim sofo notes.ps Soler J.M. and Williams A.R. 1989, Phys.Rev. B40, 1560 Sorantin P.I., and Schwarz K.H. 1992, Inorg.Chem. 31, 567 Stahn J, Pietsch U, Blaha P and Schwarz K. 2001, Phys.Rev. B63, Sun J., Xiao B., Fang Y., Haunschild R., Hao P., Ruzsinszky A., Csonka G., Scuseria G., Perdew J Phys Rev. Lett. 111, Tao Jianmin, Perdew J.P., Staroverov V. and Scuseria G. 2003, Phys.Rev.Let. 91, Tran F, Blaha P Schwarz K and Novak P 2006, Phys. Rev. B 74, Tran F, Laskowski R, Blaha P and Schwarz K. 2007, Phys. Rev. B 75, Tran F and Blaha P 2009, Phys. Rev. Lett. 102, Tran F, Blaha P 2011, Phys. Rev. B 83, Tran F 2012 Phys. Lett. A (in press) von Barth U. and Hedin L J. Phys. C.: Sol. St. Phys. 5, 1629 Wei S.H., Krakauer H., and Weinert M Phys. Rev. B 32, 7792 Weinert M J. Math. Phys. 22, 2433 Weinert M., Wimmer E., and Freeman A.J Phys. Rev. B26, 4571 Wimmer E., Krakauer H., Weinert M., and Freeman A.J Phys. Rev. B24, 864
247 229 Wu Z., Cohen R., 2006 Phys. Rev. B73, Yanchitsky B. and Timoshevskii T. 2001, Comp.Phys.Commun. 139, 235 Yu R., Singh D. and Krakauer H. 1991, Phys.Rev. B43, 6411
248 230 CHAPTER 13. REFERENCES
249 Part IV Appendix 231
250
251 A Local rotation matrices Local rotation matrices are used to rotate the global coordinate system (given by the definition of the Bravais matrix) to a local coordinate system for each atomic site. They are used in the program for two reasons: to minimize the number of LM combinations in the lattice harmonics expansion (of potential and charge density according to equ. 2.10). For example for point group mm2 one needs for L=1 just LM=1,0 if the coordinate system is chosen such that the z-axis coincides with the 2-fold rotation axis, while in an arbitrary coordinate system the three terms 1,0; 1,1 and -1,1 are needed (and so on for higher L). The interpretation e.g. of the partial charges requires a proper orientation of the coordinate system. In the example given above, the p orbitals split into 2 irreducible representations, but they can be attributed to p z and p x, p y only if the z-axis is the 2-fold rotation axis. It is of course possible to perform calculations without local rotation matrices, but in such a case the LM combinations given in Table 7.51 (and by SYMMETRY) may not be correct. (The LM values for arbitrary orientations may be obtained from a procedure described in Singh 94.) Fortunately, the local rotation matrices are usually fairly simple and are now automatically inserted into your case.struct file. Nevertheless we recommend to check them in order to be sure. The most common coordinate transformations are interchanging of two axes (e.g. x and z) rotation by 45 (e.g. in the xy-plane) rotation of z into the (111) direction Inspection of the output of SYMMETRY tells you if the local rotation matrix is the unit matrix or it gives you a clear indication how to find the proper matrix. The local rotation matrix R, which transforms the global coordinates r to the rotated ones r, is defined by Rr = r. There are two simple ways to check the local rotation matrixes together with the selected LM combinations: charge density plots generated with LAPW5 must be continuous across the atomic sphere boundary (especially valence or difference density plots are very sensitive, see 8.13) Perform a run of LAPW1 and LAPW2 using the GAMMA-point only (or a complete star of another k point). In such a case, wrong LM combinations must vanish. Note that the latter is true only in this case. For a k mesh in the IBZ wrong LM combinations do not vanish and thus must be omitted!! A first example for local rotation matrices is given for the rutile TiO2, which has already been described as an example in section Also two other examples will be given (see below). 233
252 234 APPENDIX A. LOCAL ROTATION MATRICES A.1 Rutile (T io 2 ) Examine the output from symmetry. It should be obvious that you need local rotation matrices for both, Ti and O:... Titanium operation # 1 1 Titanium operation # 2-1 Titanium operation # 5 2 z Titanium operation # 6 m n z Titanium operation # 12 m n 110 Titanium operation # 13 m n -110 Titanium operation # Titanium operation # pointgroup is mmm (neg. iatnr!!) axes should be: m n z, m n y, m n x This output tells you, that for Ti a mirror plan normal to z is present, but the mirror planes normal to x and y are missing. Instead, they are normal to the (110) plane and thus you need to rotate x, y by 45 around the z axis. (The required choice of the coordinate system for mmm symmetry is also given in Table 7.51)... Oxygen operation # 1 1 Oxygen operation # 6 m n z Oxygen operation # 13 m n -110 Oxygen operation # pointgroup is mm2 (neg. iatnr!!) axes should be: 2 z, m n y For O the 2-fold symmetry axes points into the (110) direction instead of z. The appropriate rotation matrices for Ti and O are: A.2 Si Γ-phonon Si possesses a face-centered cubic structure with two equivalent atoms per unit cell, at (±0.125, ±0.125, ±0.125). The site symmetry is -43m. For the Γ-phnon the two atoms are displaced in opposite direction along the (111) direction and cubic symmetry is lost. The output of SYMMETRY gives the following information: Si operation # 1 1 Si operation # 13 m n -110 Si operation # 16 m n -101 Si operation # 17 m n 0-11 Si operation # Si operation # pointgroup is 3m (neg. iatnr!!) axis should be: 3 z, m n y lm:
253 A.3. TRIGONAL SELENIUM 235 Therefore the required local rotation matrix should rotate z into the (111) direction and thus the matrix in the struct file should be: A.3 Trigonal Selenium Selenium possesses space group P3121 with the following struct file: H LATTICE,NONEQUIV.ATOMS: 1 MODE OF CALC=RELA POINTGROUP: ATOM= -1: X= Y= Z= MULT= 3 ISPLIT= 8 ATOM= -1: X= Y= Z= ATOM= -1: X= Y= Z= Se NPT= 381 R0= RMT= Z:34.0 LOCAL ROT.MATRIX: IORD OF GROUP G0... The output of SYMMETRY reads: Se operation # 1 1 Se operation # 9 2 $ $$ $ 110 pointgroup is 2 (neg. iatnr!!) axis should be: 2 z lm: Point group 2 should have its 2-fold rotation axis along z, so the local rotation matrix can be constructed in two steps: firstly interchange x and z (that leads to z (011) ) and secondly rotate from (011) into (001) (see the struct file given above). Since this is a hexagonal lattice, SYMMETRY uses the hexagonal axes, but the local rotation matrix must be given in cartesian coordinates.
254 236 APPENDIX A. LOCAL ROTATION MATRICES
255 B Periodic Table 237
256 238 APPENDIX B. PERIODIC TABLE informationMore information
General Principles of Software Validation; Final Guidance for Industry and FDA Staff
General Principles of Software Validation; Final Guidance for Industry and FDA Staff Document issued on: January 11, 2002 This document supersedes the draft document, "General Principles of Software Validation,More
Base Tutorial: From Newbie to Advocate in a one, two... three!
Base Tutorial: From Newbie to Advocate in a one, two... three! BASE TUTORIAL: From Newbie to Advocate in a one, two... three! Step-by-step guide to producing fairly sophisticated database applications
Single-Electron Devices and Their Applications
Single-Electron Devices and Their Applications KONSTANTIN K. LIKHAREV, MEMBER, IEEE Invited Paper The goal of this paper is to review in brief the basic physics of single-electron devices, as well as theirMoreMoreMore informationMore informationuMore information
Modelling with Implicit Surfaces that Interpolate
Modelling with Implicit Surfaces that Interpolate Greg Turk GVU Center, College of Computing Georgia Institute of Technology James F O Brien EECS, Computer Science Division University of California, BerkeleyMore information
CRYSTAL09. 2.0.1 User s Manual February 6, 2013. Av. Universidad 1001, Col. Chamilpa, 62210 Cuernavaca (Morelos) Mexico
1 CRYSTAL09 2.0.1 User s Manual February 6, 2013 R. Dovesi 1, V.R. Saunders 1, C. Roetti 1, R. Orlando 1,3, C. M. Zicovich-Wilson 1,4, F. Pascale 5, B. Civalleri 1, K. Doll 6, N.M. Harrison 2,7, I.J. BushMore information
Scalable Collaborative Filtering with Jointly Derived Neighborhood Interpolation Weights
Seventh IEEE International Conference on Data Mining Scalable Collaborative Filtering with Jointly Derived Neighborhood Interpolation Weights Robert M. Bell and Yehuda Koren AT&T Labs Research 180 ParkMore information
Why Johnny Can t Encrypt
In Security and Usability: Designing Secure Systems that People Can Use, eds. L. Cranor and G. Simson. O'Reilly, 2005, pp. 679-702 CHAPTER THIRTY- FOUR Why Johnny Can t Encrypt A Usability EvaluationMore informationMore information
Introduction to Data Mining and Knowledge Discovery
Introduction to Data Mining and Knowledge Discovery Third Edition by Two Crows Corporation RELATED READINGS Data Mining 99: Technology Report, Two Crows Corporation, 1999 M. Berry and G. Linoff, Data Mining
b-initio VASP the GUIDE
b-initio ienna ackage imulation VASP the GUIDE written by Georg Kresse, Martijn Marsman, and Jürgen Furthmüller Computational Materials Physics, Faculty of Physics, Universität Wien, Sensengasse 8/12,More?More information
The InStat guide to choosing and interpreting statistical tests
Version 3.0 The InStat guide to choosing and interpreting statistical tests Harvey Motulsky 1990-2003, GraphPad Software, Inc. All rights reserved. Program design, manual and help screens: Programming:More information | http://docplayer.net/55985-Wien2k-an-augmented-plane-wave-plus-local-orbitals-program-for-calculating-crystal-properties.html | CC-MAIN-2018-39 | refinedweb | 82,862 | 55.44 |
#include "core/or/or.h"
#include "app/config/config.h"
#include "core/mainloop/connection.h"
#include "core/or/policies.h"
#include "core/or/reasons.h"
#include "feature/client/entrynodes.h"
#include "feature/dirclient/dirclient.h"
#include "feature/dircommon/directory.h"
#include "feature/nodelist/describe.h"
#include "feature/nodelist/dirlist.h"
#include "feature/nodelist/microdesc.h"
#include "feature/nodelist/networkstatus.h"
#include "feature/nodelist/node_select.h"
#include "feature/nodelist/nodelist.h"
#include "feature/nodelist/routerlist.h"
#include "feature/nodelist/routerset.h"
#include "feature/relay/router.h"
#include "feature/relay/routermode.h"
#include "lib/container/bitarray.h"
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/math/fp.h"
#include "feature/dirclient/dir_server_st.h"
#include "feature/nodelist/networkstatus_st.h"
#include "feature/nodelist/node_st.h"
#include "feature/nodelist/routerinfo_st.h"
#include "feature/nodelist/routerstatus_st.h"
Go to the source code of this file.
Code to choose nodes randomly based on restrictions and weighted probabilities.
Definition in file node_select.c.
When weighting bridges, enforce these values as lower and upper bound for believable bandwidth, because there is no way for us to verify a bridge's bandwidth currently.
Definition at line 524 of file node_select.c.
Definition at line 140 of file node_select.c.
Definition at line 158 of file node_select.c.
Definition at line 176 of file node_select.c.
Return the smaller of the router's configured BandwidthRate and its advertised capacity, making sure to stay within the interval between bridge-min-believe-bw and bridge-max-believe-bw.
Definition at line 532 of file node_select.c.
References routerinfo_t::bandwidthcapacity, and routerinfo_t::bandwidthrate.
Pick a random element of n_entries-element array entries, choosing each element with a probability proportional to its (uint64_t) value, and return the index of that element. If all elements are 0, choose an index at random. Return -1 on error.
Definition at line 453 of file node_select.c.
References crypto_rand_int(), crypto_rand_uint64(), select_array_member_cumulative_timei(), and tor_assert().
Given a list of routers and a weighting rule as in smartlist_choose_node_by_bandwidth_weights, compute weighted bandwidth values for each node and store them in a freshly allocated *bandwidths_out of the same length as sl, and holding results as doubles. If total_bandwidth_out is non-NULL, set it to the total of all the bandwidths. Return 0 on success, -1 on failure.
Definition at line 552 of file node_select.c.
References tor_assert().
Referenced by smartlist_choose_node_by_bandwidth_weights().
Pick a random element from a list of dir_server_t, weighting by their weight field.
Definition at line 1016 of file node_select.c.
For all nodes in sl, return the fraction of those nodes, weighted by their weighted bandwidths with rule rule, for which we have descriptors.
If for_direct_connect is true, we intend to connect to the node directly, as the first hop of a circuit; otherwise, we intend to connect to it indirectly, or use it as if we were connecting to it indirectly.
Definition at line 768 of file node_select.c.
Return bw*1000, unless bw*1000 would overflow, in which case return INT32_MAX.
Definition at line 479 of file node_select.c.
Choose a random element of status list sl, weighted by the advertised bandwidth of each node
Definition at line 803 of file node_select.c.
References smartlist_choose_node_by_bandwidth_weights().
Remove every node_t that appears in excluded from sl.
Behaves like smartlist_subtract, but uses nodelist_idx values to deliver linear performance when smartlist_subtract would be quadratic.
Definition at line 837 of file node_select.c.
Return a random running node from the nodelist. Never pick a node that is in excludedsmartlist, or which matches excludedset, even if they are the only nodes available. If CRN_NEED_UPTIME is set in flags and any router has more than a minimum uptime, return one of those. If CRN_NEED_CAPACITY is set in flags, weight your choice by the advertised capacity of each router. If CRN_NEED_GUARD is set in flags, consider only Guard routers. If CRN_WEIGHT_AS_EXIT is set in flags, we weight bandwidths as if picking an exit node, otherwise we weight bandwidths for picking a relay node (that is, possibly discounting exit nodes). If CRN_NEED_DESC is set in flags, we only consider nodes that have a routerinfo or microdescriptor – that is, enough info to be used to build a circuit. If CRN_PREF_ADDR is set in flags, we only consider nodes that have an address that is preferred by the ClientPreferIPv6ORPort setting (regardless of this flag, we exclude nodes that aren't allowed by the firewall, including ClientUseIPv4 0 and fascist_firewall_use_ipv6() == 0).
Definition at line 903 of file node_select.c.
Try to find a running dirserver that supports operations of type.
If there are no running dirservers in our routerlist and the PDS_RETRY_IF_NO_SERVERS flag is set, set all the fallback ones (including authorities) as running again, and pick one.
If the PDS_IGNORE_FASCISTFIREWALL flag is set, then include dirservers that we can't reach.
If the PDS_ALLOW_SELF flag is not set, then don't include ourself (if we're a dirserver).
Don't pick a fallback directory mirror if any non-fallback is viable; (the fallback directory mirrors include the authorities) try to avoid using servers that have returned 503 recently.
Definition at line 71 of file node_select.c.
Pick a random running valid directory server/mirror from our routerlist. Arguments are as for router_pick_directory_server(), except:
If n_busy_out is provided, set *n_busy_out to the number of directories that we excluded for no other reason than PDS_NO_EXISTING_SERVERDESC_FETCH or PDS_NO_EXISTING_MICRODESC_FETCH.
Definition at line 294 of file node_select.c.
Try to find a running fallback directory. Flags are as for router_pick_directory_server.
Definition at line 103 of file node_select.c.
Try to find a running fallback directory. Flags are as for router_pick_directory_server.
Definition at line 1006 of file node_select.c.
Try to find a running directory authority. Flags are as for router_pick_directory_server.
Definition at line 995 of file node_select.c.
Choose randomly from among the dir_server_ts in sourcelist that are up. Flags are as for router_pick_directory_server_impl().
Definition at line 1044 of file node_select.c.
Given a router, add every node_t in its family (including the node itself!) to sl.
Note the type mismatch: This function takes a routerinfo, but adds nodes to the smartlist!
Definition at line 816 of file node_select.c.
References DIGEST_LEN, node_t::identity, signed_descriptor_t::identity_digest, and nodelist_add_node_and_family().
Given an array of double/uint64_t unions that are currently being used as doubles, convert them to uint64_t, and try to scale them linearly so as to much of the range of uint64_t. If total_out is provided, set it to the sum of all elements in the array before scaling.
Definition at line 424 of file node_select.c.
References tor_llround().
Helper function: choose a random element of smartlist sl of nodes, weighted by the advertised bandwidth of each element using the consensus bandwidth weights.
If rule==WEIGHT_FOR_EXIT. we're picking an exit node: consider all nodes' bandwidth equally regardless of their Exit status, since there may be some in the list because they exit to obscure ports. If rule==NO_WEIGHTING, we're picking a non-exit node: weight exit-node's bandwidth less depending on the smallness of the fraction of Exit-to-total bandwidth. If rule==WEIGHT_FOR_GUARD, we're picking a guard node: consider all guard's bandwidth equally. Otherwise, weight guards proportionally less.
Definition at line 499 of file node_select.c.
References compute_weighted_bandwidths().
Referenced by node_sl_choose_by_bandwidth(). | https://people.torproject.org/~nickm/tor-auto/doxygen/node__select_8c.html | CC-MAIN-2019-39 | refinedweb | 1,199 | 52.36 |
emotion
The Next Generation of CSS-in-JS
Update: This was written for the original version of emotion. Since this article was published we’ve increased performance and removed the babel plugin requirement along with a host of other changes. For an up to date look at emotion check out my article on version 8.
emotion is a high performance, lightweight css-in-js library. The core idea comes from Sunil Pai’s glam library and its philosophy is laid out here. The basic idea is simple. You shouldn’t have to sacrifice runtime performance for good developer experience when writing CSS. emotion minimizes the runtime cost of css-in-js dramatically by parsing your styles with babel and PostCSS. The core runtime is 2.3kb and with React support, 4kb. Total.
First Look
The api will be familiar if you know styled-components. We’ve also taken inspiration from glamorous and css-modules.
const imageBase = css`
width: 32px;
height: 32px;
border-radius: 50%;
`const Avatar = styled.img`
composes: ${imageBase};
border: 2px solid ${p => p.theme.borderColor}
@media(min-width: 420px) {
width: 96px;
height: 96px;
}
`
Benchmarks
This benchmark pushes the libraries by changing a dynamic value in the style block very quickly.
vs. styled-components — emotion is over 25x faster when using highly dynamic prop values at a third of the size.
styled-components warns against using this pattern and instead recommends using inline styles for highly dynamic values. emotion has no such limitations.
vs. glamorous — emotion is up to 2.5x faster on rerender at half the size.
css
import { css } from 'emotion'
css is the ❤️ of emotion. Most of the api, including
styled, are just wrappers around
css.
const imageBase = css`
width: 32px;
height: 32px;
border-radius: 50%;
`
css is a tagged template literal that accepts a standard css text with a few additional features such as nesting, pseudo selectors, and media queries.
css returns a string class name that can be used on any element. For our
imageBase style block above it would be something like
css-imageBase-12345.
To aid with composition
css accepts a special property in the style block called
composes.
With
composes we can use our
imageBase from above to quickly create avatar styles.
const avatarStyle = css`
composes: ${imageBase};
border: 1px solid #7519E5
`
Internally emotion will append these css classes to the generated one.
avatarStyle from above would generate a class name like
css-imageBase-12345 css-avatarStyle-12345 This allows for some really powerful composition that really shines with
styled.
css also accepts object styles 😏
const imageStyles = css({
width: 96,
height: 96
})
object styles are not auto-prefixed.
styled
import styled from 'emotion/react'
styled is a thin wrapper around
css and the supports the same style text and expressions as it does.
styled is modeled almost exactly like styled-components styled function.
const Avatar = styled.img`
width: 32px;
height: 32px;
border-radius: 50%;
`
styled also works as a function call. The first argument can be any html tag or React component that accepts a className prop.
const BigAvatar = styled(Avatar)`
width: 96px;
height: 96px;
`
You can also use another styled component as a selector.
const Heading = styled.img`
font-family: serif;
`const Header = styled.header`
display: flex;
${Heading} {
font-size: 48px;
align-self: flex-end;
}
`
Composes works too
const imageBase = css`
width: 32px;
height: 32px;
border-radius: 50%;
`const Avatar = styled.img`
composes: ${imageBase};
@media(min-width: 420px) {
width: 96px;
height: 96px;
}
`
In
styled, the value of a
composes interpolation can be a function. It is called with the current props on render. It must return an className or object style.
const types = {
success: css`
background: green;
`,
error: css`
background: red;
`,
}const Alert = styled.div`
composes: ${props => types[props.type]};
padding: 10px;
`
Remember css just returns a className so this works.
The true power of composes shines through when used with something like styled-system by Brent Jackson.
Theming
import { ThemeProvider } from 'emotion/react'
Theming is provided by the theming library. The api is laid out in detail here. It is both based on styled-components theming and heavily tested which made it a no brainer.
Whenever you provide a theme to
ThemeProvider any styled component has access to those styles via
props.theme. It does not matter how nested your component is inside
ThemeProvider, you still have access to
props.theme.
const theme = {
white: '#f8f9fa',
purple: '#8c81d8',
gold: '#ffd43b'
}const Avatar = styled.img`
width: 32px;
height: 32px;
border-radius: 50%;
border: 1px solid ${props => props.theme.gold}
`<ThemeProvider theme={theme}>
<Avatar src={avatarUrl}>
hello world
</Avatar>
</ThemeProvider>
Extract Mode vs Inline Mode
The emotion babel plugin defaults to what we call “extract mode”. In this mode, we take all of your css that is defined in each file and extract it to
[filename].emotion.css and automatically import it in the top of your js file. Dynamic values are handled with css variables. The only updates at runtime are just changes to css variables! The disadvantages of extract mode include no ie11 support due to css variables and not being able to extract critical css for server side rendering.
In “inline mode” emotion does something a bit different.
Inline mode uses the CSS Object Model (CSSOM) to manipulate css from javascript. This is how every other css-in-js library out there works. What sets emotion apart is that we can precompile all of your style rules. We don’t have to parse and auto-prefix your styles at runtime because we reduce your styles down to raw insertRule calls.
Inline mode’s biggest advantages are that it works on ie9 and above and it has proper server side rendering support with
extractCritical. There is a great example of this over in the next.js repo
Under the hood
The following example is for inline mode. Extract mode works almost exactly the same.
This code
const H1 = styled.h1`
font-size: 48px;
color: ${props => props.color};
`
Is converted to the following when babel compiles it
const H1 = styled(
'h1',
['css-H1-duiy4a'], // generated class names
[props => props.color], // dynamic values
function createEmotionStyledRules (x0) {
return [`.css-H1-duiy4a { font-size:48px; color:${x0} }`]
}
)
Whenever the render method of
H1 is called:
styledgoes through each dynamic value in your css block. As it iterates through this list, any value that is a function is called and given the current props.
createEmotionStyledRulesis called using the final values from step 1 as arguments. In our example here
x0would be the result of
props => props.color.
- The result of this call is then inserted into emotions StyleSheet shim where it is aggressively cached.
- The generated class names are appended to the component’s
classNameprop.
Take a look at the source of
styled and
css.
Bonus
Keyframes
Animations are supported with the
keyframes function.
css prop
Any component within your application that accepts a
className prop can now accept a
css prop.
const flexCenter = css`
display: flex;
align-items: center;
justify-content: center;`
<div
css={`
composes: ${flexCenter};
width: 128px;
height: 128px;
background-color: #8c81d8;
border-radius: 4px;
img {
width: 96px;
height: 96px;
border-radius: 50%;
transition: all 400ms ease-in-out;
&:hover {
transform: scale(1.2);
}
}
`}
>
The prop behaves exactly like the
css function. The resulting class name is appended to the elements
className prop.
Go write some CSS.
I want to thank Sunil Pai for his guidance, patience, and for trusting in me to carry out his idea. 🙏
Huge thanks to Mitchell Hamilton because without him emotion just wouldn’t work as well. His contributions were invaluable in getting us where we we are now.
Thanks to all the contributors, issue reporters, and early testers!
emotion.sh — website
slack.emotion.sh — slack channel — come say hi! 👋 | https://medium.com/@tkh44/emotion-ad1c45c6d28b?source=---------2------------------ | CC-MAIN-2019-43 | refinedweb | 1,281 | 58.18 |
Build Your First Sourcebit Plugin
Sourcebit is a new, MIT-licensed open source project that aims to make it easy for developers to integrate third-party data sources into their JAMstack site. In my last post, I discussed what Sourcebit is and how to get started using it.
Sourcebit has three types of plugins: source plugins; target plugins; and transformation plugins. A source plugin would connect to an API or data source. Source plugins already exist for Sanity and Contentful. A target handles preparing the content/data output for the static site generator (SSG). Target plugins already exist for Hugo, Jekyll and Next.js. Finally, transformation plugins will transform data pulled from a source before it is output for a target. An assets plugin already exists to download assets and update the links in the data to the local file URL.
All of this works amazingly if you use one of the preexisting plugins, but what if you want to connect to a source that is not yet supported? Or what if you want to support an SSG that doesn't yet have a target plugin? Well, thankfully, Sourcebit is designed to allow you to build your own plugins. You could even get them added to the plugin registry and make them available to any Sourcebit user. In this tutorial, I'll walk you through the steps for building your own plugin.
The Sample Project
Sourcebit does already provide a sample plugin that is well documented to help illustrate the various methods and requirements for building a plugin. However, I'd been experimenting with using the Wordpress API in JAMstack apps, so for this tutorial I thought I would try to build a basic Wordpress API source plugin.
You can find the source for the Wordpress source plugin at. While it has some important limitations that are explained in the README, it is a fully functional plugin that will pull pages, posts and assets from a Wordpress API URL specified by the user during the interactive setup and configuration process.
The plugin utlizes two libraries:
- Node WPAPI helps simplify working with Wordpress API methods within Node.
- Turndown turns HTML into Markdown. This is necessary because the Wordpress API delivers everything from titles to the body in rendered HTML. Note that, while configurable, Turndown can cause a loss in fidelity between the HTML and Markdown.
As you can see in the following video, here I am importing content from a local Wordpress installation to a Hugo site.
Let's see how this was built.
The Two Parts to a Plugin
It's worth thinking of your plugin as consisting of two separate parts: the first part handles collecting information from the user that is necessary to configure the plugin; and the second part is the code that actually performs the plugin action after the configuration is set.
The First Part - Collecting Necessary Information
As mentioned earlier, Sourcebit has an interactive setup and configuration process. Rather than force users to configure it via a YAML configuration file or JavaScript, Sourcebit asks for the necessary information it needs via the command line and then generates a completed configuration file.
For example, in my Wordpress plugin the only configuration needed is to collect the Wordpress REST API URL to connect to. Your plugin may require much more complex configuration and, it's worth noting, the configuration process can be as simple or complex as you need it to be. For instance, the Contentful plugin needs things like API keys, environments and workspaces to know which data to connect to, so it asks multiple questions - some even based upon data from API responses.
There are two methods and one object that define how the configuration information for your plugin is collected and managed: the
options object; the
getOptionsFromSetup method; and the
getSetup method.
You can get more details about each of the below methods in the Sourcebit plugin API documentation.
The
options object
The
options object defines data and configuration options that are available within your plugin. Each key in this object represents the name of a value (i.e. an option) you can use within your plugin code. Each option can include specific keys that define how that option is used and stored. Let's look at an example.
module.exports.options = { wpapiURL: { env: 'WPAPI_URL', private: true }, watch: { default: false, runtimeParameter: 'watch' } };
In the Wordpress plugin, the
wpapiURL is the option that will contain the URL the Wordpress API that we wish to connect to. I have not provided a
default, but I did set the value to
private, which means that Sourcebit will save it to a
.env file rather than the configuration file. This can help prevent users from accidentally committing secret key information to their public repositories. The
env key represents the name of the value within the
.env file.
The
watch option, however, defines a value representing a runtime parameter that can be specified by the user when running via the CLI. I have supplied a default of
false, but this can be overridden via a command line parameter. Most source plugins will include this
watch option as it is how Sourcebit enables live updates to be pulled from the data source (more on that later).
The
getOptionsFromSetup method
The
getOptionsFromSetup method runs when the setup process has finished and is primarily concerned with providing the answers that the user supplied during that process.
In the Wordpress plugin, there is only one answer,
wpapiURL, that needs to be provided.
module.exports.getOptionsFromSetup = ({ answers, debug, getSetupContext, setSetupContext }) => { return { wpapiURL: answers.wpapiURL }; };
The
getSetup method
The
getSetup method is where you'll define the interactive setup process for the user when configuring your plugin. This is where you will ask the questions required to get the configuration information you need from the user and where you can verify any connections your plugin requires before continuing.
The type of questions you may need to ask and the verifications you may need to make will depend largely on what type of plugin you are creating - a source, target or transformation plugin. Sourcebit provides the method with all the tools that it uses to generate the interactive setup process, meaning that you are free to customize this experience as you need to.
- The
chalkvariable contains an instance of the chalk library, which gives each plugin access to an array of text styling options for the CLI. You can reference the chalk library documentation for details on how to use it.
- The
oravariable contains an instance of the ora library, which provides a spinner tool used to inform the user when an action is loading as well as confirmation and error responses. For more information on how to use it, check the ora library documentation.
- The
inquirervariable contains an instance of the inquirer.js library, which provides the interface for the question and answer interaction via the CLI that is integral to the interactive setup process. Each inquirer prompt can contain questions that offer an array of properties to customize the behavior. In addition, inquirer.js provides a number of different built-in prompt types. Inquirer also allows for custom prompt types. For instance, some Sourcebit plugins rely on the inquirer table prompt type to allow for selecting options in a table-like format.
Let's look at an example. For this initial version of the Wordpress plugin, there is only one question: "What is the root URL for your Wordpress API?" This question cannot be left empty and will default to any existing value if the setup was run previously (this is in the
currentOptions variable). Once a user submits the response, we need to verify that the API is available at the URL provided and either show a success or a fail response.
module.exports.getSetup = ({ chalk, context, currentOptions, data, debug, getSetupContext, inquirer, ora, setSetupContext }) => { return async () => { const answers = {}; const { wpapiURL } = await inquirer.prompt([ { type: 'input', name: 'wpapiURL', message: 'What is the root URL for your Wordpress API?', validate: (value) => (value.length > 0 ? true : 'The URL cannot be empty.'), default: currentOptions.wpapiURL } ]); answers.wpapiURL = wpapiURL; const spinner = ora('Verifying space...').start(); try { let site = await WPAPI.discover(answers.wpapiURL); } catch (error) { spacesSpinner.fail(); throw error; } spinner.succeed(); return answers; }; };
Assuming everything succeeds, the user's answers are returned and Sourcebit will continue the setup process for additional plugins.
The Second Part - Pulling and Normalizing Data
Once Sourcebit collects the information from the user during the interactive setup process, it generates a configuration file written in JavaScript. This configuration file supplies the information necessary to allow Sourcebit to collect content and data from the selected data sources. This happens when a
sourcebit fetch is called via the command line or Sourcebit's
fetch() method is called within the application code. In order for this to work, the plugin API provides two methods to pull the data and to normalize it to a format expected by Sourcebit.
However, it is first important to realize two things about these methods and the pulling data:
- Sourcebit also calls both of these methods during the configuration process. This provides details that are used within other aspects of the configuration process. For instance, in order to properly configure a target plugin, Sourcebit needs to know the data models that the source plugin provides. Sourcebit also shows sample entries via the command-line to assist when mapping source content to a target. To do this, Sourcebit gets the data and holds it in memory.
- To help prevent API overuse and even potential charges associated with that, Sourcebit caches data in a
.sourcebit.cache.jsonfile. This cache is written during the
fetchprocess and retrieved from cache prior to subsequent calls. This functionality is enabled by default when
fetchis executed with the
--watchflag, or when
watch: trueis set in the
optionsobject. Alternatively, you can manually enable it with the
--cacheflag or by setting
cache: truein
options.
The
bootstrap method
The
bootstrap method is executed during the configuration process, to get data models and sample data, and when the plugin starts during the fetch process, to pull content and data. As such, it is not required and may not exist for target or transformation plugins but would typically be necessary when creating a source plugin.
This method is also responsible for defining the logic necessary to enable the
--watch flag to pull updated content from the API. This allows Sourcebit to provide the live updating functionality whereby changes made in a CMS are immediately reflected in the site.
The
bootstrap method is provided the following parameters:
logis a function for writing log messages that may be visible by the user depending on their verbosity settings.
debugis a method for writing debug output to the console that are only visible when Sourcebit is being run in debug mode via the
--debugflag.
getPluginContextis a function that gets the content and data available within Sourcebit for this plugin (i.e. entries pulled from the source plugin that may already exist in the cache).
setPluginContextis a function that allows you to overwrite the existing data stored by Sourcebit for this plugin (for example, if an entry was updated).
optionsis an object that contains: _ Configuration values set by the user during setup and stored in the main configuration file. _ Configuration values set by the user but stored in the
.envfile due to their private nature. * Options passed when to
fetcheither via the command line or via code. This includes the
watchflag that indicates that the plugin should watch for continue watching for changes in the source data.
refreshis a function called when changes are made to the data Sourcebit holds, such as when a change is detected during
watch.
Let's look at the
bootstrap method within the Wordpress plugin as an example (I'll explain the code following).
module.exports.bootstrap = async ({ debug, getPluginContext, log, options, refresh, setPluginContext }) => { const context = getPluginContext(); const site = await WPAPI.discover(options.wpapiURL); if (context && context.entries) { log(`Loaded ${context.entries.length} entries from cache`); } else { const posts = await site.posts(); const pages = await site.pages(); const entries = posts.concat(pages); const assets = await site.media(); const fieldnames = ['title', 'content', 'excerpt', 'date', 'slug']; const models = [ { id: 1, source: pkg.name, modelName: 'post', modelLabel: 'Posts', fieldNames: fieldnames, projectId: '', projectEnvironment: '' }, { id: 2, source: pkg.name, modelName: 'page', modelLabel: 'Pages', fieldNames: fieldnames, projectId: '', projectEnvironment: '' } ]; log(`Loaded ${entries.length} entries`); debug('Initial entries: %O', entries); setPluginContext({ assets, entries, models }); } if (options.watch) { setInterval(async () => { const { assets, entries } = getPluginContext(); const posts = await site.posts(); const pages = await site.pages(); const allEntries = posts.concat(pages); const media = await site.media(); let entryUpdateCompleted = false; // Handling updated assets. media.forEach((asset) => { const index = assets.findIndex((item) => item.id === asset.id); if (index !== -1) { let newUpdateDate = new Date(asset.modified); let lastUpdateDate = new Date(assets[index].modified); if (newUpdateDate > lastUpdateDate) { assets[index] = asset; entryUpdateCompleted = true; } } }); // handling entry updates allEntries.forEach((entry) => { const index = entries.findIndex((item) => item.id === entry.id); if (index !== -1) { let newUpdateDate = new Date(entry.modified); let lastUpdateDate = new Date(entries[index].modified); if (newUpdateDate > lastUpdateDate) { entries[index] = entry; entryUpdateCompleted = true; } } }); if (entryUpdateCompleted) { setPluginContext({ assets, entries }); refresh(); log(`Updated entries`); } }, 3000); } };
The function begins by getting any data Sourcebit already has in cache via the
getPluginContext function. Next, it gets the information for the Wordpress site from the API using the API URL provided during the configuration process. If entries exist in the cache, those entries are used and the code to get data from the API isn't run.
If entries do not exist, the relevant Wordpress APIs are called to get posts, pages and assets (or media, as Wordpress calls them). Pages and posts both represent entries from a Sourcebit perspective, so they are combined into one array while assets remain separate. In this example plugin, the properties available in entry (i.e.
fieldnames) and the models are all manually created. In other sources this information may come from the API, however models should conform to a specific data structure. The models, entries and assets are then stored by Sourcebit using the
setPluginContext function.
If the
watch flag is enabled, we use
setInterval to poll the API. The Wordpress API doesn't provide a means (that I am aware of, anyway) for checking if changes have been made as is provided by many headless CMS. Thus, the code loops through all the retrieved posts, pages and media and compares the last updated date with the record in the cache. If the API record is newer, it is overwritten in the cache using
setPluginContext and
refresh is called.
The
transform method
The
transform method is called after the
bootstrap method and is all about normalizing data. Sourcebit expects entries and assets to have certain baseline properties, but they can also contain any relevant data needed from the API (for example, data that might be converted to frontmatter properties). The
transform method is where a transformation plugin might modify data in one of the core data buckets of files, models or objects. It is also where a target plugin might write files and save them to pass them to the files data bucket.
Let's look at the example in the Wordpress plugin.
module.exports.transform = ({ data, debug, getPluginContext, log, options }) => { const { assets, entries, models } = getPluginContext(); const normalizedPosts = entries.map((entry) => { const normalizedEntry = { source: pkg.name, id: entry.id, modelName: entry.type, modelLabel: entry.type.charAt(0).toUpperCase() + entry.type.slice(1) + 's', projectId: '', projectEnvironment: '', createdAt: entry.date, updatedAt: entry.modified }; return { title: turndownService.turndown(entry.title.rendered), content: entry.content.rendered, excerpt: turndownService.turndown(entry.content.rendered), date: entry.date, slug: entry.slug, __metadata: normalizedEntry }; }); const normalizedAssets = assets.map((asset) => { const normalizedEntry = { source: pkg.name, id: asset.id, modelName: '__asset', modelLabel: 'Assets', projectId: '', projectEnvironment: '', createdAt: asset.date, updatedAt: asset.modified }; return { title: turndownService.turndown(asset.title.rendered), contentType: asset.mime_type, fileName: asset.media_details.sizes.full.file, url: asset.media_details.sizes.full.source_url, __metadata: normalizedEntry }; }); const normalizedEntries = normalizedPosts.concat(normalizedAssets); return { ...data, models: data.models.concat(models), objects: data.objects.concat(normalizedEntries) }; };
While there are quite a few lines of code, as you can see it is primarily taking data received from the Wordpress API and putting it into data structures required for either assets or entries by Sourcebit. Both assets and entries are stored in the
objects data bucket, so they are combined after normalization and the data object is returned.
Testing a Plugin
Now that we've finished writing our plugin, how can we test it locally? Sourcebit provides a way of adding a local plugin to be used when running the interactive setup process. First, we need to create a JSON file that contains an array of objects representing the local plugin modules that we'd like to use. For example, the JSON to load my Wordpress on my local machine would be:
[ { module: '/Users/brianrinaldi/Documents/projects/sourcebit-source-wordpress', description: 'A Sourcebit plugin for Wordpress', author: 'Brian Rinaldi', type: 'source' } ];
The
module is the local file path to the plugin. The
description and
author are both shown in the interactive setup process when choosing plugins to install. The
type is either a
source,
target or
transform depending on what kind of plugin you are creating.
Once this file is created, the plugin can be tested by providing a
--plugins option to
npx create-sourcebit where the value of
plugins is the relative path to the JSON file created above.
npx create-sourcebit --plugins=./plugins.json
It is worth noting that the plugin runs off the local source and does not actually "install" in the current project. This means that any changes made will be immediately reflected.
After running through the configuration process, you may want to run the
fetch process with debugging enabled. To do so, provide the plugin's namespace (defined in the plugin's
package.json) to the
DEBUG environment variable. For example, to run the Wordpress plugin with debugging enabled I would run:
DEBUG=plugin:sourcebit-source-wordpress sourcebit fetch
For more details on debugging check the documentation.
Registering a Plugin
So you've created an awesome plugin and you want to share it with the community. While users can download the plugin and run it locally as shown above, it'd be better if it was a default option within the interactive setup process. This is done by adding your plugin to Sourcebit's plugin registry.
The plugin registry requires the same information shown in the JSON file above. One important note is that the plugin namespace should follow the pattern used by other plugins such as
sourcebit-source-contentful,
sourcebit-transform-assets or
sourcebit-target-hugo. The namespace should start with
sourcebit then describe the type of plugin (source, transform or target) and finally what the plugin handles (for example, Contentful content, site assets or the Hugo static site generator).
When you think the plugin is ready, you can add it to the registry file and submit a pull request.
We Can't Wait to See What You Create!
The JAMstack ecosystem has so many amazing options for developers. There are countless headless CMS for content, data stores or APIs for data, and numerous SSGs. That's why Sourcebit was designed to be extensible - so that the community could expand the capabilities of the tool to support whatever SSG, CMS or data source they use or love. Hopefully this tutorial gives you the guidance you need to create your own plugin and share it with the JAMstack community. Sourcebit is a fully-extensible open source project that can connect any data source with a JAMstack site. In this post, we'll learn how you can build a plugin to connect to a data source, target SSG or transform data. | https://www.stackbit.com/blog/sourcebit-plugin/ | CC-MAIN-2022-05 | refinedweb | 3,292 | 55.84 |
24 October 2008 09:59 [Source: ICIS news]
SHANGHAI (ICIS news)--?xml:namespace>
“The new trading products include polyvinyl chloride (PVC) and polypropylene (PP), and DCE will try its best to perfect the futures trading system of chemical products,” the manager of DCE, Liu Xingqiang, said in Mandarin.
“We have not decided when to start the futures trading of these two products, because it needs to be approved by the China Securities Regulatory Commission,” he added.
DCE currently operates futures trading for just one chemical product: linear low density PE (LLDPE), said the DCE official.
DCE, founded in 1993, is one of four futures exchanges | http://www.icis.com/Articles/2008/10/24/9166016/chinas-dalian-bourse-to-trade-more-chemicals.html | CC-MAIN-2014-41 | refinedweb | 105 | 59.23 |
If it takes a thread that long to obtain a lock, it's because someone else is currently holding it.
You should look for two things:
Code blocks which synchronize on the same object or on other references to it (known as synchronized statements) :
synchronized (obj) {
...
}
Synchronized methods within the object itself.
Say obj is of type MyObject, then you should look for methods such as these:
public class MyObject{
public synchronized void myMethod() {
...
}
}
Because they are essentially the same as
public void myMethod() {
synchronized (this) {
...
}
}
So if a thread is executing obj.myMethod(), threads that want to enter a synchronized (obj) will have to wait since they lock on the same object. This, by the way, is the reason why I strongly recommend never using the synchronized method syntax, and always locking over a private (or protected) class member.
If another thread is currently executing code within such a block, the current thread will be locked out until the other thread finishes.
Total Post:28Points:196
Android Android Thread
Ratings:
490 View(s)
Rate this: | https://www.mindstick.com/forum/33649/why-does-it-seem-to-take-a-long-time-for-this-synchronized-block-to-get-a-lock | CC-MAIN-2017-39 | refinedweb | 176 | 62.58 |
Gaurav Sharma here, I’m a developer with the Information Security Tools team.
Today I want to share something about FCL’s GetHashCode method. System.Object provides a virtual GetHashCode method so that an Int32 hash code can be obtained for any and all objects.
Below is a code snippet which takes a string and generates a hash code out of it. Code goes like this:
using System;using System.Collections.Generic;using System.Text;namespace HashCodeSample{class Program{static void Main(string[] args){String message = "Hello from gaurav";Console.WriteLine(String.Format("Hash is {0}", message.GetHashCode()));Console.Read();}}}
By definition, a hash is a value that summarizes a larger piece of data and can be used to verify that the data has not been modified since the hash was generated. So for a specific piece of data we will get identical hash every time we execute a specific hash function.
But strangely, this definition do not hold true for Object.GetHashCode method defined in FCL. I ran above code sample in VS 2003 and VS 2010 and got different outputs
Result with VS2003 [–868154745]
Result with VS2010 [2020441803]
After digging deep into the MSDN for GetHashCode I got my answer-.
So, whenever we want to make use of hashing in our application we should always strive to use specific hashing algorithm types that are defined in FCL. Below is a class diagram showing available hash types.
Now my Tip of the Day for writing better code with Visual Studio:
Everyone uses Console.Writeline() method and visual studio provides a shortcut for typing this statement :).
Type cw and press TAB 2 times, you will get the statement. This feature is known as code snippets. Some of the snippets that I have in my mind right now are:
- Type ctor and 2 times TAB for CONSTRUCTOR
- Type switch and 2 times TAB for switch block. (if you have your VS open right now, just use this switch on a object of Enum type. You will be surprised how clever VS actually is)
- Type try and 2 times TAB for try catch block
There are lot of shortcuts available in VS that makes writing code fun.
Happy Coding!
Thank You for sharing the code. Didn’t worked the 1st time. Now its working. 🙂 | https://blogs.msdn.microsoft.com/securitytools/2009/08/01/object-gethashcode/ | CC-MAIN-2017-09 | refinedweb | 382 | 64.81 |
progress update stream which is an AWS resource used for access control as well as a namespace for migration task names that is implicitly linked to your AWS account. It must uniquely identify the migration tool as it is used for all updates made by the tool; however, it does not need to be unique for each AWS account because it is scoped to the AWS account.
See also: AWS API Documentation
See 'aws help' for descriptions of global parameters.
create-progress-update-stream --progress-update-stream-name <value> [--dry-run | --no-dry-run] [--cli-input-json <value>] [--generate-cli-skeleton <value>]
--progress-update-stream-name (string)
The name of the ProgressUpdateStream. Do not store personal data in this field.
--dry-run | --no-dry-run (boolean)
Optional boolean flag to indicate whether any effect should take place. Used to test if the caller has permission to make. | https://docs.aws.amazon.com/cli/latest/reference/mgh/create-progress-update-stream.html | CC-MAIN-2020-24 | refinedweb | 147 | 52.9 |
Anyone not be in 4.5. Many folks who have asked for this feature have a pre-set list of sub-features in mind that of course will be supported by ReJIT, they think. But many of those obvious sub-features will not be available in .NET 4.5. That’s what this post is about.
If you’re writing a monitoring tool, typically run in production, and…
If your tool is always on, always monitoring, but needs a way to fine-tune the amount of instrumentation it does without forcing the monitored application to restart, and…
If your tool instruments potentially everything, including framework assemblies like mscorlib, and you therefore disable the use of NGENd images and are willing to put up with longer startup times as a result, then…
ReJIT may be for you.
The ReJIT we plan to release in .NET 4.5 was designed with this scenario in mind. As such, there are many potential sub-features of ReJIT that will not be available, because they are not essential for this scenario.
ReJIT + Attach? No!
In order to enable ReJIT, your profiler must load at startup, and set an immutable flag in your Initialize method that enables the ReJIT functionality.
ReJIT + NGEN? No!.
Metadata changes in ModuleLoadFinished only.
Memory reclaimed at AppDomain unload, not revert.
ReJIT inlined functions? No!.
ReJIT + managed debugging? No!
While not technically disabled, it is not advised or supported to run a managed debugger against a process that also has a ReJITting profiler enabled. (Native-only debugging is just fine, though.)
Whatever debugging support there is, is only there for you, the profiler writer, and not.
ReJIT dynamic code? No!
Not a new limitation, but just to be explicit, profilers are not allowed to instrument dynamic code generated via the Reflection.Emit namespace, and that includes ReJIT.
ReJIT, as originally conceived by the CLR team, involved allowing profilers to attach to running processes and then instrument arbitrary code at any time. Just that one sentence would eliminate almost all the restrictions mentioned above. So what happened?
Reality, that’s what.
Stuff takes time. And in this case a lot. | http://blogs.msdn.com/b/davbr/archive/2011/10/10/rejit-limitations-in-net-4-5.aspx | CC-MAIN-2015-11 | refinedweb | 357 | 57.47 |
What do you mean by generate credentials?? AWS comes with a feature called
IAM, identity and access management, just have a look, I hope you are
looking for the similar service,one can access the ses account using ses
api or smtp settings..
You can reuse your current certificate. You need you private key file,
certificate file, and if needed a certificate chain file. What you need to
do to set it up depends on your web server. It should be relatively easy to
set it up.
I noticed on this quickstart guide it says that you should have the
namespace as "xmlns:Amazon="""
I looked in the sample provided in the sdk and for their namespace they
didn't use their package name but instead:
"xmlns:Amazon="""
That first statement is not correct. In the quickstart guide it actually
says that the namespace should be:
xmlns:Amazon="<type your package
name>"
Note the last part. That's important, because that's exactly the difference
you're basing this question on.
As with any custom view on Android, if you want to use one or more
attributes that aren't covered by the Android namespace, you have to
declare their location first.
The Boto EC2 documentation here describes the EC2 instance object, of which
"key_pair" is an attribute. Look about 3/4 of the way down, under
"boto.ec2.instance".
So, e.g., you could run some instances as follows, and then store the first
instance as "inst":
reservation = conn.run_instances(...)
inst = reservation.instances[0]
To retrieve your key-pair name as a unicode string, just use:
kp_name = inst.key_name
You can then retrieve the corresponding Boto object using get_key_pair:
kp_obj = conn.get_key_pair(kp_name)
Of course, this is a silly example, since I would have needed my key pair
name to run_instances in the first place. May you find a more fruitful
application!
Please have a look at this blog for installing a IDE on an Amazon EC2
machine that you can then VNC remote desktop into.
Amazon EC2 does not come with X11 or other graphical support by default,
but it's quite easy to install.
If you head to your S3 interface on the AWS backend, and click on the
bucket--the left pane will show some tabs associated with the bucket.
Click on the Static Web Hosting tab and you'll be able to see your
"Endpoint" address which will look something like the URL you said
above...That will be the Amazon S3 URL you're using
I think that is what you are looking for:
More details about the limitations:
But you need a valid credit card...
You can use Shopelia SDK which enables in-app purchase of physical goods
using one click payment. It is available for Amazon but also for any kind
of retailers.
It works using a combinaison of automation and monetics to inject the order
and process the payment.
Right now (October 2013), the product is in beta stage and can be
demonstrated on Shopelia website
Integration is available through SDK for Android and iOS.
Disclaimer : I'm co-founder of Shopelia. Please contact me if you are
interested to integrate the technology in your app.
All dependes on your web application load... you can start with an EC2
micro-instance, an 30GB EBS with mysql+apache installed and an Elastc IP,
all this will be under free tier, so you can taste aws server and measure
your real needs.
By the way, there is a lot of things which you can go under free tier, take
a look:
This is permission problem to access python file. When you running it
through server python script access as apache user(most probably www-data).
So apache user doesn't having privilege to execute the python file.
What you can do it is run this command as sudo and add all necessary access
to apache user(www-data) in /etc/sudoers file as below sample.
www-data ALL=NOPASSWD:/var/www/similarity.py
www-data ALL=NOPASSWD:/usr/bin/python
This is just the sample, you should change this line as according to your
environment.
IE9 uses the XDomainRequest object to make CORS requests, which is a
limited version of the XMLHttpRequest object used by other browsers. An
overview of the XDomainRequest object can be found here:
Look specifically at item #3, which states: "No custom headers may be added
to the request". By looking at your configuration, it looks like you expect
an Authorization header. This is not allowed in IE9. (Although to be
absolutely sure, it would be helpful to see an example of how you are
making the request).
Also note if you are not doing so already, you should use the
XDomainRequest for IE8/9. This article provides an example of how to pick
the correct object:().
Just found out.
We were sending the emails from email address "A" and setting a reply-to to
All bounce notifications are sent to the reply-to address... once we setup
SNS/SQS notifications to the reply-to address, notifications started
flowing.
SQS guarantees that the message will be delivered at least once. They make
no assurance that it won't be delivered a whole bunch of times. SQS is
really neat in that it scales, but you actually pick up some odd behaviors
due to how they made it scale, like this and messages being delivered out
of order that make it a little bit of a hassle for projects that don't
really need scale.
There are multiple ways to host a webserver in front and redirect requests
to multiple tomcat servers in backend. Assuming you have webserver and
multiple tomcat servers deployed over a EC2 and tomcat. Using ajp or
mod_proxy or mod_jk, you can redirect requests hitting on your webserver to
your backend tomcat servers.
By default, AWS does not provide cookie or session management. You can use
AWS Elasticache for session management.
Yes, you can upload your images and other static content on Amazon S3 and
deliver it from S3 itself or using CloudFront (CDN) while your dynamic
requests are coming to your tomcat servers.
Your questions was too broad. If you provide more details, we can help
more.
Thanks
Sanket
The same thing happened to me. The xml design editor is supposed to show
you how your layout will look. Try emulating your app or connect it to an
actual device. it should still work. For the layout with the ad-view,you
will always have the rendering problems, though.
If you haven't already done so, you can configure your production bucket to
keep a log of all the requests made against it, similar to an Apache or
other web server access log.
Once you have logging enabled, you will be able to find out the URL of the
request, who requested it and when it was requested.
Update:
If an AccessDenied error is returned when trying to access the S3 server
log files through the API or the AWS console, the problem is caused by
missing permissions (ACLs) on the log files.
To access those log files, the Open/Download permission should be granted
for the user that owns them. Having a bucket policy with public read
enabled is not enough to get access to the server log files.
More details on the is
A couple of quick points;
Set the environment up exactly like it's supposed to run. If there's a
database involved, you'll want to involve that in the testing too.
Synthetic <?php echo "ok"; CPU based benchmarks won't help you much
since normally very little of the time spent replying to HTTP requests is
actual CPU time.
A recommendation is to use a service for the benchmarking. Setting load
testing up is not without its complexities, and unless you consider
benchmarking your core business, you're probably better off using something
like Neustar to load and measure your site (there are many services,
they're not necessarily what fits you best, just pulled one out of memory)
Of course you can set a load test up yourself, but getting that done right
is not anything that can be describ
You can change it or not. When you define your product in the Amazon
developer portal you will have the ability to define the IAP items for the
app. For each IAP item you have to define multiple properties one of
which is the sku. What matters is that the sku string in the portal match
the request you make from the app. Other properties include price,
description, title, and various associated images.
I don't think you quite understood the documentation or the examples. You
need a server side component to sign the requests that Fine Uploader sends.
It looks like you are pointing Fine Uploader at a JSON file, for some
reason. I'm guessing you copied the example signature file from the blog
post and are pointing Fine Uploader at that? The example signature file
was detailed in the blog post to give you some insight into how Fine
Uploader S3 generates the policy document for simple uploads for you. You
don't need to store a copy of this anywhere.
You need a proper server side component to sign the requests Fine Uploader
sends to S3, at the very least. There are already 5 fully functional
server side examples for Fine Uploader S3 in. In
I ended up just installing numpy through yum, sudo yum install numpy. I
guess this is the best I can do for now. When working with virtualenv and I
need numpy, I will tell it to use site packages.
Thanks for the suggestion @Robert.
Your problem is most likely in your StringToSign function. It should look
somewhat like this:
StringToSign := 'POST'+ chr(13)+
AmazonMWShost + chr(13) +
'/'+ APIurl + chr(13) +
URLencodedParameters;
Where AmazonMWShost is mws.amazonservices.com for US merchants. APIurl is
an empty string for the Report API and Orders/2011-01-01 for the Order API.
Did you check the Queue Policy? When you create it, by default it has no
policy and only the owner is able to use it.
Check the IAM user you are using with the API and make sure you have the
policy on the SQS granting rights to him.
I have used SNS in the past to deliver around 1.5MM notifications each
month and I had no problems. But I have no proven track record or
experience at the rate you need. But I suggest you to take a look at the
following article
which talks a little bit about SNS x GCM.
Hope this helps.
First you need to set an ElasticIP for associated to that instance.
Then point the DNS entry of "www" for "my-domain-name.com" to the IP
assigned in the step above.
Where you manage your DNS is another thing, can be in GoDaddy or in AWS
Route53. You must adjust the delegation DNS in the "my-domain-name.com"
register. Ex: your domain can be registered with GoDaddy but its delegation
DNS point to Route53 so you can manage the domain from your AWS Console.
I see two options:
You could use CloudFlare instead of CloudFront. They provide CDN
functionality for free.
If you don't use S3 to serve images, but do it from your servers, you could
use different provider. For instance Linode has DC in Tokyo, where 4 GB
($80) gives you 8 TB transfer. Another one is vps.net - 1 GB instance ($40)
gives you 6 TB of transfer. You can also play a bit with Cloudorado to find
something for you.
I don't think there is a call that does what you want. There is a call that
does the opposite, if that is of any help: GetMatchingProductFromId will
return the ASIN for a given EAN or UPC. Why the result from this call (and
from GetMatchingProduct) does not return EANs etc. is beyond me.
If you already have items listed through MWS, the
_GET_MERCHANT_LISTINGS_DATA_ report might help
You need to assign File or InputStream property of PutObjectRequest object.
The code fragment should look like this one:
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey,
secretKey))
{
var stream = new System.IO.MemoryStream();
originalBMP.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
PutObjectRequest request = new PutObjectRequest();
request.InputStream = stream;
request.BucketName="MyBucket";
request.CannedACL = S3CannedACL.PublicRead;
request.Key = "images/" + filename;
S3Response response = client.PutObject(request);
After
require_once( "AWSSDKforPHP/aws.phar" );
reset the autoloader back to spl_autoload, and add the AWS autoloader using
spl_autoload_register
require_once( "AWSSDKforPHP/aws.phar" );
__autoload('spl_autoload');
spl_autoload_register(/* whatever you find AWS registers */);
ContentType and ContentEncoding should not be sent as metadata. Use this
instead:
$objS3->putObject(array(
'Bucket' => $sBucket
'Key' => $sBucketFolder . $sFilenameToSave,
'SourceFile' => $sFile,
'ACL' => 'public-read',
'ContentType' => 'text/css',
'ContentEncoding' => 'gzip'
));
Would you be willing to consider an alternative:
class S3 extends AmazonS3Client
{final String bucket;
S3(String u, String p, String Bucket)
{super(new BasicAWSCredentials(u, p));
bucket = Bucket;
}
boolean put(String k, String v)
{try
{final ByteArrayInputStream b = new
ByteArrayInputStream(v.toString().getBytes());
putObject(bucket, k, b, new ObjectMetadata());
setObjectAcl(bucket, k, CannedAccessControlList.PublicRead);
// Has to be here to allow change to reduced redundancy
changeObjectStorageClass(bucket, k,
StorageClass.ReducedRedundancy);
setObjectAcl(bucket, k, CannedAccessControlList.PublicRead);
// Has to be repeated beca. | http://www.w3hello.com/questions/How-is-Amazon-Lightsail-cheaper-than-Amazon-EC2-closed- | CC-MAIN-2018-17 | refinedweb | 2,223 | 63.7 |
Operating systems, development tools, and professional services
for connected embedded systems
for connected embedded systems
putwc()
Write a wide character to a stream
Synopsis:
#include <wchar.h> wint_t putwc( wchar_t wc, FILE * fp );
Arguments:
- wc
- The wide character that you want to write.
- fp
- The stream that you want to write the wide character on.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The putwc() functions writes the wide character specified by wc, cast as (wint_t)(wchar_t), to the output stream specified by fp.
Returns:
The wide character written, cast as (wint_t)(wchar_t), or WEOF if an error occurs (errno is set).
Errors:
- EAGAIN
- The O_NONBLOCK flag is set for fp and would have been blocked by this operation.
- EBADF
- The file descriptor:
See also:
errno, getwc(), getwchar(), putwchar() | http://www.qnx.com/developers/docs/6.4.0/neutrino/lib_ref/p/putwc.html | crawl-003 | refinedweb | 142 | 64.3 |
Bootstrap your Container-Based Azure Function
This blog builds on this Azure docs document, but starts with my own code rather than a pre-canned solution. The solution is simple: it's a function app with a single function that is triggered by event hub content. But it's enough to demonstrate how to create a new container-based function app using the new (in preview) functions runtime v2.
Full disclosure: this blog was written in April of 2018. I used Visual Studio 2017 to prototype the function. I used an Azure-based Ubuntu 17.10 VM as my test bed.
Start by creating a new Azure Functions Function App:
Leave off the offered triggers but browse for a storage account or create one. All Azure Functions need a storage account to store their own state. Be sure you select the v2 runtime.
Right-click the project (in my case FunctionApp1) and Add a New Azure Function.
Then select the event hub trigger and add some configuration details:
Note that the "Connection string setting" isn't the actual connection string. It's a pointer to the actual setting that's going to be in the local.settings.json file for VS tests and in an environment variable for the Docker container. The Event Hub name (insights-operational-logs) that I selected is the name of the hub that receives Azure Activity Log telemetry if the Activity Log has a diagnostics profile defined that sends Activity Log telemetry to an event hub.
Add the Connection String Setting to local.settings.json:
Hit F5 to test. You should see telemetry pouring out of the event hub. If not, check that the hub exists. This is a good indicator that there is a correctly configured diagnostics profile. The hub is created in the hub namespace automatically when telemetry starts to flow.
Next task: let's get this into a Docker container. At this point, I committed my code and then cloned it in my Linux VM. In my actual test environment, this is what it looks like (only the names are different – the structure is identical. Rather than 'goliveHubConnectionString', I used 'goliveEhConnection'.)
I added Dockerfile out of band, and here it is:
This requires some explanation. The FROM designates an alpha release of the Azure Functions v2 runtime. Follow the image here and upgrade to GA when it's available. The ENV values for AzureWebJobsStorage and AzureWebJobsDashboard are required for the function to operate. And the ENV's have semicolon's ( ; ) embedded. Note that the semicolons must be quoted with a backslash (e.g. \; ). The COPY line gets the results of my dotnet publish step. Here's how that is done:
Next step is the Docker build:
And then docker run it:
- docker run -p 8080:80 –rm -it funcv2
You should see telemetry streaming to the console just as you did when testing in Visual Studio.
Cheers! | https://docs.microsoft.com/en-us/archive/blogs/golive/bootstrap-your-container-based-azure-function | CC-MAIN-2020-50 | refinedweb | 485 | 65.73 |
Getting up and running with your first Ionic 2 app using the Ionic CLI is super simple for anyone with web development experience. As this post will show, you can get started very quickly and have a “Hello World” app within ten minutes.
Using just a couple commands on the CLI, you can have a starting template and be well on your way to having your app on Shark Tank.
Installing Ionic
The first thing you’ll want to do, if you haven’t already, is to install the Ionic 2 CLI, using the installation guide. After installing node, you’ll use NPM to install
ionic@beta.
npm install -g ionic@beta
Creating your First App
Using the CLI, wherever we want to create our app, we will run the
ionic start command to create an app called
helloWorld, using the
blank template.
ionic start helloWorld blank --v2 --ts
This will create a bunch of plumbing for you, including your first
@Page of your app, inside
app/pages/home, which will include the following files:
- home.html: The template for your page
- home.ts: The TypeScript for your page, where the
@Pagecomponent is defined
- home.scss: a file to put any custom SASS styles for this page
Modifying a Page
Let’s modify the template (home.html) to just say “Hello World” in the navbar, and in the content, we will have the text say “Hello Andrew,” where “Andrew” will be a variable passed from our
@Page component. By default, we’ve been given something like this:
<ion-navbar *navbar> <ion-title> Home </ion-title> </ion-navbar> <ion-content <ion-card> <ion-card-header> Card Header </ion-card-header> <ion-card-content> Hello World </ion-card-content> </ion-card> </ion-content>
First, we’ll modify our
ion-title to contain “Hello World”.
<ion-title> Hello World </ion-title>
Next, let’s modify our
ion-content to contain our hello text and bind a
name variable that we will pass from our
@Page.
<ion-content <ion-card> <ion-card-content> Hello {{name}} </ion-card-content> </ion-card> </ion-content>
Finally, we’ll modify our
@Page (home.ts) to assign a value to
name. By default, we’ve been given something like this:
import {Page} from 'ionic-angular'; @Page({ templateUrl: 'build/pages/home/home.html' }) export class HomePage {}
Let’s add a constructor and assign a value to
this.name which will be bound to our template.
import {Page} from 'ionic-angular'; @Page({ templateUrl: 'build/pages/home/home.html' }) export class HomePage { public name; constructor(){ this.name = "Andrew"; } }
Serve
Next, in the CLI, we’ll run
ionic serve to view our app in the browser:
ionic serve
You should end up with something similar to the following in your browser:
Conclusion
In under ten minutes, you can be up and running with Ionic version 2, using the CLI. In that short amount of time, we have the basic building blocks of your next big app! | https://blog.ionic.io/10-minutes-with-ionic-2-hello-world/ | CC-MAIN-2017-47 | refinedweb | 493 | 59.94 |
30 September 2010 18:29 [Source: ICIS news]
TORONTO (ICIS)--Chemical shipments on US railroads rose 8.9% last week from the same period in 2009, a rail industry group said on Thursday, marking their 37th increase so far this year.
Chemical railcar loadings for the week ended 25 September were 29,038, up by 2,370 carloads from 26,668 in the same week last year, according to the Association of American Railroads (AAR).
The increase compared with a 5.3% increase in the previous week ended 18 September 10.7% year-over-year increase in overall weekly railcar shipments for the 19 high-volume freight commodity groups tracked by the ?xml:namespace> | http://www.icis.com/Articles/2010/09/30/9397786/us-weekly-chemical-railcar-traffic-rises-8.9-year-over-year.html | CC-MAIN-2014-52 | refinedweb | 114 | 62.68 |
On Thu, 2004-12-16 at 16:48, Greg KH wrote:Thanks for your help. Comments and more questions inline. > On Thu, Dec 16, 2004 at 04:37:34PM -0600, Kylene Hall wrote:> > +config TCG_TPM> > + tristate "TPM Hardware Support"> > + depends on EXPERIMENTAL> > + ---help---> > + If you have a TPM security chip in your system, which> > + implements the Trusted Computing Group's specification,> > + say Yes and it will be accessible from within Linux. To > > + compile this driver as a module, choose M here; the module > > + will be called tpm. For more information see > > +. A implementation of the > > + Trusted Software Stack (TSS), the userspace enablement piece > > + of the specification, can be obtained at > > +> > + If unsure, say N.> > What happened to the "if built as a module..> ." text?It is there in the middle of the paragraph. I moved it to the end ofthe paragraph to make it easier to find in the future.> > > +> > +config TCG_NSC> > + tristate "National Semiconductor TPM Interface"> > + depends on TCG_TPM> > +> > +config TCG_ATMEL> > + tristate "Atmel TPM Interface"> > + depends on TCG_TPM> > Please provide help text for these options.Added.> > > +/*> > + * Vendor specific TPMs will have a unique name and probe function.> > + * Those fields should be populated prior to calling this function in> > + * tpm_<specific>.c's module init function.> > + */> > +int register_tpm_driver(struct pci_driver *drv)> > +{> > + drv->id_table = tpm_pci_tbl;> > + drv->remove = __devexit_p(tpm_remove);> > + drv->suspend = tpm_pm_suspend;> > + drv->resume = tpm_pm_resume;> > +> > + return pci_register_driver(drv);> > +}> > +> > +EXPORT_SYMBOL(register_tpm_driver);> > Why not EXPORT_SYMBOL_GPL()? Based on the content of these drivers, I'd> feel better if they all were that way, but that's just me :)> Actually, why even have this function at all? It's not needed, just> export the suspend, resume, and remove functions, and you are set.> All fixed.> Also, don't say that other drivers really support the other pci devices,> when they do not. The MODULE_DEVICE_TABLE() stuff needs to be in the> driver that actually supports that hardware. Otherwise all of the> hotplug functionality will not work properly.> So the problem we have is that the chip does not have a unique id and weare just having to rely on the id of the chipset that the lpc bus is ontherefore either chip (NSC or Atmel, etc.) could claim any of these ids.Do you have a better suggestion so we can get away from maintaining thislist? Also, in my latest version this table has been moved to theheader inorder to move to static initialization of the struct pci_driveras Chris suggested.> > +> > +void unregister_tpm_driver(struct pci_driver *drv)> > +{> > + pci_unregister_driver(drv);> > +}> > +> > +EXPORT_SYMBOL(unregister_tpm_driver);> > Um, why even have such a function?> Fixed.> > > +EXPORT_SYMBOL(register_tpm_hardware);> > EXPORT_SYMBOL_GPL() (same goes for all of these exported symbols...)> Fixed.> > diff -uprN linux-2.6.9/drivers/char/tpm.h linux-2.6.9-tpm/drivers/char/tpm.h> > --- linux-2.6.9/drivers/char/tpm.h 1969-12-31 18:00:00.000000000 -0600> > +++ linux-2.6.9-tpm/drivers/char/tpm.h 2004-12-16 17:16:50.000000000 -0600> > +extern void tpm_time_expired(unsigned long);> > +extern int rdx(int);> > +extern void wrx(int, int);> > Please use better names for these functions. That's very cryptic for a> global symbol.Fixed.> > > +extern int lpc_bus_init(struct pci_dev *, u16);> > No "tpm"?> Fixed.> > +extern int register_tpm_driver(struct pci_driver *);> > +extern void unregister_tpm_driver(struct pci_driver *);> > +extern int register_tpm_hardware(struct pci_dev *, struct tpm_chip_ops *,> > + u16);> > Try putting "tpm" first here, for these functions, so the namespace is sane.> Fixed.> thanks,> > greg k-h> Thanks,Kylene> > -------------------------------------------------------> SF email is sponsored by - The IT Product Guide> Read honest & candid reviews on hundreds of IT Products from real users.> Discover which products truly live up to the hype. Start reading now. >> _______________________________________________> tpmdd-devel mailing list> tpmdd-devel@lists.sourceforge.net>> -To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2004/12/17/166 | CC-MAIN-2018-47 | refinedweb | 633 | 57.37 |
Customizing the 2007 Office Fluent Ribbon for Developers (Part 1 of 3)
Summary:.
extensibility markup looks like this:
This markup tells Office to call the MyButtonOnAction method when the button is clicked. The MyButtonOnAction method has a specific signature depending on your choice of languages; here is an example:
The MyButtonOnAction procedure must be declared as public. The control parameter carries the unique id and tag properties of the control, which enables you to use the same callback procedure for multiple controls.
Applications that support the Ribbon (except Access 2007, as described Creating an Access Application-Level Custom Ribbon) extensibility markup must include one of the following identifiers.
General Format of XML Markup Files=.
..
Customizing the Fluent UI by Using Office Open XML Formats Files.
To customize the Fluent UI by using Office Open XML Formats files extensibility commands and controls...
Save the document as a macro-enabled workbook with the file name extension .xlsm.
Exit Excel.
To create the file that contains the XML markup to modify the Fluent UI>
To modify files contained in the macro-enabled file container.
Open the new folder, and then open the .rels file in a text editor.
Add the following text between the last <Relationship> element and the </Relationships> element, and then save and close the file..
Click Large Button. Clicking the button triggers the onAction callback, which calls the macro in the workbook, which displays the "Hello World" message.
Customizing the Fluent UI with COM Add-Ins.
To customize the Fluent UI by using COM add-ins extensibility.
Customizing the Fluent UI in Access Loading Customizations at Run Time.
The following procedure describes, in a generalized manner, how to add application-level customizations in Access. A later section includes a complete walkthrough.
To apply a customized application-level Ribbon at design time.
To assign a specific custom Ribbon to a form or report.
To explore this process further, work through the following examples.
The first part of the example sets an option that reports any errors that exist when you load custom UI (although you are performing these steps in Access, you can perform similar steps in other applications).
To create an Access application-level custom ribbon.Table 2. USysRibbons table field definitions.Table 3. USysRibbons table data Microsoft Office Button, and then click Access Options..Figure 3. The Access application-level UI
To clean up, repeat the previous few steps to display the Access Options dialog box. Delete the contents of the Ribbon Name option, so that Access displays its default Fluent UI after you close and re-open the database..
To create a dynamic Ribbon customization.. extensibility functionality as a package without the need to add VBA code to each application. Add-ins are implemented in Access just as they are in other Office applications.
Consider the following scenarios that illustrate ways to modify the Fluent UI to fit your needs.
Creating Custom Solutions.
Showing and Hiding Tabs
You can use markup like the following sample to show or hide built-in tabs or custom tabs.
If you want to programmatically determine whether to show or hide a tab (or other element), you can provide a callback procedure. That is, you can define the element as in the following XML.
Then, in an add-in, or within VBA code, you can provide a procedure that returns a Boolean value that indicates whether the item is visible. For example, you might use code like the following to hide the Insert tab in Word 2007 on weekends.
Showing and Hiding Groups
You can use code like the following sample (along with the callback procedure in the previous example) to show or hide built-in groups or custom groups.
Adding Custom Tabs
You can use the following code sample to add custom tabs.
Adding Custom Groups with Controls
You can use the following code sample to add a custom group, and then add built-in controls.>
Creating a Custom Menu with Nested Menus and Controls"/> </menu> </menu> </menu>
Adding Combo Boxes or Drop-Down Boxes with Nested Items
You can use the following code sample to add a built-in combo box control with items (drop-down controls use the same syntax).
Adding Custom Gallery Controls with Items.
Filling a Drop-Down List Dynamically.
Grouping Individual Controls>
...
To add references an XML customization file.
To create the XML resource.
Modify the existing first line of the OnConnection method, which creates an instance of the Word.Application object.
(Visual Basic only) Modify the line of code, near the top of the class, that starts with Implements, adding support for implementing the IRibbonExtensibility namespace. Visual Basic inserts the GetCustomUI procedure automatically.
(C# only) At the end of the public class Connect : statement, add a comma and then type the following interface name.
following method to the class. This method inserts the company name into the document at the current cursor location....
To add a Ribbon extensibility item
On the Project menu, click Add New Item..
It is easiest to use the XML file if it is treated as a resource within the project's resource file.
To create the XML resource
On the Project menu, click InsertCompanyAddIn1 Properties.
Click the Resources tab..
Close the Resources window. When prompted, click Yes to save the resources.
To modify the Ribbon code and complete the add-in.
In the Ribbon1 class, modify the GetCustomUI procedure so that it returns the XML from the Ribbon1 resource, rather than calling the add-in's GetResourceText procedure.
In the Ribbon1 class, add a public declaration for a variable that can refer to the Word Application object.
In the same file, in the ThisAddIn partial class, immediately below the line of code that creates the instance of the Ribbon1 class, add code that sets the Ribbon1 class' Application property.
Add the following procedure to the Ribbon1 class, so that you can handle the onAction callback for the new button in the Ribbon and insert the company name at the cursor location in the document.
To test the add-in
On the File menu, click Save All..
extensibility:
In your code (VBA code within a document, or perhaps Visual Basic code or C# code in an add-in), add a procedure like the following code.
The IRibbonUI interface exposes the following methods. | http://msdn.microsoft.com/en-au/library/ms406046.aspx | CC-MAIN-2014-52 | refinedweb | 1,050 | 56.25 |
Hello, First of all thank you for taking time to help.
I recently started playing around with templates and singletons. I'm trying to make something like Unity's Debug.Log but in C++. Starting with simple things like cout. Unfortunately I got stuck and with all the googling I can't seem to find how to solve this issue without not making class singleton. Maybe there is better way of doing this?
//Console.h
#pragma once #include <iostream> class Console { private: Console() {} ~Console() {} public: static Console& instance() { static Console INSTANCE; return INSTANCE; } template <class T> void Print(T arg); };
//Console.cpp
#include "Console.h" template <class T> void Console::Print(T arg) { std::cout << arg.c_str() << std::endl; }
//main.cpp
#include "Console.h" int main(int argc, char *argv[]) { Console::instance().Print(5); return 0; }
The error is: | http://www.gamedev.net/user/199518-konrad-jablonski/?tab=topics | CC-MAIN-2016-07 | refinedweb | 139 | 71.21 |
Building Native User Interfaces is the Right Way To Build Cross Platform Style Apps
I hear a few developers getting down on Xamarin because they are required to:
- Create different projects for the various mobile platforms that they want to target.
- Learn the particulars of a given platform, or as I term them, the “isms.”
Interestingly,
these are not negatives to going with a Xamarin style cross platform
solution; these are most definitely positives in their style of
solution. Wait, how can this be? Developers have been training to
think that sharing as much code as possible (including the UI) is a good
thing. In this blog post, I’ll try to explain the issues of cross
platform development, what users want (yes, I do tend to do crazy things
like talk to users), the problems in cross platform development, and
finally why presenting the user with a native solution is just plain
better than a mobile web based solution.
What Users Want
Users want solutions to their problems. It is pretty simple. Solve a user problem, don’t create more problems, help the business cut costs, be a net positive in an organization, add value. These are fairly simple items. Unfortunately, a number of developers don’t quite understand this. Many developers just want to write code, “But Wally, I just want to write code. It is why I got into this job.” Or, you may be a part of some IT group where you are seen as a cost center. Whatever your position within the organization, getting out and talking to users has resulted in my finding the following items:
- Users want applications that look just like all of the other applications on their platform. Giving a user an application that looks like a Windows application while running on the Mac can result in some interesting feedback.
- Users want applications that act just like all of their other applications on their platform.
Basically,
this means that an application must call platform specific APIs and
must do so fairly close to the application logic. By doing this, the
application will look, smell, and taste just like every other
application on a platform. An iOS application will look like iOS. An
Android application will look like Android.
History’s Lessons
I’ve done a little bit with cross platform tools in the past. Early on in my career when I worked at The Cola-Cola Company, there was some involvement with:
- PowerBuilder for the Mac.
- Visual C++ for the Mac. While this never shipped, it existed to the point of us getting an NDA. It may have only existed to create FUD.
After
talking to users and working through some options, this is where I
learned how important it is for apps to look like the other apps that
users use.
A few years later, Java came on the scene. Unfortunately, Java ran into several issues:
- Java apps didn’t look like other apps on a given platform. Swing came out later on and it provides a much more platform specific look/feel to it.
- Early on, Java wasn't very fast, let's just be honest about it.
- Java had small incompatibility issues between platforms. Its promise of “Write Once Run Anywhere” had become “Write Once Debug Everywhere.”
- There was no guarantee that the Java framework was on a device. Expecting a user to install the framework was no realistic.
Not
long after Java, Microsoft .NET came on the scene. Unfortunately
Microsoft .NET never took over outside of the Windows space. Its cross
platform capabilities never really came about.
Now, I am sure
that there is someone jumping up and down widely waving their arms and
screaming “HTML5, HTML5 will save us.” Ultimately, HTML was designed
for the display of documents and content to users. Back in the mid
1990s, the reason why HTML took off was due to:
- Deploying most custom apps within a business was a nightmare. Deploying apps to a web browser was much easier. No dll hell, no installation programs to run, life was much better. Imaging trying to do this outside of a company without a support staff?
- Early web sites were much more about marketing. Very few public web sites back then were about applications. It took a few years for web sites to take on more of an application feel to them and now many have an app feel to them.
While there have been many attempts to give an HTML file device like capabilities, these capabilities always seem to be lacking in something. Mobile web apps with HTML5 are no different. There is always something that they can't do. For example, I’m working with some folks that are trying their hardest to get out of phonegap due to limitations of the platform. Now, I’m not going into the specifics on that, merely that there are issues and these aren’t the only folks with them.
Just so that we're clear on things, HTML web apps work out really well in a lot of situations. I've written a lot of them. I'm a Microsoft ASP.NET MVP (well at least for a little while longer). I continue to work on several. They just aren't the go to platform for mobile.
Developer Productivity
One of the big arguments I hear regarding using a single set of source files to build an application, is that this is more efficient for developers. I agree, this is absolutely true. Unfortunately, user productivity is 10-100x more valuable than developer productivity. Increasing user productivity by a small percent multiplied by the number of users results in a greater increase in productivity.
But, But, But HTML5……
While I will argue the point about user productivity increases dwarfing developer productivity, I’m not going to be unrealistic regarding what is happening in the marketplace. There are some places where having a single set of course files is valuable. These typically are:
- The client only has a few shillings to pay for a solution. The cost of an HTML5 mobile web solution is lower, let’s be honest about it. You can get your neighbor’s kid to do the work. This has a tendency to drive down the price. I’m just sayin’.
- If your IT department is considered to be a cost center. Build something, deploy it to a bunch of platforms, later, rinse, repeat.
PhoneGap Will Save Us
Sorry folks, but PhoneGap isn’t the be all and end all. PhoneGap is a container that embeds HTML, JS, and CSS content. It allows access to device APIs in a cross platform way. Unfortunately, you get access to content via a web view, so you are limited to what can be provided in the web view.
I almost went down the PhoneGap route back in 2009, until I read the first announcement of MonoTouch (now Xamarin.iOS).
But I do Java, ObjectiveC, or something else
Ok, great. There are tools for Java that allow you to write for iOS. Unfortunately, that won’t help you with WP. The same is true with ObjectiveC.
Why Xamarin
When Xamarin.iOS was first announced, I knew that was where I needed to be. It provides:
- Access to the native APIs directly from an application via the bindings contained in the various namespaces in Xamarin’s products. If your application isn’t calling native APIs, your application will most likely have small things that are out of place in some way. This immediately solved the problem that I had 20 years ago.
- Access to the .NET framework that I already know. I don’t have to go learn ObjectiveC, Java, Xcode, Eclipse, or Android Studio. I can use Visual Studio to develop apps for multiple platforms. I don’t have to go learn a new IDE.
- Sharing non-device specific code between iOS, Android, WP, and other .NET platforms.
- Learning the UI specifics and platform-isms allows you to build an application that integrates with the platform better than a shared application.
I have heard the chimes at midnight. I have gone through the cross platform battles in the past. The bottom line is that you have to create platform specific versions of your app. I think that Xamarin is the right place for me. I’ve learned my lesson. I’m calling native APIs with my language of choice, C#.
If you are interested in a discussion regarding Xamarin vs. Vendor
Directed solutions, I suggest this discussion in the Xamarin forms: | http://weblogs.asp.net/wallym/building-native-user-interfaces-is-the-right-way-to-build-cross-platform-style-apps | CC-MAIN-2015-35 | refinedweb | 1,427 | 65.93 |
Member
67 Points
Mar 24, 2012 03:03 PM|ravibagadiya|LINK
i have one problem when in inserting data into the database .when user start quiz then after press next button ,at that time whatever user selecting is store in one database but actually is not stored i used detaillist view to display quiz question.
quiz.aspx.cs code is:
protected void Button1_Click1(object sender, EventArgs e)
{
// Save off previous answers
System.Data.DataRowView dr = (System.Data.DataRowView)DetailsView1.DataItem;
// Create Answer object to save values
Answer a = new Answer();
a.QuestionID = dr["QuestionID"].ToString();
a.CorrectAnswer = dr["CorrectAnswer"].ToString();
if (RadioButton1.Checked == true)
{
crropt = "option1";
}
else if (RadioButton2.Checked == true)
{
crropt = "option2";
}
else if (RadioButton3.Checked == true)
{
crropt = "option3";
}
else if (RadioButton4.Checked == true)
{
crropt = "option4";
}
a.UserAnswer = crropt;
ArrayList al = (ArrayList)Session["AnswerList"];
al.Add(a);
Session.Add("AnswerList", al);
if (DetailsView1.PageIndex == DetailsView1.PageCount - 1)
{
// Go to evaluate answers
Response.Redirect("evaluate.aspx");
}
else
{
DetailsView1.PageIndex++;
Button1.Text = "Finished";
}
error of Answer object is solved but
now i get error like::
:
All-Star
20720 Points
Mar 24, 2012 03:31 PM|gerrylowry|LINK
this is a standard compiler error: the compiler has no clue about your type Answer ... if Answer is defined in a different assembly or namespace, you need to point the c# compiler in the correct direction ...
sometimes this is as simple as adding a namespace with a using or fulling qualifying the type name:
using RavisNamespace;
or
RavisNamespace.Answer = new RavisNamespace.Answer();
at other times, you might actually have to add a Reference to the assembly that contains your type Answer.
Please look closely at your code, is the namespace for Answer different from the namespace for the code where you are using the type Answer to creat your object a?
g.
Member
67 Points
All-Star
20720 Points
Mar 24, 2012 04:25 PM|gerrylowry|LINK
@ ravibagadiya TIMTOWTDI =. there is more than one way to do it
there's probably a shorter way, but this works:
put your cursor in Answer and press F12 or right click Answer and click Go To Definition ...
if that does not help you see the namespace associated with Answer, try
Click on Answer, open the Object Browser from the view menu and search for Answer ...
if you find Answer in the Object Browser, you may see something like Member of xyx;
if you then drill up, by clicking on xyz, you will eventually find the namespace associated with Answer.
Note: if all your efforts fail to locate Answer, then you will likely need to reference some external assembly where Answer is defined.
Another possibilty: you have not yet defined Answer or you've spelled Answer incorrectly where you've defined it.
To add references, depending on your project type, you can right click in Solution Explorer your Reference folder and click Add Reference... and/or you might have to right click inside your code behind file (i am not sure because i do not use code behind anymore).
g.
Star
9764 Points
Mar 24, 2012 07:08 PM|Primillo|LINK
Hi ravibagadiya
Here is a quiz application you can use as reference:
May help
4 replies
Last post Mar 24, 2012 07:08 PM by Primillo | http://forums.asp.net/p/1784690/4897295.aspx?quiz+application | CC-MAIN-2014-15 | refinedweb | 539 | 54.52 |
sorry didn't see you already answered that one :o
Type: Posts; User: jesamjasam
sorry didn't see you already answered that one :o
import java.util.Scanner;
class SemesterProject {
public static void main(String[]args) {
Scanner scanReader = new Scanner(System.in);
String password = "";
int length;
int...
oh, ok then try this:
import java.util.Scanner;
public class While {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
I don't quite understand what you're trying to do, but from what i understand this is what you're looking for:
import java.util.Scanner;
public class While {
public static void...
Yes that's it, requestFocus() did it. Thank you i would never figure this out by myself.
Yes, as you can see in Igra class i added key listener and made a private class (Slusalac) to serve as one, when i create Igrac object directly in my Igra class it all works, but when i create Igrac...
I started learning java, and tried to make a game, i almost finished it but then i realized that it doesn't work, so i copied the project and started dumping code from my game to find what did i do...
Basically you have to call your getSSN method inside the while loop just after the print statement:
import java.util.Scanner;
public class SSNValidatorApp
{
public static String ssn;
... | http://www.javaprogrammingforums.com/search.php?s=1de981dcdde614efe251354e21b79b92&searchid=1725389 | CC-MAIN-2015-35 | refinedweb | 230 | 72.16 |
SQL Expression Language Tutorial
This section presents the API reference for the SQL Expression Language. For a full introduction to its usage, see SQL Expression Language Tutorial.
The alias.
Return the clause expression COLLATE collation.
Return a Delete clause element.
Similar functionality is available via the delete() method on Table.
Return a descending ORDER BY clause element.
e.g.:
order_by = [desc(table1.mycol)]
Return a DISTINCT clause.)
Return the clause extract(field FROM expr)..
Return a _Null object, which compiles to NULL in a sql statement..
Return an Alias object derived from a Select.
*args, **kwargs.
Return a SQL tuple.
Main usage is to produce a composite IN construct:
tuple_(table.c.col1, table.c.col2).in_( [(1, 2), (5, 12), (10, 19)] )
Coerce the given expression into the given type, on the Python side only.
type_coerce() is roughly similar to :func:..
Bases: sqlalchemy.sql.expression.ColumnElement
Represent a bind parameter.
Public constructor is the bindparam() function.
Construct a _BindParamClause.
Compare this _BindParamClause to the given clause.
Bases: sqlalchemy.sql.visitors.Visitable
Base class for elements of a programmatically constructed SQL expression.
Returns the Engine or Connection to which this ClauseElement is bound, or None if none found..
Compile and execute this ClauseElement.
Deprecated since version 0.7: (pending) Only SQL expressions which subclass Executable may provide the execute() method.}
Compile and execute this ClauseElement, returning
Deprecated since version 0.7: (pending) Only SQL expressions which subclass Executable may provide the scalar() method.
the result’s scalar representation. this ColumnElement to another.
Special arguments understood:
Return True if the given ColumnElement has a common ancestor to this ColumnElement.
Bases: sqlalchemy.sql.expression.ColumnOperators
Defines comparison and math operations for ClauseElement instances.
Produce a ASC clause, i.e. <columnname> ASC
Produce a BETWEEN clause, i.e. <column> BETWEEN <cleft> AND <cright>
Produce a COLLATE clause, i.e. <column> COLLATE utf8_bin
Produce the clause LIKE '%<other>%'
Produce a DESC clause, i.e. <columnname> DESC
Produce a DISTINCT clause, i.e. DISTINCT <columnname>
Produce the clause LIKE '%<other>'
Compare this element to the given element or collection using IN.
Produce a column label, i.e. <columnname> AS <name>.
This is a shortcut to the label() function..
Produce the clause LIKE '<other>%'
Defines comparison and math operations.
x.__init__(...) initializes x; see help(type(x)) for signature
Hack, allows datetime objects to be compared on the LHS..
Add the given WHERE clause to a newly returned delete construct.
Bases: sqlalchemy.sql.expression._Generative
Mark a ClauseElement as supporting execution.
Executable is a superclass for all “statement” types of objects, including select(), delete(), update(), insert(), text().
Compile and execute this Executable. invoking:
Compile and execute this Executable, returning the result’s scalar representation..
This is shorthand for calling:
from sqlalchemy import alias a = alias(self, name)
Return the collection of Column objects contained by this FromClause.
Return the collection of Column objects contained by this FromClause.
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
Given a ColumnElement, return the exported ColumnElement object from this Selectable which corresponds to that original Column via a common anscestor column.
the given ColumnElement, if the given ColumnElement is actually present within a sub-element of this FromClause. Normally the column will match if it merely shares a common anscestor with one of the exported columns of this FromClause.
return a SELECT COUNT generated against this FromClause.
a brief description of this FromClause.
Used primarily for error message formatting.
Return the collection of ForeignKey objects which this FromClause references.
Return True if this FromClause is ‘derived’ from the given FromClause.
An example would be an Alias of a Table is derived from that Table.
return a join of this FromClause against another FromClause.
return an outer join of this FromClause against another FromClause.
Return the collection of Column objects which comprise the primary key of this FromClause.
replace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this FromClause.
return a SELECT of this FromClause..
Bases: sqlalchemy.sql.expression.FromClause
represent a JOIN construct between two FromClause elements.
The public constructor function for Join is the module-level join() function, as well as the join() method available off all FromClause subclasses.
The usual entrypoint here is the join() function or the FromClause.join() method of any FromClause object. )
See alias() for further details on aliases.
Create a Select from this Join.
The equivalent long-hand form, given a Join object j, is:
from sqlalchemy import select j = select([j.left, j.right], **kw).\ where(whereclause).\ select_from(j) column expression to the columns clause of this select() construct.
append the given correlation expression to this select() construct.
append the given FromClause expression to this select() construct’s FROM clause.
append the given expression to this select() construct’s HAVING criterion.
The expression will be joined to existing HAVING criterion via AND.
append the given columns clause prefix expression to this select() construct.
append the given expression to this select() construct’s WHERE criterion.
The expression will be joined to existing WHERE criterion via AND.
return a new select() construct with the given column expression added to its columns clause. new select() construct which will apply DISTINCT to its columns clause.
return a SQL EXCEPT of this select() construct against the given selectable.
return a SQL EXCEPT ALL of this select() construct against the given selectable.
Return the displayed list of FromClause elements.
return child elements as per the ClauseElement specification.
return a new select() construct with the given expression added to its HAVING clause, joined to the existing clause via AND, if any.
an iterator of all ColumnElement expressions which would be rendered into the columns clause of the resulting SELECT statement.
return a SQL INTERSECT of this select() construct against the given selectable.
return a SQL INTERSECT ALL of this select() construct against the given selectable.
return a Set of all FromClause elements referenced by this Select.
This set is a superset of that returned by the froms property,
which is specifically for those FromClause elements that would actually be rendered.
return a new select() construct which will apply the given expression to the start of its columns clause, not using any commas.
return a new Select construct with the given FROM expression merged into its list of FROM objects..
return a ‘grouping’ construct as per the ClauseElement specification.
This produces an element that can be embedded in an expression. Note
that this method is called automatically as needed when constructing expressions.
return a SQL UNION of this select() construct against the given selectable.
return a SQL UNION ALL of this select() construct against the given selectable.
return a new select() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.')
return a new select() construct with its columns clause replaced with the given columns.
Deprecated since version 0.6: autocommit() is deprecated. Use Executable.execution_options() with the ‘autocommit’ flag. LIMIT criterion applied.
return a new selectable with the given OFFSET criterion applied.
return a new selectable with the given list of ORDER BY criterion applied.
The criterion will be appended to any pre-existing ORDER BY criterion..
return a SELECT COUNT generated against this TableClause.
Generate a delete() construct.
Generate an insert() construct.
Generate an update() construct.
Bases: sqlalchemy.sql.expression._ValuesBase
Represent an Update construct.
The Update object is created using the update() function.
return a new update() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.
specify the VALUES clause for an INSERT statement, or the SET clause for an UPDATE..
Bases: sqlalchemy.sql.functions.GenericFunction
Bases: sqlalchemy.sql.expression.Function
Bases: sqlalchemy.sql.functions.GenericFunction
Define a function whose return type is the same as its arguments.
Bases: sqlalchemy.sql.functions.GenericFunction
Bases: sqlalchemy.sql.functions.ReturnTypeFromArgs
Bases: sqlalchemy.sql.functions.GenericFunction
Bases: sqlalchemy.sql.functions.GenericFunction
The ANSI COUNT aggregate function. With no arguments, emits COUNT *..ReturnTypeFromArgs
Bases: sqlalchemy.sql.functions.ReturnTypeFromArgs
Bases: sqlalchemy.sql.functions.GenericFunction
Bases: sqlalchemy.sql.functions.GenericFunction
Bases: sqlalchemy.sql.functions.AnsiFunction
Bases: sqlalchemy.sql.functions.ReturnTypeFromArgs
Bases: sqlalchemy.sql.functions.AnsiFunction
Bases: sqlalchemy.sql.functions.AnsiFunction | https://codepowered.com/manuals/SQLAlchemy-0.6.9-doc/html/core/expression_api.html | CC-MAIN-2022-33 | refinedweb | 1,370 | 52.97 |
Struts2 framework security flawsAbstract
This article describes the development of popular java framework for struts2, and webwork some of the security flaws, and illustrates the framework itself as well as developers use the framework, arising from security problems, and the author of a number of mining framework for security vulnerabilities had learned.
Recommend the following people to read
Learn about java development framework for developing understanding of web application security, "Network security enthusiasts"
Text
The current java web site development are usually not pure JSP, and most use the java framework.
With this framework, allows developers to more quickly develop the code, but also so that the code is very scalable, layered architecture of those ideas, even more pervasive. This also greatly affected the security code review, he proposed "layered audit code" ideas, such as DAO layer of specialized inspection sql injection, xss in the view layer of checks and so on. Of these frameworks has its own level, this article is mainly talking about the struts framework of related security issues, there will be a small part deals with the struts behind the DAO layer.
This framework updates the struts hold significant market share in a framework that at all levels, located as shown here:
Can see the struts in the web application to handle receiving user data, called business processing, and display the data work. Therefore, this paper, the function of struts into controller layer and the view layer, controller layer to complete the receive user data, distribution of user requests, while the view specifically for displaying data.
A separate struts, it is illogical, because the architect is usually like a collection of a variety of frameworks, so that they each responsible for a certain layer of processing. Study of a framework for security problems, can not just stand on the perspective of the framework should also be fully taken into account developers how to use these frameworks, what they most like to write the code, so as to restore a normal, complete web application scenarios .
From the search results on the Internet, most tutorials recommend struts + hibernate + spring such a combination of gold, then I assume that there is an application to use this combination in order to focus on struts, standing on the attacker's point of view, layers of analysis struts of the design flaws.
Development Review and easy to learn Struts2
To put the review or study how struts2, together we build an action, jsp page, do one receiving user input, followed by dealing with what, and then displayed to the user process, struts2 proficient students can skip this step.
------------------------------------- struts Review start
First, the establishment of action, called AaaaAction:
public class AaaaAction extends ActionSupport (
private String name;
public String getName () (
return name;
)
public void setName (String name) (
this.name = name;
)
public String execute () (
System.out.println ( "exe");
return SUCCESS;
)
public String bbb () (
System.out.println ( "bbbbb");
return SUCCESS;
)
)
Please note that execute this method, so that the address entered by the user action, the default will visit this method.
After the configuration struts.xml file
<action name="aaaaaaa">
<result name="success"> user / aaa.jsp </ result>
</ action>
Configuration of this file, when the user input
The time, struts will be responsible for AaaaAction in the execute method of processing user requests.
Processing, the method returns "return SUCCESS;", struts also responsible for finding the name is a result of the jsp page seccuess pointed.
To parse the page, return to the user.
The user can see is aaa.jsp page html code.
struts2 inherits all the advantages of webwork, in fact, tantamount to webwork upgrade, if the developers want the user to directly access the action in a way, rather than access to the default execute method, so long as the definition of a method called the bbb, and is a public, user - can directly enter the
Direct access to the methods of the bbb.
That request parameter, if it receives? struts2, this process is packaged up and is very convenient to use, as long as the action defined in a property, called public String name;. Then add getName and setName methods can be the same as the normal use of property, the receiver to the user to pass over variables. Either get a request or post requests in this way can be used to receive user input.
The whole process is so simple, it is now on the process with the understanding, we began to discuss the text, if you still want to know more, your own google.
---------------------------------- struts Review end
Struts2 flaws
Struts2 in the data flow can be seen, there are two main points, one is to enter the (in), one is the output (out). And I do dig the idea of vulnerability, but also follow the process this data to begin the analysis, here we started to let the data entry.
Action attribute default value can be covered by deficiencies:
In their daily java projects, we often encounter save a new object (such as registration of a user), and then give the object to give some user submitted, property values, where only need to define an object class:
public class User (
private Long
private String name;
private String pass;
private Integer type = 1;
. . . The following methods get and set code for slightly
)
Definition, in the action, add an attribute
User reguser;
User registration page code is as follows:
<form XXXXXXX>
<input name="reguser.name">
When the user submits the form to the action in the following, struts2 will be responsible for automatically mapping reguser.name's value to reguser related attributes (name), so the execute this method, you can use reguser.getName () to get users to submit a reguser.name value. Therefore, we the following code is very simple:
public String execute () (
add (user);
add method, more simple, because our project integrates hibernate, this framework automatically maps user classes each of the attributes, automatic composition of insert statements. As long as we add the call session.save (user); you can save the user to the database.
Previously referred to so many "simple" words, are these processes are safe while he gave us just the convenience brought about Yao?
struts2 is only responsible for mapping all the objects, he provided a form validation, and can only verify that the contents of the form of attribute values, such as email format, etc., and can not bind the user to submit other properties up, so this becomes a very dangerous functions.
When the User has a property type, whether the administrator on behalf of User (1 for ordinary users, 2 as an administrator), troubles come, the attacker in the original registration form, by adding a new input, called the
<input name="reguser.type">
And then enter the value is 2, together with this value to the action. In this process, this value is, of course, will be automatically taken to a database, down processing logic, the user, it has become the administrator of the.
When you see a struts2 or webwork application, you can try to use the property attack, modify the current form, which has all the attributes you have to guess to be submitted to up, it could affect the whole logic, to achieve any offensive purpose. This paper is just one example, in fact, the data transmission process, we can arbitrarily override the default value of the data, has always been a dangerous defect, while the struts2 and webwork framework of these two saw it only benefits ignored this regard, based on security considerations, just be concerned about the correctness of the data submitted by the user. Struts2 this function in the absence of contrast, when we need action in one of the needs of a variable, from the user's request to submit the solution out of a one treatment, such is not the security problems. It is now packaged this process, since that is in, but out of a serious problem.
Action in the method is defective violence guess Xie
Mentioned earlier, there is a way to allow users access to action, has no access to the default execute method, but direct access to other action in the way the condition that the action in writing a public method. Developers If you need to make a landing, the show features a list of all users, and he's a "decoupling" the development of habits, will be here to lead to security flaws.
Define an action as follows
public class Userlogin extends ActionSupport (
private String uname = "";
private String upwd;
private List list;
/ / getter and setter methods slightly
public String login () (
if (uname! = null & & upwd! = null & & uname.equals ( "kxlzx") & & upwd.equals ( "pass"))
(/ / if login success
return list ();
)
return false;
)
public String list () (
list.add ( "kxlzx"); list.add ( "kxlzx1"); list.add ( "kxlzx2"); list.add ( "kxlzx3");
return "list";
)
)
Userlogin, because the list this function (show all user list), is actually a common feature, it is easy to call other places, so developers had written it to a separate method.
When the user login time, open the
Come to the user's landing page, you can see, only the user enters the correct user name and password in order to ultimately call the list () method, displays the results.
However, all public methods struts2 are exposed out, leading to user input is now a
User to access this link, struts2 call the list method, and then returns the results to the user, so there is no login, it displays all the user information,
Direct bypassing the login in the login authentication.
In the absence of struts2, we want to servlet's doget or dopost methods, such as writing the code to determine if, in order to allow users to call other servlet in the way, it seems a matter of fact this is a protective measure. Now struts2 order to facilitate the development of all the public method of mapping out a unified, leading to the development to a frequently used functions, used to write a public method, but has now become a serious loophole.
struts2 in action attribute design flaws
Let us turn to our action in the attribute definition, you will find, and now they have become a loophole as struts2 provides property get and set methods must be public to.
Then we define the
private String name;
public String getName () (
return name;
)
public void setName (String name) (
this.name = name;
)
When this code is, in fact, to write two public methods.
That these two surfaces do not have any real meaning, there will be any security risk it?
This requires the previous text link mentioned earlier, we struts.xml file, defined as follows:
<action name="user">
<result name="success"> user / userlist.jsp </ result>
<result name="addUser"> user / addUser.jsp </ result>
<result name="added"> user / added.jsp </ result>
<result name="false"> user / false.jsp </ result>
</ action>
This code means that, UserAction, any implementation of a method, if the return is a success of this string will be the user / userlist.jsp returned to the user.
If the return is addUser, will be the user / addUser.jsp returned to the user.
UserAction now is to manage a user's page, in our system, there are general managers and super managers, and their difference is that general managers can view the user, but can not add a user.
Therefore, we UserAction in writing
public String addUser () (
if (true) (/ / In fact Here is a super-administrator to judge, I have been lazy.
return "false";
)
return "addUser";
)
This method does not allow the code to determine the general administrator access, but the user / addUser.jsp the jsp page, and no such decision logic.
Because the development that only when the return addUser only came to this page, but to return to addUser, you must pass the super administrator validation.
That way we can make a return addUser Mody? Of course you can!
This link, struts2 how would deal with it?
He will find struts.xml in the path segment corresponding to user, so to find the corresponding treatment of Action (net.inbreak.UserAction), because of the path with the "! GetUsername", so he went to the Action in getUsername this method, Obviously, this approach is a username of this property get method, if you want Action to receive user-submitted username, you have to define this method.
Then this method will return what? Will return the value of the username field action! HA HA ! username the user has submitted to the action, and links behind a sign reading "? username = addUser", struts2 this action given the value of the username attribute. Then return here, of course, "addUser"!
After a series of coincidences led to the user is now returned to the user / addUser.jsp page, which is a form to add a user page, and users do not have to go for the super administrator to verify this step.
Now add the users to see a user's page, he has two kinds of attacks on thinking:
1, direct submission, if not handled that submitted by the user without further action to determine user identity, then submitted to a success.
2, if he is to determine the user's identity, we can also csrf him, because we know the address of this action, and it needs parameters!
Because of the action and jsp file struts2 separation, resulting in developers tend to action approach, the implementation of competence to judge, but jsp page and did not call for the implementation of this assessment, he thought the action to determine enough. But had the properties of action, has brought us a customizable way to return result, leading to action that we can bypass the access to jsp pages.
Those that result type of Struts2 defects (redirect)
Struts2 we have just learned, has brought us the benefits of those properties, and now we go down to take one step after the study method to return the results of Action.
In fact, not only by the String type of results returned, struts2 there are other types of returns, such as "redirect" type.
<action name="test">
<result name="false"> user / false.jsp </ result>
<result name="redir" type="redirect"> $ (redirecturl) </ result>
</ action>
This code, we only possible to read, that is, type = "redirect" the.
This is a url redirect the way, struts2 for the convenience of all the development, the "custom 302 Jump to the other url" in this way to package up. As long as the above definition, we can write the action method:
public String redirect () (
return "redir";
)
And then define the properties
private String redirecturl;
When the user opens
The time, it will jump to 302
This is a very common application url jump in struts2, the above configuration what can be achieved.
I believe any discerning person looking out, it is clear there exist url Jump vulnerability, if the user enters a
This will jump to phishing site (-_-!). So how defense?
To defend, url Jump to phishing sites, we certainly need a white list mechanism, or simply let him jump to the next site. That's when the judge is as follows:
public String redirect () (
if (redirecturl.startsWith ("/"))
(
return "redir";
)
return "false";
)
Perhaps you saw it, and just to judge "/" at the beginning, in fact, can not put an end to url jump holes, because the
Will still jump. But here is enough, because struts2 has taken over this process, as long as "/" at the beginning, were all let you automatically add the local domain name, Ethereal, you will see
location:
In fact there will be no problem.
struts2 also believe that such judgments would not be a problem, but the user input
In fact, the former chapter have been analyzed, and so the use of action in the str property, bypassing the need to "/" at the beginning of the judgments of the direct jump.
test, there are a str attributes, can be customized to return, where the custom of the "redir", it came to the
<result name="redir" type="redirect"> $ (redirecturl) </ result>
The redirecturl values, also submitted to the action, so the jump.
Those that result type of Struts2 defects (Ajax)
The struts2 using ajax, is also supported by struts2, it provides a return type, called "stream". In the study of the use of this result, the author saw a book called "Struts 2 The Definitive Guide: Based on the WebWork core MVC development." This book is very well known, almost all of struts2 users are recommended.
Ajax book description It can be used:
Configuration struts.xml
<action name="ajaxtest">
<result type="stream">
<param name="contentType"> text / html </ param>
<param name="inputName"> input </ param>
</ result>
</ action>
After the write TestajaxAction:
public InputStream input;
public String execute () throws Exception (
input = new StringBufferInputStream ( "aaaa <td> <script> alert (" kxlzx ") </ script> aa");
return SUCCESS;
)
In fact, we have seen what I meant, and returned to the contentType to "text / html" pages, content
aaaa <td> <script> alert ( 'kxlzx') </ script> aa
The results, when the browser parsing the emergence of XSS vulnerabilities.
Originally default contentType is text / plain, no configuration, if the user directly to open, only to see a Stream, which does not parse html and js. Now, said the book should be written so I do not know whether the author knows the impact of this tutorial to all of us, results have been misled a large number of developers.
In fact, this is not a struts issue is the struts "authority" tutorial questions. Authoritative tutorial, once a security breach occurs, often will mislead a large number of developers who do not know at the time of digging holes, whether it is aware of this point, especially when the official DEMO a loophole, it is definitely shaking ZZZZZZZZZ the tragedy of .
Those that result type of Struts2 defects (custom page)
Sometimes, developers for the convenience of like configuration struts.xml is as follows:
<action name="test">
<result name="success"> user / test.jsp </ result>
<result name="testpro"> user / testproperty.jsp </ result>
<result name="redir" type="redirect"> $ (redir) </ result>
<result name="testloadfilepath"> $ (testloadfilepath) </ result>
<result name="false"> user / redirfalse.jsp </ result>
<result name="input"> user / input.jsp </ result>
</ action>
Please note, in which a result, the name "testloadfilepath", $ (testloadfilepath) is the role of a custom jsp page address, receive or request in the session pass over the value of this variable. Then the user submits
Of course, it will return user / test.jsp page, very flexible. Although not all of the development will be done, but once this happens, what would be the problem?
Do not know if you understand the meaning of this url is not, first call getRedir, can be customized to return to the testloadfilepath, while testloadfilepath have designated WEB-INF/classes/hibernate.cfg.xml. WEB-INF directory, are protected by the web container things, the relative address of the default does not allow a direct request to visit. The directory inside program compiled class file (which can be directly anti-compiled java source code), there is a database configuration files and other sensitive documents, and now open the above url, downloaded directly hibernate.cfg.xml, there stood the database user name and password.
In this way, the attacker can download all of your source code, all the files on the server. struts in providing us with this form of time, and there is no official statement here, that it is dangerous, and this is a non-timed bomb.
The taglib design flaws Struts2
After a few examples of down, do not know what notes the absence, from the user input came here, has reached the output of this step. struts2 of those result of the type, is actually several output modes, there are jsp, ajax, redirect, and other plug-in configuration after jsonplugin can also support other output modes. Even support a number of tag libraries, such as the freemarker other tag library. However, we only talk about struts2 tag library comes in a jsp top of the page, written some code, you can use the struts2 pages provided by the data output and data manipulation of the label.
Jsp output than in the past we have "<% = name%>" to be more convenient, the following give an example:
test.jsp Code
<% @ Taglib prefix = "s" uri = "/ struts-tags"%>
<s:property
The first line is to tell the struts are here to use the struts tag library, the second line is a label used, meaning the value of username is the output, username from the session, request, page, etc. to take place here does not care about the order of the data obtained.
struts2 The taglib design flaws (struts2.0 does not support escapeJavaScript)
Speaking of the output, we can think of XSS vulnerabilities, then as a pop framework, struts2 doing here, what control?
struts2.0 on the part of the label has done a default htmlescape:
Effect of that label actually mean just
<s:property
Do not think they are doing a htmlescape enough, the output in the javascript in the time will appear xss vulnerability. Therefore, this version of struts in 2.1.6 also supports the javascriptescape:
struts2.1.6:
<s:property
Enabled by default as shown above, when you want to output to a js in the time, you can use escapeJavaScript to escape.
In other words, once you determine struts is 2.0, as long as developers put into the js variable output, the likelihood would be a xss problems.
struts2 The taglib design flaws (no rich text safe output label)
To include the highest version 2.1.8 included, still do not support rich text safety output, this is a tragic thing, if the development of a popular blog with struts application, but also support the rich text of the article, developers can only htmlescape and jsescape are removed, in order to ensure the business up and running, it has led to XSS vulnerabilities.
struts2 The taglib design flaws (not all of the output labels have done a default htmlescape)
Several labels are not do htmlescape, such as
<s:a>
<s:text>
<s:url>
In fact, this is a serious trap, as long as that struts2, seniors will tell you, ease of use, which by default do htmlescape. That is what causes some of the labels did not do the default escape it? By turning the next source code, but also failed to identify any specific reason, do not know how those people think.
And, after a simple fuzz, found that in certain circumstances, those who made the label will be output escaping problems.
We know that the default htmlescape are not escaped single quotes, so, when the struts tag library source code in the output of some label attribute, if the label attribute is used around the single quotes, while the attacker can control the label attribute When examining the contents will appear xss vulnerability. Are as follows:
<input name="username">
When this xss's content can be controlled by the attacker, even though the content of xss made htmlescape, can still be an attacker bypass.
Based on this principle, the authors searched the struts tag library source code, those who "XXX.ftl" document search ") '" sign, to find more than N to test one of the following:
-------------
<s:textfield> tags, in normal use, he would put a <s:form> label, the final output html, it will become an input box.
It has a property known as "tooltip", if the label for the user can control, such as to read user input from the database, and this label is located
<s:form> opened up:
<s:form
When the value entered by the user tooltip, there will be the following:
struts2.0 ->
<span dojoType = "tooltip" ...
caption content is the value of tooltip from the database to identify
struts2.1.6 & struts2.1.8 ->
<img"domTT_activate(this, -'StrutsTTClassic');alert('xss');a('','styleClass'-" />
onmouseover generate a domTT_activate function call, the parameter in one of the values is the tooltip content. Here is a bypass.
------------
Found in several of these places do not actually do any escape, the output data directly. The following do that even if the default htmlescape, or will be problems, unless it is by default done javascriptEscape. struts2 default, have a place to do javascriptEscape Mody?
The answer is "no." Therefore, they all can be XSS!
struts2 of these escape, is in fact a very eunuch safety programs, safety engineers hated is this program has done a security program, do not complete, leaving a pile of problems.
struts2 addressing deficiencies of HTTP Parameter Pollution
webwork and struts2 have this problem, when a user to a web application submission:
When, if we define the action in the
private String redir;
public String getRedir () (
return redir;
)
public void setRedir (String redir) (
this.redir = redir;
)
Action will be taken to the redir value "kxlzx, aaad61" Note that there are spaces in the middle.
This data is from the webwork (struts2) the merger of the two parameters, but if we request.getParameter ( "redir"); get the value, but it is only the first one (the value kxlzx).
We know that struts2 promote the use of interceptors to do something, he can approach the implementation of the action to execute to do some before and after the operation. Then there are a number of development, taken for granted here, what url defense jump, SQL injection, XSS and other attacks. We take a look at how they will do:
@ Override
public String intercept (ActionInvocation arg0) throws Exception (
... ...
String name = request.getParameter ( "name");
if (name! = null & & name.indexOf ("'")>- 1) (
System.out.println ( "find sql injection");
request.getSession (). setAttribute ( "msg", "find sql injection");
return "falseuser";
)
String redir = request.getParameter ( "redir");
if (redir! = null & &! redir.equals ( "")) (
System.out.println ( "find url redirect");
request.getSession (). setAttribute ( "msg", "find url redirect");
return "falseuser";
)
return arg0.invoke ();
)
In this code, the authors only example in the defense in the interceptor and the url jump vulnerability sql injection, sql injection defense is to check the rules " '" single quotes, but loopholes in the rules is to check the url jump to jump to "http : / / "to go. Authors did not fully know the defense, so we do not here to hold the first defense programs, is just an example.
And developers in the business code is as follows:
String sql = "select book_name, book_content from books";
if (name! = null) (
sql + = "where book_name like '%" + name + "%'";
)
Obviously, that can be pumped.
public String redirect () (
return "redir";
)
Is also evident url Jump loopholes.
However, due to the interceptor prior to the implementation of the action, so if we entered the '
Of course, the interceptor will return an error "find sql injection";
As the implementation to the
String name = request.getParameter ( "name");
if (name! = null & & name.indexOf ("'")>- 1) (
Found that the value of the name does have single quotation marks.
But if we entered the
? name = aaaaa & name = a 'union select name, pass from user where''<>'
Directly bypassing the interceptor judgments. Because the interceptor obtained request.getParameter ( "name"), is the first value of the parameter aaaaa, abandoned the second parameter, but the action in the name of the value, but it is "aaaaa, a 'union select name, pass from user where''<>' "is why they are injected into
Most of the interceptor is to do the defense, including some filter and so on.
This incident occurred in url jump loopholes, but not obvious, because the attacker at best construct a:
Ethereal to see if
It jumped, go. Therefore, a direct Baocuo IE, saying that not open this address. But we still have another browser, always like to give you friendly information on the browser chrome to the user to see what advice:
Chrome also think that this is a wrong link, it gives the "correct" the link. This is not just used by phishing sites Mody?
struts2 official vulnerability announcements and patch the security flaw after the trigger
From there struts2, up to now, the official issued a total of four of loopholes in the
*
From the name, you can see the contents of the vulnerability, the author of which only two have done a source-level bug fixes assessment, found a lot of tragic things.
Students who are interested can go to study the remaining two holes.
struts2 official vulnerability announcements and patch security holes caused by post-(S2-002)
Take a look at "S2-002 - Cross site scripting (XSS) vulnerability on <s:url> and tags" this loophole.
As the name suggests is a <s:url> and <s:url> the xss bug fixes, but the previously mentioned, there are XSS vulnerabilities, is it that everyone in the Huyou? We take a look at how the gang of engineers to repair, and came to this svn Address:
Attention to these two lines:
To see when these two lines of code, the author laughed, because the author seems to see the tragedy of at least two things, and now to formulate them in story:
A tragedy of the first things a certain period of a day, a script-kiddies to the official reports of vulnerabilities that, when using the <s:url> tag code as follows:
<s:url </ s: url>
He then entered the = <script> alert ( 'hacked by kxlzx') </ script>
And told the official that this is a XSS vulnerability, which I hope fixes out.
Government attaches great importance to, a development went to repair, add the following judgments:
if (result.indexOf ( "<script>")> = 0) (
result = result.replaceAll ( "<script>", "script");
And conducted smoke testing, functional testing, black box testing, white box. That there is no problem, since the author of a malicious attacker to the url, the output of the
scriptalert ( 'hacked by kxlzx') </ script>
Results and not the implementation of xss script pages. Later, script kiddies also tested a bit and found no problem, the matter would have passed without the knowledge of the people of the public, quietly repaired.
The tragedy of the first two things, then after a certain person on a particular day, a one script kiddies has made a flaw, or that part of the code, but the url changed to: = <<script>> alert ( 'hacked by kxlzx') </ script>
Note that, here is <<script>>, after a replaceAll function after just become a <script>, re-formed the XSS vulnerabilities.
The government had to pay attention to it, decided to determine if into a while, no matter how much you gave you become <<<<<<< script >>>>>>>,
scriptalert ( 'hacked by kxlzx') </ script>
And conducted smoke testing, functional testing, black box testing, white box. This has also issued a bulletin out and say that there is no problem, we attach great importance to security vulnerabilities have been repaired.
Authors can see here, to test new bypass the official patch code url is: = <script kxlzx=kxlzx> alert ( 'hacked by kxlzx') </ script>
So XSS script has been executed, because here is <script kxlzx=kxlzx>, not <script>, so I do not meet the conditions to judge, have not been replaceAll, again bypas of bug fixes. . .
struts2 official vulnerability announcements and patch security holes caused by post-(S2-004)
This vulnerability patch, is more frustrating than the previous one, this is a / .. / access to the resource file vulnerability
S2-004 - Directory traversal vulnerability while serving static content
To learn more about the causes of this vulnerability, we need to first understand a knowledge point.
When the struts of the FilterDispatcher received a request for the following two path url of file:
Or
Would be to fetch struts-core package core.src.main.resources.org.apache.struts2 following static resource files, these resources are in fact some js script file and some css files. Mentioned earlier
<img"domTT_activate(this, -'StrutsTTClassic');alert('xss');a('','styleClass'-" />
Code domTT_activate, in fact the
File a function.
The struts2.0 time, as long as you dare, on a number of versions of the struts2, an attacker can, through ..% 252f ..% 252f ..% 252f ..% 252fWEB-INF/classess/example/Login.class /
Browse to your web directory, web directory to download files.
I will not speak bug fixes, the reader is quickly think about your company's developers, whether to use the struts2, and put "Struts 2.0.0 - Struts 2.0.11.2" between the several versions of packaged or no packaging, direct on the web application. If there is such a situation, the above methods can be directly attack these days by a few large portals to find the loopholes that they were all there this loophole, by the way downloaded their database configuration file, while reporting a loophole.
Struts official may have been attacked, and then fix the code.
Authors also looked at svn repair records:
Can be seen "if (! Name.endsWith (". Class ")) (" This line of code to fix them, they were deleted.
Patch before the code, why the former should be filtered. Class documents? Is because the struts provides a function:
If the developers want to use their own static file mapping feature, you can configure the web.xml
<filter>
<filter-name> struts </ filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</ filter-class>
<init-param>
<param-name> packages </ param-name>
<param-value> net.inbreak.action </ param-value>
</ init-param>
</ filter>
Above configuration, when the user input
When, in fact struts are going to see net.inbreak.action this folder under domTT.js documents to users, rather than the core of the package to find that folder. This feature is opening up, the official packages in order to prevent the corresponding class files are downloaded under the following anti-compiled source code, so writing lines of code, filter. Class files.
This line of code because of the existence of a time, it happened again struts2 popular era. The article describes a large number of Internet struts2-core source code, in introducing to the FilterDispatcher time, inevitably referred to here will be filtered. Class files, if the developers use this feature, you can rest assured that your class file will not be downloaded.
Later, out of vulnerability, an attacker can use ..% 252f ..% 252f ..% 252fWEB-INF/classess/example/Login.class /
To bypass the official limit, download class files. Indeed, this finally fixes / .. / loopholes. But the tragedy is that because the file is still the class can be downloaded, so the official fix at the same time, removing "if (! Name.endsWith (". Class ")) (" This line of code, you may feel that this line of code is too shameful.
Once the tutorial is also on the Internet, to tell you class file is not downloaded, the official has issued a statement repaired / .. / vulnerability. However, the development of tutorials to see who has long been to map the directory static files:
<param-name> packages </ param-name>
<param-value> net.inbreak.action </ param-value>
If this development net.inbreak.action package under a UserLogin.class documents, there are loopholes in the struts2 version, the server will face the fate of all the files have been downloaded. Even if the development of upgraded struts, because the core code of the class to determine the file removed, resulting in this file can still be
Official in the absence of any notification under the premise of flying in the tutorial to tell you class file is not downloaded the premise, in order to face this judge Qudiao quietly. Well this time, no matter whether upgrade, people do not break, if developers become dizzy, configuration is as follows:
<param-name> packages </ param-name>
<param-value> / </ param-value>
On a major, and you can download all the files under the resource directory.
Summary
Author struts2 dug some of the holes, but also dug a number of web vulnerability in other frameworks (not in the scope of this article), summarized these frameworks digging holes under way.
First of all, is not on the framework. Once developed using these frameworks, web applications will directly face a number of vulnerabilities:
1, open a certain function, leading to the default application to adopt a framework vulnerabilities
Because this framework, without permission, the quietly opened some of the features may be in order to facilitate the development of such effects, resulting in the generation of the holes.
For example:
This AJAX frameworks such as DWR, once used, in some versions, the input
Will be able to see a page, which is a method of mapping all the ajax, and even some service method is not configured to automatically map out. On this page you can map out ways to those who submit arguments, call the method. For example there getUserpasswdByid way to see the name, we know that passing the user id, return your password.
Another example is the article in the ../../ vulnerability struts2.
If you want to dig such a loophole is absolutely level 0day vulnerabilities, so we need to suspect that an implementation of each step, this loophole in fact mostly be found in the development environment and the formal differences in the environment as well as some weird function of point .
2, extending a certain function, leading to security problems
Our web application, that could have been writing their own code to achieve some of the features, but this framework in order to facilitate the development and management, the developers write the code packaged, so long as a few simple lines can achieve the original code can achieve a large number of functions. These facilities, has brought a lot of security issues. Digging holes at the same time, we should pay special attention to where a lot of convenience than the original, extended a lot of these extensions and convenient, whether it takes into account the safety factors.
This article describes the struts example of the result (urlredirect) related vulnerabilities.
3, DEMO, or tutorial or user's guide to mislead
Since the emergence of the framework, in order to let people understand and use the framework of the fastest, the official was right out the user's manual, demo and other functions. And many large cattle, have also out of the corresponding tutorials or books, but these tutorials, DEMO, examples of books, just had a lot of loopholes. Even the development did not go according to tutorial, there will be no loopholes, but was misled tutorial. If a hacker to see these books, please do not hesitate to put him out of your scanner, we do have a lot of development will follow the tutorial to do.
For example, that book mentioned in this article we use the ajax thing.
4, had a safety program, but was a functional code coverage
In fact, this is a tragic thing, tell us should pay attention to in their daily development and bug fixes, whether there are any developers who know the truth, in order to achieve a particular function, quietly taken out of context to the original security plan coverage out. When digging holes, paying particular attention to the annex to the code changes in safety programs, it may find a very mentally retarded logic.
For example, this class of documents submitted by the judge.
5, imperfect security
The implementation of a safety program should be thoroughly, pay attention to the integrity of the program can not be that some local programs OK, in some places can not be implemented. When digging holes, and do not be intimidated by the security program, not with the program, it sounds like cattle X, absolutely no flaws, at least, should there be a comprehensive fuzz.
For example, XSS missing points mentioned in this article, as well as rich text omission.
6, version upgrade, there is no visible security bulletins
We know that all architects are reluctant to upgrade the framework of emergency all right, especially in the framework of an unstable version, because the upgrade may bring a lot of unexpected problems, so we may even see the security bulletin, it did not go to upgrade. If you do not understand security, even more reluctant to upgrade the framework of the. So, the official must do a vulnerability patch, the release of an announcement to be associated with the code log. To tell you specifically where to do changes. The students dug holes should close watch on these areas, in every possible way to change part of refining and testing, not to be a common test results startled and ambiguous that the vulnerability has been repaired.
7, the tragedy of the program
Very often, we will see an official patch vulnerabilities, or the results of the implementation of some safety programs. It was not really able to achieve the effect of plugging the loopholes to do?
For example, this article <s:url> tag xss vulnerabilities, the official patch all the loopholes, really racked his brains, ultimately a tragedy.
8, excellent programs, the implementation of the tragedy
RT, no explanation.
9, Challenges web server configuration
This problem it is necessary to say, struts emergency all right to be a static mapping to do? In fact the purpose is to separate the framework and applications, it is clear that js file should be placed in the project in the web directory, but why do so? Is because the package is not released when the struts, no project, only a framework.
In order to achieve even if it is on any projects can also be a way to provide access to its purpose of those js had to reluctantly forced to carry out this function, the static directory is mapped. Regardless of any project, deployment, just behind the root directory url add / struts, or the / static can access js. Later, this feature did not also feel good, actually provide the functionality out to recommend to the developers. In the final analysis because the struts of the web server configuration challenges that must make their own static mapping. Need to know other people to do web server mapping is the result of many years grinding out hacking, struts have all these?
This underscores the map a directory in a separate, individual right to do access a directory, do DIR list of features, if you see a framework that has done such a function, Congratulations! Quickly dig up, there are loopholes in all likelihood!
10, there is no safety program, and no reminder
In fact, this article does not mention a number of web vulnerabilities, such as csrf, such as session fix, such as transmission encryption, it is clear the existence of loopholes in struts, but authors think that these things do not need to say here that we are all discerning eye to see form where there is no token , hundred percent csrf Well!
Think of the Crown, the government has also clearly know that the framework of their own will, after the existence of these loopholes, why did not even have to remind it? Originally developed do not know, you wish to hide:. If the framework of responsible, issued a notice, saying that if you use my framework to be careful what is in fact what the attack. . .
Uh. . . I understand why the official did not dare to say. -_-!
In addition to these frameworks that "as long as you use will inevitably flawed" security flaws, there are many problems that will appear on developers use the framework of the process:
1, two frameworks are convenient, there are loopholes in combination with a framework called Spring security, is based on the url of access control, and do it well. If you are not an administrator, absolutely can not access the admin directory. However, there are many web frameworks, access to an action or access a controller, more than one url can be accessed, where did the compatibility processing, multiple url point to the same application, leading to Spring security of this url-based access control, exists in name only.
2, the developer of "normal" use of the framework, it may create loopholes that is among the most miserable thing, the framework would not claim this type of vulnerability, he will think this is a development issue. However, this article "action method of brute force, url redirect magnify" The two security flaws, and indeed there is the meaning of the framework (facilitate the development of) the consequences. Yao will be an official patch? I think it will, at most, said we should not just one kind or another, will not do what the security program. Should be aware of these vulnerabilities is a struts or webwork characteristics, and only the use of only some of these frameworks.
3-point framework dangerous features brought some function point, such as Tag lib some of the XSS, when used, must have loopholes.
4, the framework for developers digging and this is fundamentally a trap, or say / static, / struts, if the development is not configured to download at most a js, little impact, if the development to use this feature, map a certain directory, then fell into the pit went.
5, a framework for vulnerability brought about by another framework to maximize the variables mentioned herein are the default value is overwritten, and also because hibernate do not need to write sql statement, and ultimately be stored into the database.
I recall a problem, If we allow ourselves to write sql statement to achieve, can you add the time ordinary users will be really special to write a variable to receive the user registration of the administrator's field of incoming Mody?
But this is too hibernate problem? Of course not, but because of it, leading to more serious vulnerabilities only.
Added
In this paper, struts2 various security flaws, it referred to here. Personally think that this is a direction of digging holes, digging holes on the framework.
We are focused on the code may be safe, there is not much to see the framework of their own safety and the use of the framework, does it really safe.
Therefore, many people ignore this issue, I believe this is not a new beginning, nor is it an end, just so that everyone began to pay more attention to the security framework.
The author also mentioned in this article only the struts, webwork these two frameworks, in fact, a lot of the framework, they really secure? Yet to be verified!
Addressed to those who actually intend to end technology for the practice of students, the framework of vulnerability scanner, it can make out, the guess for the solution of the problem difficult to solve, you can look at spiders the site, and then save those developers who prefer to use the field name, and concern about the input's name, action name, directory name and so on, generates a list of guess solution. The struts used to determine whether a more simple:
Feature 1: XXX.action may be struts or webwork
Feature 2: XXX.do may be struts or webwork
Feature 3: XXX! Bbb.action may be struts or webwork
Feature 4: XXX / struts / ..% 252f necessarily struts2
This article comes from:, thank you share
Related Posts of Struts2 framework security flaws
Maven 2.0: Compile. Test. Deployment. Run
<url> </ url> <dependencies> <dependency> <groupId> junit </ groupId> <artifactId> junit </ artifactId> <version> 3.8.1 </ version> <scope> test </ scope> <
jBPM Development Getting Started Guide
Although the workflow is still immature stage of development, not even a recognized standard. But its application has already been launched in the Express, indicating the market's demand for job-flow framework are urgent and enormous. Backgrounds of o
js page Jump implementation of a number of ways
The first is: <script language="javascript" type="text/javascript"> window.location. alert | http://www.codeweblog.com/struts2-framework-security-flaws/ | CC-MAIN-2014-42 | refinedweb | 7,877 | 56.49 |
It raises larger API questions. From the standpoint of
> user-level code readability, the present array of marker and
> line identifiers (inherited from Matlab) is not good. For
> example, why should '-' mean a solid line, but '_' means a
> horizontal line marker? What is the difference between '^'
> and '2', and how on earth is anyone reading the code
> supposed to know what '2' means? The only justification I
> can see for the 1- and 2-character codes is their
> convenience in interactive use for things like
> "plot(x,y,'g.'". I would not want this to go away, but for
> non-interactive coding I think longer names, typically
> corresponding to the name of the function that generates the
I think for interactive use it is important to keep these short
characters though you are right, for some of the more arcane ones like
1,2,3,4 it makes no sense since there is no mnemonic. But I see no
harm in keeping them for interactive users
> This needs either some broader discussion, or a command
> decision by John along the lines of "Forget it; it's OK the
> way it is, or it is too late to make any change in this part
> of the API."
As you suggest, what we need to provide is an easy way for people to
use long readable names. The easiest way is in set_marker and
set_linestyle to do something like (untested sketch)
def set_linestyle(self, linestyle):
funcname = '_draw_%s'%linestyle
func = getattr(self, funcname, None)
if callable(func):
self._lineFunc = func
and ditto for set_marker while still supporting the old mnemonics.
We can then advertise any of names available as values in the
Line2D._lineStyles and Line2D._markers dictionaries as legitimate
values for the linestyle and marker properties. Extra credit for
auto-updating the docstring by parsing the dictionary values.
In [1]: from matplotlib.lines import Line2D
In [2]: print [name[6:] for name in Line2D._markers.values() if
name.startswith('_draw_')]
['tickleft', 'tickright', 'tickup', 'tickdown', 'nothing', 'nothing',
'plus', 'pixel', 'point', 'tri_down', 'tri_left', 'tri_up',
'tri_right', 'triangle_left', 'triangle_right', 'nothing', 'diamond',
'hexagon2', 'hline', 'triangle_up', 'thin_diamond', 'hexagon1',
'circle', 'pentagon', 'square', 'triangle_down', 'x', 'vline']
JDH | https://discourse.matplotlib.org/t/marker-color-handling-line-and-marker-designations/6046 | CC-MAIN-2019-51 | refinedweb | 359 | 61.06 |
Reindeer - Moose with more antlers
This document describes version 0.018 of Reindeer - released March 28, 2015 as part of Reindeer.
# ta-da! use Reindeer; # ...is the same as: use feature ':5.xx'; # where xx is appropriate for your running perl use Moose; use MooseX::MarkAsMethods autoclean => 1; use MooseX::AlwaysCoerce; use MooseX::AttributeShortcuts; # etc, etc, etc extensions already applied. Reindeer is a drop-in replacement for your "use Moose" line, that behaves in the exact same way... Just with more pointy antlers.
Be aware this package should be considered early release code. While Moose and all our incorporated extensions have their own classifications (generally GA or "stable"), this bundling is still under active development, and more extensions, features and the like may still be added.
That said, my goal here is to increase functionality, not decrease it.
When this package hits GA / stable, I'll set the release to be >= 1.000.
This method allows you to easily compose a new class with additional traits:
my $foo = Bar->with_traits('Stools', 'Norm')->new(beer => 1, tab => undef);
(See also MooseX::Traits.)
Unless specified here, all options defined by Moose::Meta::Attribute and Class::MOP::Attribute remain unchanged.
For the following, "$name" should be read as the attribute name; and the various prefixes should be read using the defaults
Coercion is ENABLED by default; explicitly pass "coerce => 0" to disable.
(See also MooseX::AlwaysCoerce.)
The reader methods for all attributes with that option will throw an exception unless a value for the attributes was provided earlier by a constructor parameter or through a writer method.
(See also MooseX::LazyRequire.).
In addition to all sugar provided by Moose (e.g. has, with, extends), we provide a couple new keywords.' };
(See also Moose::Util::TypeConstraints.)' };
(See also Moose::Util::TypeConstraints.)
Exactly like "has" in Moose, but operates at the class (rather than instance) level.
(See also MooseX::ClassAttribute.)
default_for() is a shortcut to extend an attribute to give it a new default; this default value may be any legal value for default options.
# attribute bar defined elsewhere (e.g. superclass) default_for bar => 'new default';
... is the same as:
has '+bar' => (default => 'new default');
abstract() allows one to declare a method dependency that must be satisfied by a subclass before it is invoked, and before the subclass is made immutable.
abstract 'method_name_that_must_be_satisfied';
requires() is a synonym for abstract() and works in the way you'd expect.
It is safe to use overloads in your Reindeer classes and roles; they will work just as you expect: overloads in classes can be inherited by subclasses; overloads in roles will be incorporated into consuming classes.
(See also MooseX::MarkAsMethods)
We export the following trait aliases. These traits are not automatically applied to attributes, and are lazily loaded (e.g. if you don't use them, they won't be loaded and are not dependencies).
They can be used by specifying them as:
has foo => (traits => [ TraitAlias ], ...);
has foo => ( traits => [ AutoDestruct ], is => 'ro', lazy => 1, builder => 1, ttl => 600, );
Allows for a "ttl" attribute option; this is the length of time (in seconds) that a stored value is allowed to live; after that time the value is cleared and the value rebuilt (given that the attribute is lazy and has a builder defined).
See MooseX::AutoDestruct for more information.
This attribute trait allows one to designate that certain attributes are to be cleared when certain other ones are; that is, when an attribute is cleared that clearing will be cascaded down to other attributes. This is most useful when you have attributes that are lazily built.
See MooseX::CascadeClearing for more information and a significantly more cogent description.
This is a Moose attribute trait that you use when you want the default value for an attribute to be populated from the %ENV hash. So, for example if you have set the environment variable USERNAME to 'John' you can do:
package MyApp::MyClass; use Moose; use MooseX::Attribute::ENV; has 'username' => (is=>'ro', traits=>['ENV']); package main; my $myclass = MyApp::MyClass->new(); print $myclass->username; # STDOUT => 'John';
This is basically similar functionality to something like:
has 'attr' => ( is=>'ro', default=> sub { $ENV{uc 'attr'}; }, );
If the named key isn't found in %ENV, then defaults will execute as normal.
See MooseX::Attribute::ENV for more information.
has 'data' => ( traits => [ MultiInitArg ], is => 'ro', isa => 'Str', init_args => [qw(munge frobnicate)], );
This trait allows your attribute to be initialized with any one of multiple arguments to new().
See MooseX::MultiInitArg for more information.
Applying this trait to your attribute makes it's initialization tolerant of of undef. If you specify the value of undef to any of the attributes they will not be initialized (or will be set to the default, if applicable). Effectively behaving as if you had not provided a value at all.
package My:Class; use Moose; use MooseX::UndefTolerant::Attribute; has 'bar' => ( traits => [ UndefTolerant ], is => 'ro', isa => 'Num', predicate => 'has_bar' ); # Meanwhile, under the city... # Doesn't explode my $class = My::Class->new(bar => undef); $class->has_bar # False!
See MooseX::UndefTolerant::Attribute for more information.
Reindeer includes the traits and sugar provided by the following extensions. Everything their docs say they can do, you can do by default with Reindeer.
Note that this causes any overloads you've defined in your class/role to be marked as methods, and namespace::autoclean invoked.
This provides a new class method,
with_traits(), allowing you to compose traits in on the fly:
my $foo = Bar->with_traits('Stools')->new(...);
Non-Moose specific items made available to your class/role:
If you're running on v5.10 or greater of Perl, Reindeer will automatically enable v5.10 features in the consuming class.
Technically, this is done by MooseX::MarkAsMethods, but it's worth pointing out here. Any overloads present in your class/role are marked as methods before autoclean is unleashed, so Everything Will Just Work as Expected.: $!";
See the Path::Class documentation for more detail."; };
See the Try::Tiny documentation for more detail.
This author is applying his own assessment of "useful/popular extensions". You may find yourself in agreement, or violent disagreement with his choices. YMMV :)
Reindeer serves largely to tie together other packages -- Moose extensions and other common modules. Those other packages are largely by other people, without whose work Reindeer would have a significantly smaller rack.
We also use documentation as written for the other packages pulled in here to help present a cohesive whole. | http://search.cpan.org/~rsrchboy/Reindeer-0.018/lib/Reindeer.pm | CC-MAIN-2016-40 | refinedweb | 1,074 | 55.64 |
I'm facing some issue while trying to pass the data from one controller to the other using my service.
I've been implementing the prototype inheritance using the $rootScope in my controller and broadcasting that object, so that I can access that data in the other controllers.
As I'm using the $rootScope, I'm polluting the global namespace, I'd like to pass the data from this controller to the other.
I'm just displaying minimal data inside a table, when the user clicks on specific record of the table, I want to display entire data inside the object.
This is how I'm handling.
<tr ng-
Here is the reference Link:
You could use an angular service for this.
The angular services are singletons and you inject them in controllers so you could inject the same service in two different controllers and you are effectively passing state between them.
Imagine you have a property in your service which could be called selectedUserID. You update this property when you click on the specific row. Then in the next controller, you inject the same service and use this property to determine which details you will load.
so you could have a method inside your service which could look like this :
updateSelectedUser = function(userID) { this.selectedUserID = userID; }
Your controller then calls this method from the service when the click action happens :
myService.updateSelectedUser($scope.selectedUserID);
This is just an example of course, put your own values in there.
One thing to keep in mind : services can hold state, they are objects after all and singletons so you always inject the same instance.
It makes sense to make sure that the state stored inside the service is not modified by outside actions which do not go through this service. In other words make sure that nothing else changes this selectedUserID so your service state data never gets out of sync. If you can do this, then you are golden. | https://codedump.io/share/4IO5oZKppRU9/1/how-to-pass-data-from-one-controller-to-other-using-service | CC-MAIN-2016-50 | refinedweb | 328 | 61.06 |
In this tip, I show you how you can create a Visual Studio 2008 macro that creates a new MVC controller, view folder, and controller unit test with a single command.
In this tip, I show you how you can create a Visual Studio 2008 macro that creates a new MVC controller, view folder, and controller unit test with a single command.
Don’t get me wrong. I like the Visual Studio 2008 designer tools. I like dragging-and-dropping items from the toolbox. I’ve memorized many useful Visual Studio keyboard shortcuts. But, at the end of the day, there is nothing faster than firing off a quick command from the Command window.
In this tip, I explain how you can take advantage of Visual Studio macros and the Visual Studio Command window to generate files and code for an ASP.NET MVC project. In particular, I explain how you can create a macro that creates a new MVC controller, MVC view, and MVC controller unit test.
There are two approaches that you can take to creating new Visual Studio macros. First, you can record your actions when interacting with Visual Studio. To do this, select the menu option Tools, Macros, Record TemporaryMacro. A VCR-like control panel appears. After you are finished recording, you can click the Stop button and you will have a new macro that you can save and replay in the future.
The other approach is to write the macro from scratch. I took this second approach when creating my MVC macros. I was forced to use this second approach since I needed to write generic functions that would work with any MVC project.
Visual Studio macros must be written in the Visual Basic .NET programming language. The majority of your macro code consists of calls to the Visual Studio Automation Object Model. My MVC macros took advantage of the following Automation objects:.
You create a new Visual Studio Macro Project by selecting the menu option Tools, Macros, New Macro Project. Selecting this menu option opens the New Macro Project Dialog Box (see Figure 1).
Figure 1 – New Macro Project Dialog Box
After you create a new Macro Project, the Macro Explorer window opens in the location normally occupied by the Solution Explorer window (see Figure 2). You can double-click any macro in the Macro Explorer window to run a macro. You also can right-click a macro in the Macro Explorer and select the menu option Edit to modify the macro.
Figure 2 – Macro Explorer Window
When you edit a macro, the Macro IDE appears. The Macro IDE looks just like another instance of Visual Studio 2008. However, it is a more limited development environment that is specifically designed for developing macros.
You create a set of macros by creating a Visual Basic .NET module. Each public subroutine that you define in the module is exposed as a separate macro. For example, the code in Listing 1 a super simple macro that simply displays a message box with the message “Hello World!”.
Listing 1 – Test.vb
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module Test
Sub SayHello()
MsgBox("Hello World!")
End Sub
End Module
A macro subroutine can accept parameters. However, all parameters must be Optional parameters – use the Visual Basic Optional keyword. If you don’t make the parameters optional, then the subroutine won’t appear in the Macro Explorer window.
After you create a macro, there are several ways to execute it:
· From the Macro Explorer window
· From the Command window
· From the Find input box
· From the Macro Explorer window
· From the Command window
· From the Find input box
The easiest way to execute a macro is to double-click the macro in the Macro Explorer window. However, that defeats the purpose of this tip. The goal of this tip is to explain how you can quickly modify an ASP.NET MVC project by typing out commands.
The second option is to execute a macro from the Command window. You can open the Command window by selecting the menu option View, Other Windows, Command Window (or better, use the keyboard combination Ctl-Alt-A). After the Command window opens, you can fire off a macro by typing Macros.Macro Name. For example, you can execute the macro that we created in the previous section by typing the following command into the Command window:
Macros.MVC.Test.SayHello
You get full statement completion when entering a macro name (see Figure 3). So you really only need to enter the letter “m” and arrow down to the macro that you want to execute.
Figure 3 – Command window statement completion
I discovered this last method of executing a macro from Sara Ford’s blog at:
You can execute a macro from the Find input box that appears in the Visual Studio toolbar (see Figure 4). Type a “>” followed by the name of the macro to execute the macro. You can navigate quickly to the Find input box from the keyboard by using the keyboard combination Ctl+/ (Press the Ctl key and press the forward slash).
Figure 4 – Executing a macro from the Find input box
If you really want to reduce the amount of typing required to execute a macro then you can create a macro alias. Just use the alias command like this:
alias h Macros.MVC.Test.SayHello
alias h Macros.MVC.Test.SayHello
After you execute this command from the Command window, you can execute the SayHello macro simply by typing the single letter h.
You delete an alias with the /delete switch like this:
Alias h /delete
Alias h /delete
By taking advantage of aliases, you can perform common ASP.NET MVC tasks with the bare minimum of typing.
The MVC macros are contained in Listing 2. The file in Listing 2 contains a module named Generate that contains four public subroutines named All, Controller, View, and ControllerTest.
Listing 2 – Generate.vb
Imports System.IO
Public Module Generate
Sub All(Optional ByVal name As String = "NewThing")
' Generate Controller
Controller(name)
' Generate View
View(name)
' Generate Controller Test
ControllerTest(name)
Sub Controller(Optional ByVal name As String = "NewThing")
' Get MVC project
Dim mvcProj = GetMVCProject()
If Not IsNothing(mvcProj) Then
BuildControllerClass(mvcProj, name)
End If
Sub View(Optional ByVal name As String = "NewThing")
BuildView(mvcProj, name)
Sub ControllerTest(Optional ByVal name As String = "NewThing")
' Get Test project
Dim testProj = GetTestProject()
If Not IsNothing(testProj) Then
BuildControllerTestClass(testProj, name)
Private Sub BuildControllerClass(ByVal project As Project, ByVal name As String)
Dim controllerName As String = name & "Controller.cs"
Dim controllerPath = Path.Combine(Path.GetDirectoryName(project.FileName), Path.Combine("Controllers", controllerName))
Dim newController As CodeClass = project.CodeModel.AddClass(Path.GetFileNameWithoutExtension(controllerName), controllerPath, 0, "System.Web.Mvc.Controller", Nothing, vsCMAccess.vsCMAccessPublic)
' Add Index Function
Dim func As CodeFunction2 = newController.AddFunction("Index", vsCMFunction.vsCMFunctionFunction, "System.Web.Mvc.ActionResult")
func.Access = vsCMAccess.vsCMAccessPublic
Private Sub BuildView(ByVal project As Project, ByVal name As String)
Dim viewsFolder As ProjectItem = GetViewsFolder(project)
If Not IsNothing(viewsFolder) Then
viewsFolder.ProjectItems.AddFolder(name)
Private Sub BuildControllerTestClass(ByVal project As Project, ByVal name As String)
Dim controllerName As String = name & "ControllerTests.cs"
Dim newControllerTest As CodeClass = project.CodeModel.AddClass(Path.GetFileNameWithoutExtension(controllerName), controllerPath, 0, Nothing, Nothing, vsCMAccess.vsCMAccessPublic)
newControllerTest.AddAttribute("Microsoft.VisualStudio.TestTools.UnitTesting.TestClass", String.Empty)
' Add Test Function
Dim func As CodeFunction2 = newControllerTest.AddFunction("IndexTest", vsCMFunction.vsCMFunctionSub, "void")
func.AddAttribute("Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod", String.Empty)
' Gets MVC project based on NO Tests suffix
Private Function GetMVCProject() As Project
For Each proj As Project In DTE.Solution.Projects
If Not proj.Name.EndsWith("tests", StringComparison.InvariantCultureIgnoreCase) Then
Return proj
End If
Return Nothing
End Function
' Gets test project based on Tests suffix
Private Function GetTestProject() As EnvDTE.Project
For Each proj As EnvDTE.Project In DTE.Solution.Projects
If proj.Name.EndsWith("tests", StringComparison.InvariantCultureIgnoreCase) Then
Private Function GetViewsFolder(ByVal project As Project)
For Each item As ProjectItem In project.ProjectItems
If String.Compare(item.Name, "Views") = 0 Then
Return item
You can create a new controller, view folder, and controller test by executing the following command from either the Command window or the Find input box:
Macros.MVC.Generate.All Product
Macros.MVC.Generate.All Product
Executing this command creates a new controller named ProductController, a new view folder named Product, and a new unit test named ProductControllerTests.
If you want to reduce the amount of typing that you need to execute these commands, then you can create a macro alias like this:
alias gen Macros.MVC.Generate.All
alias gen Macros.MVC.Generate.All
This command creates an alias named gen that represents the MVC.Generate.All macro. After you create the alias, you can create a new controller, view folder, and unit test class like this:
gen Customer
gen Customer
This is the ultimate approach to creating MVC project items in the fastest and laziest possible way! After executing this command, your Solution will contain the files in Figure 5.
Figure 5 -- Generating a Customer
My goal with this tip was to show that it is possible to build commands that can be executed from within the Visual Studio IDE that enable you to quickly generate ASP.NET MVC project items. By taking full advantage of the powerful Automation Model included in Visual Studio 2008, you could (theoretically) build entire ASP.NET MVC Applications without opening a single dialog box or selecting a single menu item.
This is something I think should be included in OOTB template.
I have some remarks:
1. In the generated controller class, there are no 'using' statements, as well as the namespace declaration - there are only class declaration and action result method. How do we customize the code created?
2. Also in test controller class, situation is the same
I tried to record a macro to see how this can be done, but I only have DTE Commands with string arguments
@panjkov -- You are right that the code included in this tip is really more of a Proof of Concept code sample than anything else. I wanted to show that you could do code generation easily from the Visual Studio Command window. I think it would be really useful and cool to create macros that did more extensive code generation (like create views, LINQ to SQL entities, and so on).
This is a pretty useful tool. It needs a little tweaking, but I like this better than my NAnt solution I did recently.
I'm concerned about the method of selecting the project, as it seems pretty brittle. Most of my apps have many projects, and only one of them is the web project.
Anyway, cool stuff! | http://weblogs.asp.net/stephenwalther/archive/2008/07/09/asp-net-mvc-tip-16-create-asp-net-mvc-macros.aspx | crawl-002 | refinedweb | 1,781 | 55.74 |
The following
bit field
#include <stdio.h>
// A space optimized representation of date
struct date
{
// d has value between 1 and 31, so 5 bits
// are sufficient
unsigned int d: 5;
// m has value between 1 and 12, so 4 bits
// are sufficient
unsigned int m: 4;
unsigned int y;
};
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
So although the data size is reduced, the code size is increased.
In general, this is correct: it's a trade-off between more compact storage vs faster access.
For example, this is what my compiler produces for the
printf statement in your bitfield example:
movq _dt@GOTPCREL(%rip), %rax movzwl (%rax), %edx movl %edx, %esi andl $31, %esi ; -- extract the 5 bits representing day shrl $5, %edx ; -+ extract the four bits for the month andl $15, %edx ; / movl 4(%rax), %ecx ; -- year doesn't require any bit manipulation leaq L_.str.1(%rip), %rdi xorl %eax, %eax callq _printf
For comparison, the same code when
date is a simple
struct:
movq _dt@GOTPCREL(%rip), %rax movl (%rax), %esi ; -- day movl 4(%rax), %edx ; -- month movl 8(%rax), %ecx ; -- year leaq L_.str.1(%rip), %rdi xorl %eax, %eax callq _printf
All of this is of course compiler- and platform-specific. | https://codedump.io/share/GxJT61RSFgNV/1/how-does-c-compiler-handle-bit-field | CC-MAIN-2017-34 | refinedweb | 234 | 58.35 |
Hey, Scripting Guy! Do you have a script that will enable me to enumerate all the values in a registry key?
-- DG
Hey, DG. You know, this past weekend the Scripting Guy who writes this column went out to buy doughnuts, a process that took much longer than it should have. Why did it take so long just to buy doughnuts? Because the woman in line in front of him insisted on grilling the clerk about the nutritional value of each and every doughnut in the display case. “So,” she mused at one point. “What would you say is your healthiest option?”
Look, lady, you’re in a doughnut shop, for crying out loud; your healthiest option would be to turn tail and run. Healthiest option? Good heavens, just walking into that shop probably took a year or two off your life.
Sheesh.
Anyway, the doughnut store clerk – who was far more patient and understanding than the Scripting Guy who writes this column – recommended the Blueberry Cake. Just for the heck of it, the Scripting Guy who writes this column looked up the nutritional value of a Blueberry Cake doughnut versus a traditional glazed doughnut. (Did he do all that on company time? Um, he … doesn’t remember where, or how, he found this information ….)
Here’s what he came up with:
In other words, the Blueberry Cake is actually a less healthy option than the glazed doughnut. Does that mean that the clerk made an honest mistake, or was he trying to get the lady to eat a Blueberry Cake doughnut, hoping maybe that she would drop dead on the spot and then never come back in just to ask silly questions about which doughnut is the healthiest option? Beats us; all the Scripting Guy who writes this column wanted to do was get his dozen doughnuts (all cake doughnuts) and go home.
The truth is, if you’re looking for healthy options the doughnut shop is not the best place to look. Instead, the best place to look is the Script Center, where we have all sorts of healthy options, like a script that can enumerate all the values (and the values of those values) found in a registry key. Enjoy this in good health:
Const HKEY_CURRENT_USER = &H80000001 Const REG_SZ = 1 Const REG_EXPAND_SZ = 2 Const REG_BINARY = 3 Const REG_DWORD = 4 Const REG_MULTI_SZ = 7 strComputer = "." Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv") strKeyPath = "Software\Microsoft\Internet Explorer\Main" objRegistry.EnumValues HKEY_CURRENT_USER, strKeyPath, arrValueNames, arrValueTypes For i = 0 to UBound(arrValueNames) strText = arrValueNames(i) strValueName = arrValueNames(i) Select Case arrValueTypes(i) Case REG_SZ objRegistry.GetStringValue HKEY_CURRENT_USER,strKeyPath, strValueName,strValue strText = strText & ": " & strValue Case REG_DWORD objRegistry.GetDWORDValue HKEY_CURRENT_USER,strKeyPath, strValueName, intValue strText = strText & ": " & intValue Case REG_MULTI_SZ objRegistry.GetMultiStringValue HKEY_CURRENT_USER,strKeyPath, strValueName,arrValues strText = strText & ": " For Each strValue in arrValues strText = strText & " " & strValue Next Case REG_EXPAND_SZ objRegistry.GetExpandedStringValue HKEY_CURRENT_USER,strKeyPath, strValueName,strValue strText = strText & ": " & strValue Case REG_BINARY objRegistry.GetBinaryValue HKEY_CURRENT_USER,strKeyPath, strValueName,arrValues strText = strText & ": " For Each strValue in arrValues strText = strText & " " & strValue Next End Select Wscript.Echo strText Next
So how does that script, useful as it might be, make you healthy? Hey, what do we look like: doctors? We can’t explain how the script makes you healthy; it just does.
Or at least it doesn’t making you any less healthy.
As far as we know, anyway.
You know what? Let’s set all this medical mumbo-jumbo aside for a moment and see if we can figure out how this all works. As you can see, we start out by defining a whole bunch of constants. We’ll use HKEY_CURRENT_USER to tell the script which registry hive we want to work with; we’ll use the other constants to determine the data type of the individual registry values we run into. For example, in WMI a registry value that has a data type of 1 happens to be a value with the REG_SZ data type. Consequently, we assign the value 1 to the constant REG_SZ:
Const REG_SZ = 1
Seems reasonable – and healthy – enough, doesn’t it?
After defining all our constants we next connect to the WMI service on the local computer. And yes, we can run this very same script against a remote computer; all we have to do is assign the name of that remote machine to the variable strComputer:
strComputer = "."
While we’re at it you should take a closer look at our WMI connection string:
Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
Keep two things in mind when it comes to this connection string. First, note that we connect to the root\default namespace. That’s a little unusual; when writing WMI scripts we typically connect to the root\cimv2 namespace. Note also that we bind directly to the StdRegProv class; that’s because all the registry methods are “static” methods, which means that they operate against the class as a whole rather than individual instances of the class.
After we connect to the WMI service we use this line of code to assign the desired registry path (within the HKEY_CURRENT_USER hive) to a variable named strKeyPath:
strKeyPath = "Software\Microsoft\Internet Explorer\Main"
As soon as that’s done we can use the EnumValues method to retrieve a collection of all the registry values found within that registry key:
objRegistry.EnumValues HKEY_CURRENT_USER, strKeyPath, arrValueNames, arrValueTypes
This is the part where things start to get a little goofy. To begin with, we need to note that the EnumValues method will return the names and data types of all the values found in a given registry key. (But not the values found in any subkeys of that registry key; you’ll have to write a recursive function to do that.) For example, our sample script will tell us that the Main registry key includes a registry value named Anchor Underline, and that Anchor Underline has a data type of REG_SZ. That’s cool, but is Anchor Underline set to yes, or is Anchor Underline set to no? Well, that’s something EnumValues won’t tell us. We’re going to have to figure that out for ourselves.
But don’t despair; as long as we know the value names and data types figuring out the actual values isn’t too terribly difficult. (A little cumbersome, perhaps, but not too terribly difficult.) You might have noticed that when we called EnumValues we supplied the method with four parameters:
So what do we do with all the information returned by EnumValues? Well, to begin with, we set up a For Next loop that walks us through the array of value names (arrValueNames):
For i = 0 to UBound(arrValueNames)
Inside that loop, we take the name of the first registry value and assign it to a pair of variables:
strText = arrValueNames(i) strValueName = arrValueNames(i)
We’re going to use the variable strText to hold both the name of each registry value and – as soon as we’ve retrieved it – the value of each registry value. Meanwhile, we’ll use strValueName to represent this particular value when we try to retrieve, well, the value of that value.
Any time we need to read from the registry the Scripting Guys always use WMI rather than Windows Script Host. Why? Well, it’s not because WMI is easier to use; in fact, WMI is considerably more difficult to use than WSH. That’s because WMI requires you to use a different method for each registry data type. Have a value with the data type REG_SZ? Then you need to use the GetStringValue method. Have a value with the data type REG_DWORD? The you need to use the GetDWORDValue method. By contrast, WSH enables you to read any data type using a single method: RegRead.
So then why do we always use WMI rather than WSH? One reason and one reason only: WMI lets us read the registry off a remote computer. WSH doesn’t allow for that.
At any rate, the fact that, with WMI, different data types require different methods explains this next line of code:
Select Case arrValueTypes(i)
What we’re doing here is examining the data type of the first registry value. Let’s assume that this value has the data type REG_SZ (remember, we defined a constant named REG_SZ way back at the beginning of the script). In that case, we’re going to use the GetStringValue method to read the value from the registry and then add the value to the variable strText:
Case REG_SZ objRegistry.GetStringValue HKEY_CURRENT_USER,strKeyPath, strValueName,strValue strText = strText & ": " & strValue
Needless to say, if our value has a different data type then we’ll use a different method. You might note as well that both GetMultiStringValue and GetBinaryValue return data in the form of an array. That means we need to set up a For Each loop to get at all the values in that array:
Case REG_MULTI_SZ objRegistry.GetMultiStringValue HKEY_CURRENT_USER,strKeyPath, strValueName,arrValues strText = strText & ": " For Each strValue in arrValues strText = strText & " " & strValue Next
After echoing back the value of strText, it’s back to the top of the loop, where we repeat the process with the next name in the array arrValueNames. When all is said and done we should have output that looks something like this:
NoUpdateCheck: 1 NoJITSetup: 1 Disable Script Debugger: no Show_ChannelBand: No Anchor Underline: yes Cache_Update_Frequency: Once_Per_Session Display Inline Images: yes
Etc., etc.
That should do it, DG; let us know if you have any questions. Incidentally, did you notice that researchers have now decided that the old maxim that everyone should drink 8 glass of water each day no longer, well, no longer holds any water? According to an editorial in the Journal of the American Society for Nephrology (of course we subscribe to this; doesn’t everybody?) this misconception is due, in part, to a misreading of a 1945 report from the Food and Nutrition Board, which stated:
If you read all three sentences in that paragraph you’ll see that you can get most of your daily allowance of water just by eating. But, Americans being Americans, who could be bothered to read all three sentences? People had a tendency to read just the first sentence and ignore the rest. Thus was born the myth that people need to drink 8 glasses of water a day.
So why do we mention the 8-glasses-of-water-a-day thing? Well, health care practitioners were wrong when they said we needed 8 glasses of water a day. So does that mean that, instead of 8 glasses of water, we’re supposed to have 8 doughnuts a day? Let’s just say that the Scripting Guys are keeping our fingers crossed.
Well, OK: keeping our pudgy fingers crossed.
This script works fine to get all named values of a registry key, but what about the default key? Why does the EnumKeys method leave this value out? How do we account for it?
-MCDONAMW
Hi,
I am just not able to read values under "strKeyPath = "SOFTWAREMicrosoftWindowsCurrentVersionInstallerFolders" on windows 64 BIT OS??
Any specific reason for the same
When I run this on SoftwareMicrosoftWindows NTCurrentVersionWindows Messaging SubsystemProfiles365
I get:
—————————
Windows Script Host
—————————
Script: C:Usersjw.CSDocumentsScriptsTestReg.vbs
Line: 16
Char: 1
Error: Type mismatch: 'UBound'
Code: 800A000D
Source: Microsoft VBScript runtime error
—————————
OK
—————————
Please help | https://blogs.technet.microsoft.com/heyscriptingguy/2008/04/09/hey-scripting-guy-how-can-i-retrieve-all-the-values-in-a-registry-key/ | CC-MAIN-2018-17 | refinedweb | 1,892 | 60.45 |
Technical Articles
Fundamental Library for Angular version 0.31 is out
It took us some time to release Fundamental NGX version 0.31. This is the biggest release yet by far 🤩. It includes ~20 new features and components and more than 200 improvements, fixes, and documentation updates.
Almost all of the new staff worths special attention and more details. I will try to list them all without going into too much details in this blog post. I hope to have time to write separate posts for all them soon.
- Moment Date Time Adapter – the fundamental date picker, time picker, date time picker components rely on provided date-time implementation and date-time formats. These components could be used with FdDatetimeAdapter, based on the JavaScript’s native Date object, but one of the biggest shortcomings of the native Date object is the inability to set the parse format. As an alternative could be the MomentDateAdapter or a custom DateAdapter that works with the formatting/parsing library of your choice. This is coming as a separate npm package (@fundamental-ngx/moment-adapter)
- Platform Table Features (custom column width and resizing) – we didn’t stop adding new features to the platform table and in this release we focused on resizing and allowing custom column width
- Platform Approval Flow Phase 3 and 4 features – ability to add the first and parallel approvers; improve editing approvers, ability to disable setting due date; add functionality to have multiple final nodes; while adding a new node as parallel add the ability to remain parallel to the current node or to the next serial node.
- Form Generator – it is a component that generates forms based on data. It supports form layout with multiple responsive forms; automatic component rendering without predefines template; ability to extend the default set of controls; dynamic validators. The component reduces the boiler-plate code.
- Wizard Generator – another component that allows you to create a full page wizard with minimal code. It provides ability to dynamically generate Wizard without any user-provided templates. Steps are dynamically rendered based on steps object input.
- Responsive Popover for mobile mode. Popover Mobile Mode can be configured globally by providing
MOBILE_MODE_CONFIGtoken
- Date Time Formatter Pipes -Introduces 3 new pipes for formatting dates based up on the dates provided to
DATE_TIME_FORMATSby the developer.
dateFormatPipeformats dates
dateTimeFormatPipeformats datetimes
dateFromNowPipecan potentially be used to display how much time has passed since a date – this is currently not implemented with the default DATE_TIME_FORMATS/FdDateTimeAdapter but will be easy to add to the adapter when using moment.js or some similar library.
- Core Package Split – split core library into multiple sub-packages, while still keeping legacy way of imports. Recommended way of importing files from the core library now is following:
import {DialogModule, DialogService} from '@fundamental-ngx/core/dialog';
Happy hacking!
The full release notes can be found here.
Stay tuned for more updates. Want to read more blog posts about Fundamental Library? Check these out or visit out brand new Topic Page
Feel free to raise any questions or try our libraries in case you didn’t have a chance.
Be the first to leave a comment
You must be Logged on to comment or reply to a post. | https://blogs.sap.com/2021/08/16/fundamental-library-for-angular-version-0.31-is-out/ | CC-MAIN-2021-39 | refinedweb | 536 | 52.7 |
On Tue, 25 Mar 2003 08:45:56 -0800, "Luck, Tony" <tony.luck@intel.com> wrote: >>>>>> On Sat, 22 Mar 2003 15:12:55 +1100, Keith Owens <kaos@sgi.com> = >said: > > Keith> arch/ia64/kernel/mca.c:ia64_mca_rendez_int_handler has > Keith> #ifdef CONFIG_SMP > Keith> cpu =3D cpu_logical_id(hard_smp_processor_id()); > Keith> #endif > Keith> ia64_mc_info.imi_rendez_checkin[cpu] =3D = >IA64_MCA_RENDEZ_CHECKIN_DONE; > > Keith> All the other code that runs imi_rendez_checkin does so using = >logical > Keith> cpu numbers. Why does ia64_mca_rendez_int_handler use that = >convoluted > Keith> expression instead of the simpler > Keith> cpu =3D smp_processor_id(); > > David> I don't know either. Perhaps the original author remembers = >(Jenna or > David> Tony, perhaps?). > >This code predates me. I checked with Jenna and she says that it's = >before >her time too. > ><speculation> >That convoluted expression avoids use of the per-cpu mapping, but I = >can't see >why we'd be scared to use that here, and not be paranoid elsewhere. How = >was >smp_processor_id() implemented far back in days of 2.4.0 and before? ></speculation> At one time there was confusion between which arrays used the logical cpu number in smp_processor_id() and which arrays used the hardware cpu number. This is probably a holdover from that period. Index: 20.5/arch/ia64/kernel/mca.c --- 20.5/arch/ia64/kernel/mca.c Wed, 11 Dec 2002 20:58:53 +1100 kaos (linux-2.4/s/c/5_mca.c 1.1.3.2.3.1.1.1.1.3 644) +++ 20.5(w)/arch/ia64/kernel/mca.c Wed, 26 Mar 2003 08:14:29 +1100 kaos (linux-2.4/s/c/5_mca.c 1.1.3.2.3.1.1.1.1.3 644) @@ -640,13 +640,10 @@ ia64_mca_wakeup_all(void) void ia64_mca_rendez_int_handler(int rendez_irq, void *arg, struct pt_regs *ptregs) { - int flags, cpu = 0; + int flags, cpu = smp_processor_id(); /* Mask all interrupts */ save_and_cli(flags); -#ifdef CONFIG_SMP - cpu = cpu_logical_id(hard_smp_processor_id()); -#endif ia64_mc_info.imi_rendez_checkin[cpu] = IA64_MCA_RENDEZ_CHECKIN_DONE; /* Register with the SAL monarch that the slave has * reached SALReceived on Tue Mar 25 13:16:00 2003
This archive was generated by hypermail 2.1.8 : 2005-08-02 09:20:12 EST | http://www.gelato.unsw.edu.au/archives/linux-ia64/0303/4997.html | CC-MAIN-2020-16 | refinedweb | 347 | 50.12 |
Best Practices: Transfer NPM to New Web Servermdhtbm Nov 1, 2012 10:53 AM
I am in the process of upgrading our NPM installation (NPM 10.3.1, APM 4.2, SEUM 1.5.0, NTA 3.7) to a new web server. The database and database server will remain the same. While I understand the general steps to complete this, I'm looking for advice form folks who have actually done this kind of upgrade before on best practices and things to avoid. I am discovering that it is probably best to only transfer web servers running the same component versions and do component upgrades as a separate step.My plan is to install all the components on the new web server, create a test database using a backup of the production database and point the new server at it. Once I've verified that everything is working the way I want, I'll schedule an outage, shutdown the old server, change the dns alias and ip address of the new server to match the old one, and point the production database at the new server. I assume that as long as my component versions are the same I can do it this way rather than have a longer outage where I stop the old server, move the database to the new server, and install and point the applications at the database one by one. Thoughts/Advice?
Matthew
Re: Best Practices: Transfer NPM to New Web ServerLeon Adato
Nov 1, 2012 1:29 PM (in response to mdhtbm)
I want to clarify which servers you are using before forging ahead:
The database (ie MS-SQL schema, tables, etc run on the database server
The polling engine performs the requests for data from the nodes
the web server displays the SolarWinds portal
All 3 can be running on the same machine, or you can actually separate all 3 functions (a separate db server, a separate polling engine, and a separate web server)
It sounds like you are separating two of the 3 - you have one server for MS-SQL, and another server that is the polling engine and the web server. Is that correct? I'm going to offer a few thoughts under the presumption that I'm on the right track.
You are right that your new servers should have the same versions as the old ones. It's just nice to use like-for-like.
IF you didn't customize your SolarWinds website in any way (messing with the CSS files, the ASP files, etc) then you don't really have to "migrate" anything. The Solarwinds installation on the new server (polling engine and web server) will take care of all of it for you. Just run the install and you'll have a web instance running on port 80 (or whatever you choose) and it will show your solarwinds screens. Custom views, etc will all carry over.
What you WILL need to migrate are any custom reports you created. Those are text files located in (using the default installation location) C:\program files(x86)\solarwinds\orion\reports. You only have to migrate your custom reports, not the standard ones.
Let me know where (or if) I've gotten anything wrong with my assumptions about your situation.
Re: Best Practices: Transfer NPM to New Web Servernetlogix
Nov 1, 2012 2:19 PM (in response to Leon Adato)
when you migrate server, if you change IPs, make sure you update all your access-lists and your SNMP agents to allow the new IP
if you change the hostname (or IP), make sure you update the engines table " Update Engines Set ServerName = '<NewServerName>', IP = '<NEW_IP>' where ServerName = '<OLD_Server_Name>' " before you connect the new server.
Re: Best Practices: Transfer NPM to New Web Servermdhtbm Nov 1, 2012 4:36 PM (in response to Leon Adato)
Yes, Adatole, you are correct. We have a separate database server but the polling engine and web server are on the same server.
I'm running into a lot of problems at least with the testing phase of this project. I'm using a clone of the production database on the new server for testing purposes and had no trouble installing NPM and APM. However, when I try to install SEUM, something in the installation is triggering corruption in the test database. After SEUM 1.5 is installed, Orion web console no longer recognizes the trial licenses of NPM and APM. SEUM itself doesn't even show up in the license summary and when I click on the Transactions tab I get an error "SEUM License Verification Failed". Orion also gives me a tab for Netflow even though it isn't installed and also doesn’t show up in the license summary. Additionally, I get rendering errors on each node page for components such as Applications and Top XX Components by Statistic Data which didn't show up before. Basically something in the SEUM 1.5 installation is making the test database revert back to matching what is in production, at least in terms of components installed, licenses and versions.
After that happened I uninstalled SEUM and everything was back the way it should be - the web console shows trials for NPM and APM and nothing else. I then tried to install NTM 3.7 and that install broke my web server, I get this error:
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name 'Reporting' does not exist in the namespace 'SolarWinds.Netflow.Web' (are you missing an assembly reference?)
I tried restarting all services and uninstalling/reinstalling without success.
Re: Best Practices: Transfer NPM to New Web Servermdhtbm Nov 6, 2012 11:30 AM (in response to Leon Adato)
I migrated my custom reports. Does this automatically migrate the report scheduler information? If not, how can the report scheduler entries be migrated to a new server?
Re: Best Practices: Transfer NPM to New Web ServerLeon Adato
Nov 6, 2012 2:57 PM (in response to mdhtbm)
No it doesn't (migrate the schedules). The report scheduler is actually a (fairly klunky) interface to Windows scheduler. So unless you know a way to export/import windows scheduler jobs there isn't a migration path.
I'm not saying there's NOT a Windows scheduler export/import option. I just haven't ever looked for it.
Re: Best Practices: Transfer NPM to New Web Servermdhtbm Nov 7, 2012 10:56 AM (in response to Leon Adato)
I manually recreated our scheduled reports. I can view the reports just fine by clicking on the URL in the report scheduler screen, and according to the Windows Task Manager the reports are running successfully; however, no one is receiving the e-mails the reports are supposed to be generating. The e-mail server settings are correct and in fact are the exact same settings that we are using to send our alerts which are working just fine. Do you know what could cause just the report scheduler e-mails not to work or how I could troubleshoot this?
Re: Best Practices: Transfer NPM to New Web ServerLeon Adato
Nov 7, 2012 11:42 AM (in response to mdhtbm)
The next test I would make is to re-create a job through the actual report scheduler and see if it works. if it does, then something is missing in your manual recreation. If it doesn't work, then something is broken overall.
Re: Best Practices: Transfer NPM to New Web ServerPavelSrot Nov 8, 2012 3:40 AM (in response to mdhtbm)
I would suggest try to install Wireshark or any other packet sniffer and try to catch communication between computer where run Orion (Report Scheduler) and your SMTP server. In report scheduler try to execute job manually (right mouse button and from popup menu select Run Selected Job Now). And consequently try to examine if you will see some communication between your computer and SMTP email server.
Re: Best Practices: Transfer NPM to New Web Serverharrijs Nov 1, 2012 2:23 PM (in response to mdhtbm)
***DOH Beat to the punch by 3 minutes***
I know that that this doesn't apply to your particular scenario, but it might be food for thought for anyone who isn't responsible for their security devices. We recently migrated our server to new hardware and also migrated to a new IP address. One thing that I failed to calculate in this process was the neccessity to touch all of our firewalls to modify NAT statements and ACLs allowing the polling server access to the monitored network resources.
This caused our upgrade to be longer than anticipated, but no real problems. | https://thwack.solarwinds.com/thread/52637 | CC-MAIN-2018-39 | refinedweb | 1,475 | 58.21 |
The 1st row is the prices for the 1st house, we can change the matrix to present sum of prices from the 2nd row. i.e, the costs[1][0] represent minimum price to paint the second house red plus the 1st house.
public class Solution { public int minCost(int[][] costs) { if(costs==null||costs.length==0){ return 0; } for(int i=1; i<costs.length; i++){ costs[i][0] += Math.min(costs[i-1][1],costs[i-1][2]); costs[i][1] += Math.min(costs[i-1][0],costs[i-1][2]); costs[i][2] += Math.min(costs[i-1][1],costs[i-1][0]); } int n = costs.length-1; return Math.min(Math.min(costs[n][0], costs[n][1]), costs[n][2]); }
}
Hi, yao9208. Great code! Very nice idea to give
costs[i][j] a new meaning and at the mean time save the usage of additional spaces.
Well, personally I would like to keep
costs unmodified. I rewrite the code in C++, a little verbose than yours :-)
class Solution { public: int minCost(vector<vector<int>>& costs) { if (costs.empty()) return 0; int n = costs.size(), r = 0, g = 0, b = 0; for (int i = 0; i < n; i++) { int rr = r, bb = b, gg = g; r = costs[i][0] + min(bb, gg); b = costs[i][1] + min(rr, gg); g = costs[i][2] + min(rr, bb); } return min(r, min(b, g)); } };
r/
b/
g in the
i-th loop means the minimum costs to paint the
i-th house in red/blue/green respectively plus painting the previous houses. The time and space complexities are still of
O(n) and
O(1).
It is nicer if you take "int n = costs.length-1;" before for loop and in the for loop use it as "i <= n;" :)
jianchao.li.fighter's answer seems better, since your code modifies the original inputs.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/21311/simple-java-dp-solution | CC-MAIN-2017-34 | refinedweb | 331 | 76.01 |
Opened 10 years ago
Closed 7 years ago
Last modified 6 years ago
#5612 closed (fixed)
Signals for login / logout
Description
A small patch that adds signals for login / logout events. The signal passes on the request. I use it to clean up session-data.
Attachments (5)
Change History (32)
Changed 10 years ago by
comment:1 Changed 10 years ago by
Changed 10 years ago by
Self contained (moved signals to contrib.auth.signals)
comment:2 Changed 10 years ago by
comment:3 Changed 10 years ago by
Marking as wont fix. Signal dispatching is slow. This should be accomplished using the
daily_cleanup.py
found in
django/bin
. If that doesn't suit you then rewrite parts of
django.contrib.auth
or maybe through a custom auth backend. Please reopen with better use cases. I just don't see signals being a solution to really any use case for something like this.
comment:4 Changed 10 years ago by
Signals are slow, but login and logout events would occur so rarely that signal performance shouldn't be a consideration here.
comment:5 Changed 10 years ago by
Another use case could be to log all login/outs in a single place (iso /admin/, /accounts/registration and possibly other locations or rewriting bits of django core). To alleviate the worries about speed, it could be made entirely optional and off by default.
comment:6 Changed 10 years ago by
Alright, I am going to re-open this ticket to get some exposure by the core devs. There are a few use cases for this and having an optional on and off switch would be nice to alleviate any performance issues.
comment:7 Changed 10 years ago by
comment:8 Changed 9 years ago by
Changed 8 years ago by
comment:9 Changed 8 years ago by
Updated patch to work with newer version, changed behavior to trigger login signal before updating last_login because i need to log time between logins.
comment:10 Changed 8 years ago by
comment:11 Changed 8 years ago by
comment:12 Changed 8 years ago by
another use case: demo users - profiles, passwords and other data needs to be reset on login/logout.
comment:13 Changed 8 years ago by
I'd love to see this one - we'd like to hook into the login process and are considering wrapping the default views. What's the status on this one?
comment:14 Changed 7 years ago by
New patch with docs & tests. Also moved the update for last_login to a signal which allows for it to be disconnected if someone wanted to.
Changed 7 years ago by
comment:15 Changed 7 years ago by
comment:16 Changed 7 years ago by
Another use case: with signal you could add a message to the user informing her that she was successfully logged in or out and redirect her to the page she wanted to go in the first place and not to the default login page. It is a nice information to users that they know what is happening behind the scenes.
comment:17 Changed 7 years ago by
I'd love to see this as in my app I'm currently wrapping the default login view to store login attempts. So preferably a hook for a successful login and another for a failed attempt.
I tried using a custom authentication back end to handle failed login attempts but those only get username/password - need the http request to dig out IP...
comment:18 Changed 7 years ago by
mitar: using signals doesn't just make that possible. In fact, it confuses the issue more: what if you have two conflicting responses from signal listeners?
drizzo4shizzo: that's an interesting idea - I don't think it's part of this primary ticket though so perhaps you should open a new ticket for that (and crosslink it to here)
comment:19 Changed 7 years ago by
I do not understand why it would not be possible. I am quite happily using such views:
def login(request, *args, **kwargs): res = login_view(request, *args, **kwargs) if request.user.is_authenticated(): signals.user_login.send(sender=login, request=request, user=request.user) return res
def logout(request, *args, **kwargs): user = request.user res = logout_view(request, *args, **kwargs) signals.user_logout.send(sender=logout_redirect, request=request, user=user) return res
comment:20 Changed 7 years ago by
And then:
def user_login_message(request, user, **kwargs): messages.success(request, _("You have successfully logged in."), fail_silently=True) user_login.connect(user_login_message) def user_logout_message(request, user, **kwargs): messages.success(request, _("You have successfully logged out."), fail_silently=True) user_logout.connect(user_logout_message)
comment:21 Changed 7 years ago by
Right, I get that adding a message would be a useful use of the signal.
It's was the "redirect her to the page she wanted to go in the first place and not the default login page" statement that I was referring to. It has nothing to do with signal listeners, which is what this ticket was about ;)
comment:22 Changed 7 years ago by
Ah, yes. This is something else. I pass
next parameter to login view so that user is redirected back to where it started the login process. So I do not use signals for redirecting. But once you do redirecting it is nice to tell user that login was successful, because otherwise just some small part of the page changes (like that username is written somewhere instead of "login" link). So messages are useful to tell the user this. And having signals then makes this really easy to do.
comment:23 Changed 7 years ago by
Speed isn't a concern for signals any more, and it's an obvious place to be raising a signal. Accepting.
Changed 7 years ago by
comment:24 Changed 7 years ago by
comment:25 Changed 7 years ago by
comment:26 Changed 7 years ago by
comment:27 Changed 6 years ago by
Milestone 1.3 deleted
I believe the contrib modules are supposed to be self-contained, so should the signal objects should probably be within contrib.auth rather than core. | https://code.djangoproject.com/ticket/5612 | CC-MAIN-2017-43 | refinedweb | 1,024 | 61.77 |
In following example we will discuss about Array in Java. Array is a collection of data of same datatype.We can use it to store Integer, Boolean, String object. We can store only primitive data in array. We have contained multiples value of the same type and we can store the multiple value in memory at fixed size. We can use multiple type array. It can be used in Java, C++, PHP and any other programming languages.
We can use array in program as:
There are many syntax Declaration of an array:-
Advantages of array:
Disadvantages of Array:
public class ArrayExample { public static void main(String[] args) { int num[] = new int[7]; for (int i=0;i<7;i++){ num[i]=i+1; } for (int i=0;i<7;i++){ System.out.println("array["+i+"] = "+num[i]); } System.out.println("Length of Array = "+num.length); } }
Liked it! Share this Tutorial
Ask Questions? Discuss: Array in java
Post your Comment | http://www.roseindia.net/java/beginners/array-in-java.shtml | CC-MAIN-2014-10 | refinedweb | 159 | 60.82 |
.
You might get a good start on a new game idea, too!" (like a level or area).
- Tile-based refers to the method of building levels in a game. The code will layout tiles in specific locations to cover the intended area.
To get even more basic, I'll put it like this:
A tile-based game lays out tiles in order to create each level.
In reference to the common tile types - rectangular and isometric - we will use rectangular tiles in this article for their simplicity. If you do decide to try out isometric levels some day, there is additional math involved to make it work. (Once you're done here, check out this great primer on creating isometric worlds.)
There are some pretty cool benefits that you get from using a tile engine. The most apparent perk is that you won't need to create massive images by hand for each individual level. This will cut down on development time and cut down on file sizes. Having 50 1280x768px images for a 50-level game vs having one image with 100 tiles makes a huge difference.
Another side-effect is that locating things on your map using code becomes a little easier. Instead of checking things like collision based on an exact pixel, you can use a quick and easy formula to determine which tile you need to access. (I'll go over that a bit later.)
Finding or Making Your Own Tiles
The first thing you will need when building your tile engine is a set of tiles. You have two options: use someone else's tiles, or make your own.
If you decide to use tiles that have already been made, you can find freely available art all over the web. The downside to this is that the art wasn't made specifically for your game. On the other hand, if you're just prototyping or trying to learn a new concept, free tiles will do the trick.
Where to Find Your Tiles
There are quite a few resources out there for free and open source art. Here are a few places to start your search:
Those three links should give you more than enough places to find some decent tiles for your prototypes. Before you go crazy grabbing up everything you find, make sure that you understand what license everything is covered under and what restrictions they come with. Many licences will allow you to use the art freely and for commercial use, but they might require attribution.
For this tutorial, I used some tiles from a The Open Game Art Bundle for platformers. You can download my scaled-down versions or the originals.
How to Make Your Own Tiles
If you haven't taken the plunge of making art for your games yet, it might be a little intimidating. Luckily there are some amazing and simple pieces of software that get you into the thick of it so you can start practicing.
Many developers start out with pixel art for their games and here are a few great tools for just that:
- Aseprite
- Pyxel Edit
- Graphics Gale
- Pixen for the Mac users
These are some of the most popular programs for making pixel art. If you want something a bit more powerful, GIMP is an excellent option. You can also do some vector art with Inkscape and follow some amazing tutorials over at 2D Game Art For Programmers.
Once you grab the software you can start experimenting with making your own tiles. Since this tutorial is meant to show you how to create your tile map engine I won't go into too much detail about making the tiles themselves, but there is one thing to always keep in mind:
Make sure your tiles fit together seamlessly, and add some variation to keep them interesting.
If your tiles show obvious lines between them when put together, your game won't look very nice. Make sure you put some time into creating a nice "puzzle" of tiles by making them seamless and adding some variation.
Writing the Code to Display Tiles
Now we've got all of that art stuff out of the way, we can dive into the code to put your newly acquired (or created) tiles on screen.
How to Display a Single Tile on Screen
Let's start with the very basic task of displaying a single tile on screen. Make sure that your tiles are all the same size and saved in separate image files (we'll talk more about sprite sheets later).
Once you have the tiles in your assets folder of your project, you can write up a very simple
Tile class. Here is an example in Haxe:
import flash.display.Sprite; import flash.display.Bitmap; import openfl.Assets; class Tile extends Sprite { private var image:Bitmap; public function new() { super(); image = new Bitmap(Assets.getBitmapData("assets/grassLeftBlock.png")); addChild(image); } }
Since all we are doing now is putting a single tile on the screen, the only thing that the class does is import the tile image from the
assets folder and add it as a child to the object. This class will probably vary greatly based on the programming language you use, but you should be able to easily find a guide on how to display an image on the screen.
Now that we have a
Tile class, we need to create an instance of a
Tile and add it to our Main class:
import flash.display.Sprite; import flash.events.Event; import flash.Lib; class Main extends Sprite { public function new() { super(); var tile = new Tile(); addChild(tile); } public static function main() { Lib.current.addChild(new Main()); } }
The
Main class creates a new
Tile when the constructor (the
new() function, called when the game starts) is called, and adds it to the display list.
When the game is run, the
main() function will also be called, and a new
Main object will be added to the stage. You should now have your tile appearing at the very top left of the screen. So far, so good.
Tip: If none of that makes sense - don't worry! It's just standard boilerplate Haxe code. The key thing to understand is that this creates a
Tile object and adds it to the screen.
Using Arrays to Lay Out an Entire Screen of Tiles
The next step is to find a way to fill the entire screen with tiles. One of the easiest ways to do this is to fill up an array with integers that each represent a tile ID. Then you can iterate through the array to decide which tile to display and where to display it.
You have the option of using a typical array or using a 2-dimensional array. In case you aren't familiar with 2D arrays, it's basically a single array that is filled with multiple arrays. Most languages will denote this as
nameOfArray[x][y] where
x and
y are indices for accessing a single element.
Since
x and
y are also used for screen coordinates, it might make sense to use
x and
y as coordinates for our tiles. The trick with 2D arrays is understanding how the integers are organized. You might have to reverse the
y and
x when iterating through the arrays (example below).
private var exampleArr = [ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ];
Notice that in this implementation, the "0th" element in the array is itself an array, of five integers. This would mean that you access each element with
y first, then
x. If you try to access
exampleArr[1][0], you would be accessing the sixth tile.
If you don't quite understand how the 2D arrays work right now, don't worry. For this tutorial I will use a normal array in order to keep things simple and to make things easier to visualize:
private var exampleArr = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
The above example shows how a normal array can be a little bit simpler. We can visualize exactly where the tile will be and all we have to do is use a simple formula (don't worry, it's coming!) to get the tile we want.
Now let's write up some code to create our array and fill it with ones. The number one will be the ID that represents our first tile.
First we need to create a variable inside of our Main class to hold our array:
private var map:Array<Int>;
This might look a little strange, so I'll break it down for you.
The variable name is map and I've given it a very specific type:
Array. The
<Int> portion just tells our program that the array will only hold integers. Arrays can hold just about any type that you want, so if you are using something else to identify your tiles, feel free to change the parameter here.
Next we have to add some code to our
Main class's constructor (remember, this is the
new() function) so that we can create an instance of our map:
map = new Array<Int>();
This line will create an empty array that we can soon fill with our ones for testing it out. First, let's define some values that will help us with our math:
public static var TILE_WIDTH = 60; public static var TILE_HEIGHT = 60; public static var SCREEN_WIDTH = 600; public static var SCREEN_HEIGHT = 360;
I've made these values
public static because this will give us access to them from anywhere in our program (via
Main.Tile_WIDTH and so on). Also, you might have noticed that dividing
SCREEN_WIDTH by
TILE_WIDTH gives us
10 and dividing
SCREEN_HEIGHT by
TILE_HEIGHT gives us
6. Those two numbers will be used to decide how many integers to store in our array.
var w = Std.int(SCREEN_WIDTH / TILE_WIDTH); var h = Std.int(SCREEN_HEIGHT / TILE_HEIGHT); for (i in 0...w * h) { map[i] = 1 }
In this block of code, we assign
10 and
6 to
w and
h, like I mentioned above. Then we need to jump into a
for loop to create an array that can fit
10 * 6 integers. This will account for enough tiles to fill the entire screen.
Now we have our basic map built, but how are we going to tell the tiles to get into their proper place? For that we need to go back to the
Tile class and create a function that will allow us to move tiles around at will:
public function setLoc(x:Int, y:Int) { image.x = x * Main.TILE_WIDTH; image.y = y * Main.TILE_HEIGHT; }
When we call the
setLoc() function, we pass in the
x and
y coordinates according to our map class (formula coming soon, I promise!). The function takes those values and translates them into pixel coordinates by multiplying them by
TILE_WIDTH and
TILE_HEIGHT, respectively.
The only thing left to do in order to get our tiles on screen is to tell our
Main class to create the tiles and put them in place based on their locations within the map. Let's go back to
Main and implement that:
for (i in 0...map.length) { var tile = new Tile(); var x = i % w; var y = Math.floor(i / w); tile.setLoc(x, y); addChild(tile); }
Oh yeah! That's right, we now have a screen full of tiles. Let's break down what is happening above.
The Formula
The formula that I keep mentioning is finally here.
We calculate
x by taking the modulus (
%) of
i and
w (which is 10, remember).
The modulus is just the remainder after integer division: \(14 \div 3 = 4 \text{ remainder } 2\) so \(14 \text{ modulus } 3 = 2\).
We use this because we want our value of
x to reset back to
0 at the start of each row, so we draw the respective tile on the far left:
As for
y, we take the
floor() of
i / w (that is, we round that result down) because we only want
y to increase once we have reached the end of each row and moved down one level:
Math.floor()when dividing integers; Haxe just handles integer division differently. If you are using a language that does integer division, you can just use
i / w(assuming they are both integers).
Lastly, I wanted to mention a little bit about scrolling levels. Usually you won't be creating levels that fit perfectly within your viewport. Your maps will probably be much larger than the screen and you don't want to continue drawing images that the player won't be able to see. With some quick and easy math, you should be able to calculate which tiles should be on screen and which tiles to avoid drawing.
For example: Your screen size is 500x500, your tiles are 100x100, and your world size is 1000x1000. You would simply need to do a quick check before drawing tiles to find out which tiles are on screen. Using the location of your viewport - let's say 400x500 - you would only need to draw tiles from rows 4 to 9 and columns 5 to 10. You can get those numbers by dividing the location by the tile size, then offsetting those values with the screen size divided by the tile size. Simple.
It might not look like much yet since all the tiles are the same, but the foundation is almost there. The only things left to do are to create different types of tiles and design our map so that the they line up and create something nice.
Editing Tile Layouts for Different Levels
All right, we now have a map that is full of ones which covers the screen. By this point you should have more than one tile type, which means that we have to change our
Tile constructor to account for that:
public function new(id:Int) { super(); switch(id) { case 1: image = new Bitmap(Assets.getBitmapData("assets/grassLeftBlock.png")); case 2: image = new Bitmap(Assets.getBitmapData("assets/grassCenterBlock.png")); case 3: image = new Bitmap(Assets.getBitmapData("assets/grassRightBlock.png")); case 4: image = new Bitmap(Assets.getBitmapData("assets/goldBlock.png")); case 5: image = new Bitmap(Assets.getBitmapData("assets/globe.png")); case 6: image = new Bitmap(Assets.getBitmapData("assets/mushroom.png")); } addChild(image); }
Since I used six different tiles for my map, I needed a
switch statement that covers the numbers one through six. You'll notice that the constructor now takes an integer as a parameter so we know what kind of tile to create.
Now, we have to go back to our
Main constructor and fix the tile creation in our
for loop:
for (i in 0...map.length) { var tile = new Tile(map[i]); var x = i % w; var y = Math.floor(i / w); tile.setLoc(x, y); addChild(tile); }
All we had to do was pass the
map[i] to the
Tile constructor in order to make it work again. If you try to run without passing an integer to
Tile, it will give you some errors.
Almost everything is in place, but now we need a way to design maps instead of just filling them with random tiles. First, remove the
for loop in the
Main constructor that sets each element to one. Then we can create our own map by hand: ];
If you format the array like I have above, you can easily see how our tiles will be organized. You can also just enter the array as one long line of numbers, but the former is nice because you can see 10 across and 6 down.
When you try to run the program now, you should be getting some null pointer exceptions. The problem is that we are using zeros in our map and our
Tile class doesn't know what to do with a zero. First, we'll fix the constructor by adding in a check before we add the image child:
if (image != null) addChild(image);
This quick check makes sure that we aren't adding any null children to the
Tile objects we create. The last change for this class is the
setLoc() function. Right now we are trying to set the
x and
y values for a variable that hasn't been initialized.
Let's add another quick check:
public function setLoc(x:Int, y:Int) { if (image != null) { image.x = x * Main.TILE_WIDTH; image.y = y * Main.TILE_HEIGHT; } }
With those two simple fixes in place, and the tiles that I provided above, you should be able to run the game and see a simple platformer level. Since we left 0 as a "non-tile", we can leave it transparent (empty). If you want to spice up the level, you can put a background in before you lay out the tiles; I just added a light blue gradient to look like a sky in the background.
That is pretty much everything you need to set up a simple way to edit your levels. Try to experiment a little with the array and see what designs you can come up with for other levels.
Third-Party Software for Designing Levels
Once you've got the basics down, you might consider using some other tools to help you design levels rapidly and see what they look like before you toss them into the game. One option is to create your own level editor. The alternative is to grab some software that is available for free to use. The two popular tools are Tiled Map Editor and Ogmo Editor. They both make level editing much easier with multiple export options.
You Just Created a Tile-Based Engine!
Now you know what a tile-based game is, how to get some tiles to use for your levels, and how to get your hands dirty and write the code for your engine, and you can even do some basic level editing with a simple array. Just remember that this is only the beginning; there is a lot of experimenting you can do to make an even better engine.
Also, I've provided the source files for you to check out. Here's what the final SWF looks like:
...and here, again, is the array that it's generated from: ];
Don't Stop Here!
Your next task is to do some research and try out some new things to improve what you made here. Sprite sheets are a great way to improve performance and make life a bit easier. The trick is to get some solid code laid out for reading from a sprite sheet so that your game doesn't have to read each image individually.
You should also start practising your art skills by making a few tilesets of your own. That way you can get the right art for your future games.
As always, leave some comments below about how your engine is working for you - and maybe even some demos so we can try out your next tile game.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://gamedevelopment.tutsplus.com/tutorials/an-introduction-to-creating-a-tile-map-engine--gamedev-10900 | CC-MAIN-2019-51 | refinedweb | 3,234 | 78.38 |
Is there a way to generate a sine wave with the IDAC on Happy, Happy Gecko does have all of the requisite features needed to generate a sine wave (or any other waveform) under software control.
Regardless of the kind of digital-to-analog converter used, any kind of waveform generation requires the presence of a time base to sequence the analog values generated. The IDAC has no such capability, so one of the EFM32 timers must be used. Furthermore, unless the CPU can dedicate itself to this purpose, a hardware assistance mechanism, like a queue or DMA, is needed to periodically update the analog output while the processor performs other tasks. The DMA on Happy Gecko can do this.
Some consideration of how the IDAC differs from the EFM32 DAC is also necessary. The DAC is a ratiometric converter, which means that the value written into the Channel Data Register (DACn_CHxDATA) generates an analog voltage that is, subject to various error contributions, proportional to the selected reference.
The IDAC is also a ratiometric converter, but it differs from the DAC in that the value written into the STEPSEL field of the Current Programming Register (IDAC_CURPROG) permits sinking or sourcing of a current that is proportional to the selected reference. Compared to the DAC, which has a resolution of 12 bits, the Step Size Select field of the IDAC_CURPROG register is only 5 bits wide.
A 5-bit converter might seem rather limited, but for the purpose of waveform generation, it provides ample resolution when allowing 5 µs for the output to settle. Using this as a limiting factor, the IDAC can output a 32-entry wave table (twice that used for the hardware sine wave generator in the DAC) at a respectable 1 ÷ (32 steps × 5 µs/per step) = 6.25 kHz.
Knowing these parameters and the capabilities of the IDAC, the outline for wave generation software takes shape as follows:
The example Simplicity Studio project attached to this article runs on the Happy.
First, it's not sufficient to write raw wave table values to the IDAC Current Programming Register. The STEPSEL field occupies bits [12:8] of the register, so the raw values must be shifted left to reflect this. In addition, the output current range of the IDAC is set by the RANGESEL field in bits [1:0]. Because all peripheral register writes must be 32 bits, each wave table entry written to IDACn_CURPROG must include the output range along with the step value. All of this is handled in cosine_table.c as shown below:
#include "em_idac.h"
#define IDAC_RANGE IDAC_CURPROG_RANGESEL_RANGE3
#define COSINE_TABLE_SIZE 32
const uint32_t cosine_table_size = COSINE_TABLE_SIZE;
const uint16_t cosine_table[COSINE_TABLE_SIZE] = {
((31 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((30 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((29 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((28 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((26 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((24 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((21 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((18 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((16 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((13 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((10 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((07 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((05 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((03 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((02 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((01 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((00 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((01 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((02 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((03 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((05 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((07 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((10 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((13 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((16 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((18 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((21 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((24 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((26 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((28 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((29 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
((30 << _IDAC_CURPROG_STEPSEL_SHIFT) | IDAC_RANGE),
};
Second, note the use of ping-pong instead of basic DMA to service the IDAC. The purpose of ping-pong DMA is to keep a constant stream of data moving between a peripheral and memory by allowing the CPU to periodically step in and update the DMA with the next set of transfers.
As implemented on EFM32 devices, the DMA uses primary and alternate descriptors in ping-pong mode that contain information about the transfers to be processed. When all data specified by the primary descriptor is transferred, work begins on the alternate descriptor's transfers, and the DMA requests interrupt service. The callback function executed in the interrupt handler can update the primary descriptor to point to a new set of data and refresh the ping-pong configuration. On completion of the alternate descriptor's transfers, this process repeats but with the DMA again processing the primary descriptor while the alternate descriptor is updated in the callback function.
If the cosine frequency is 6.25 kHz, a "constant stream of data" to update the IDAC might seem overkill. In this example, the waveform consists of 32 points, so the actual update rate is a much higher 32 × 6.25 kHz = 200 kHz or one DMA transfer every 5 µs or 70 clock cycles at the default HFRCO frequency of 14 MHz.
The DMA takes 17 clock cycles per byte, halfword, or word, which would seem to be sufficiently fast to reproduce the waveform at the desired frequency. It is, but only for a single iteration of the waveform when basic DMA is used. After the IDAC is updated with the last wave table value, the callback function is executed to restart the DMA cycle, and herein lies the problem. The callback function is dispatched from emlib's DMA IRQ handler as shown below:
void DMA_IRQHandler(void)
{
int channel;
DMA_CB_TypeDef *cb;
uint32_t pending;
uint32_t pendingPrio;
uint32_t prio;
uint32_t primaryCpy;
int i;
/* Get all pending and enabled interrupts */
pending = DMA->IF;
pending &= DMA->IEN;
/* Assert on bus error. */
EFM_ASSERT(!(pending & DMA_IF_ERR));
/* Process all pending channel interrupts. First process channels */
/* defined with high priority, then those with default priority. */
prio = DMA->CHPRIS;
pendingPrio = pending & prio;
for (i = 0; i < 2; i++)
{
channel = 0;
/* Process pending interrupts within high/default priority group */
/* honouring priority within group. */
while (pendingPrio)
{
if (pendingPrio & 1)
{
DMA_DESCRIPTOR_TypeDef *descr = (DMA_DESCRIPTOR_TypeDef *)(DMA->CTRLBASE);
uint32_t chmask = 1 << channel;
/* Clear pending interrupt prior to invoking callback, in case it */
/* sets up another DMA cycle. */
DMA->IFC = chmask;
/* Normally, no point in enabling interrupt without callback, but */
/* check if callback is defined anyway. Callback info is always */
/* located in primary descriptor. */
cb = (DMA_CB_TypeDef *)(descr[channel].USER);
if (cb)
{
/* Toggle next-descriptor indicator always prior to invoking */
/* callback (in case callback reconfigurs something) */
primaryCpy = cb->primary;
cb->primary ^= 1;
if (cb->cbFunc)
{
cb->cbFunc(channel, (bool)primaryCpy, cb->userPtr);
}
}
}
pendingPrio >>= 1;
channel++;
}
/* On second iteration, process default priority channels */
pendingPrio = pending & ~prio;
}
}
Even for a single pending DMA channel interrupt, entry into and processing of this IRQ handler and execution of the callback function take more than the 70 clock cycles available when running at 14 MHz. This results in a delay between the last and first points of two subsequent waveforms as shown below:
Increasing the clock frequency minimizes the delay incurred processing the IRQ handler and callback function as does reproducing the waveform at a lower the frequency, but these options do not fix the underlying problem. Ping-pong DMA resolves this altogether by transferring two complete iterations of the waveform in series and refreshing the DMA descriptors between each one:
The example project that generates the waveform above is attached to this article and can be imported into Simplicity Studio v4 as follows:
Build the project, download it to the Happy there a way to generate a sine wave with the IDAC on Zero, Zero Gecko does have all of the requisite features needed to generate a sine wave (or any other waveform) under software control.
The example Simplicity Studio project attached to this article runs on the Zero.
Build the project, download it to the Zero the mbed TSL library included in the Gecko SDK suite FIPS PUB 140-2 certified?
The mbed TSL library included in the Gecko SDK Suite is not FIPS PUB 140-2 certified. For more details:
Do EFM32 series 0 or series 1 devices support Serial Wire Multidrop?
EFM32 series 0 and series 1 devices do not support Serial Wire Multidrop.
Is there a way to measure and verify the actual voltage of the EFx32xG1 internal 1.25 V or 2.5 V ADC references, such as by outputting the reference voltage to a pin?
The internal 2.5 V and 1.25 V references are based upon the internal bandgap reference (BGR), and the full scale reference value (i.e. 2.5V or 1.25V) is achieved through manipulation of input signal attenuation settings. Thus, there is not a 2.5 V reference value that could even be measured per se. Additionally, the internal reference sources can not be routed to a GPIO pin.
Additionally, because the ADC internal reference source in the EFx32xG1 device achieves different VFS values through input signal attenuation factors/dividers, the voltage of 2.5 V (or 1.25 V, or 5 V) does not actually exist in the device as a node voltage. Because of this, we do not specify any absolute voltages for the ADC reference sources, but instead specify a gain error for the ADC module (see "Gain error in ADC," EFR32xG1 datasheet, Table 4.39, section 4.1.16, page 75), which is -0.2% typical and 5% maximum. Thus, this specification can be interpreted to mean that the VFS when using the 2.5V internal reference option will fall within the range [2.35 V, 2.65 V] (worst case). Typical variation will be much tighter ([2.495 V, 2.505 V]). The ~0.833 V BGR reference from which the internal VFS levels are derived is calibrated for each device in production.
If you wish to monitor your ADC reference voltage directly, you can use an external reference by setting ADCn_SINGLECTRL.REF (or ADCn_SCANCTRL.REF) = EXTSINGLE (0x4) and connecting a reference source to the ADCn_EXTP reference pin (for single ended reference).
I have a Silicon Labs WSTK with a working radio board, but a damaged main board. Can I purchase a replacement WSTK main board (BRD4001A)?
Unfortunately, The WSTK main board (BRD4001A) is only available for purchase as a part of one of our wireless starter kits, and is not currently available for sale as a standalone board. I believe that the least expensive kit that includes this board would be the Blue Gecko Bluetooth Low Energy SiP Module Wireless Starter Kit (SLWSTK6101C -).
1) How do you use the APORT to select a pin as an ADC input?
2) What is the correct way to configure a pin for an analog function?
1) Control of the APORT and associated pin connections for the ADC is accomplished through your selections in the ADC input selection bitfields in ADCn_SINGLECTRL (i.e. NEGSEL and POSSEL) for single conversions. This is true in a similar way for other analog peripherals in the sense that those peripherals have a mechanism within their registers for selecting a particular APORT bus and channel as inputs/outputs to the module. For each of these peripherals, the act of selecting an APORT channel as an input or output will cause that peripheral to exert control of the necessary switching and internal device routing necessary to connect the pin assigned to that channel to the peripheral. Because of this, multiple peripherals requesting access to the same APORT bus can create conflicts, which can be configured to generate interrupts to aid in debugging the issue. For more information about APORT conflicts and generating interrupts on this condition in the ADC module, please refer to section 24.3.5.3 on page 765 of the EFR32xG1 reference manual. Please note that the MCU pins assigned to each APORT bus and channel are fixed and are defined in each device specific datasheet (see [Pin Definitions] > [Analog Port (APORT)]). The ADC positive input mux is connected only to APORT 'X' buses, while the negative input mux is connected only to APORT 'Y' buses, as shown in Figure 24.5 on page 760 of the EFR32xG1 reference manual. The easiest way to select the correct input mux setting to correspond to the pin you wish to use as input to the ADC is to consult the device datasheet and find which APORT (0, 1, 2, 3, or 4), Bus (X or Y), and channel (0-15) correspond to the pin you wish to use. You can easily find this information in Table 7.4: APORT Client Map on page 68 of the BGM12x datasheet (ADC0 APORT selections begin on page 71). Matching this information to the options given for the NEGSEL and POSSEL fields of the ADCn_SINGLECTRL register (see page 783 of EFR32xG1 reference manual). Writing to these bitfields will immediately cause the ADC to take control of the selected APORT bus.Also, please note that emlib provides a relatively simple API for selecting the APORT channel for the positive and negative (if used) input to the ADC, using the ADC_InitSingle_TypeDef structure in combination with the ADC_InitSingle() function. For example:...ADC_InitSingle_TypeDef singleInit = ADC_INITSINGLE_DEFAULT;singleInit.posSel = adcPosSelAPORT1XCH6; //select PC6 for BGM123singleInit.negSel = adcNegSelVSS;ADC_InitSingle(ADC0, &singleInit);...
2) In the GPIO module, all you must do to use a GPIO pin as an analog input is to configure the pin mode to "disable" (to disable the input sense, output driver and pull resistors) and disable over-voltage tolerance for that pin (recommended for reduced distortion of analog signals):GPIO_PinModeSet(gpioPortC, 6, gpioModeDisabled, 0); //set PC6 to DISABLE with no pull resistorsGPIO->P[gpioPortC].OVTDIS |= (0x01 << 6); //Disable over-voltage tolerance for PC6 As for the distinction between APORT A, B, C, D, etc... These correspond to APORT0 APORT1, etc. This can be a little confusing. Each APORT (0-4) has an X and a Y bus.Finally, GPIO pin configuration follows the same guidelines whether the pin is being used as an analog input or output (i.e. set pin to DISABLE w/o pull and disable over-voltage tolerance). For more information on using GPIO pins for analog functions, please refer to section 28.3.4.1 of the EFR32xG1 reference manual on page 918. Note that Push-Pull mode should be used for digital outputs, and alternate port control can be used to apply different slew rate, drive strength, and data input disable settings to digital pins in the same port grouping, but this does not apply for analog functionality.
Why does EM_AES in emlib use while loops on AES_STATUS instead of an interrupt or some other nonblocking method of waiting for completion?
The general principle of emlib is not to use interrupts to leave the usage of interrupts up to the user. You can modify this code to a nonblocking implementation of your choice if you do not want to wait on AES_STATUS.
Can I use bit-banding through the DMA?
No. Bit-banding is only available through the CPU, and no other AHB masters can perform bit-banding operations.
Can I download Simplicity Commander separately from Simplicity Studio for use during production?
Silicon Labs offers a variety of options for production programming of devices. The following page has all of the options described in depth:
The Production Programmer referred to on the above page is the best option for using standalone during production.
32-bit Knowledge Base
Sine Wave Generation with the IDAC on Happy Gecko
Sine Wave Generation with the IDAC on Zero Gecko
mbed TLS FIP certification
Serial Wire Multidrop
EFx32xG1 ADC Voltage Reference (Can it be measured?)
Replacement EFR32 Wireless Starter Kit (WSTK) Mainboards (BRD4001A)
Clarifying APORT Usage for EFR32xG Analog Peripherals
EM_AES
Bit-banding through DMA
Production Programmer | https://www.silabs.com/community/mcu/32-bit/knowledge-base?filter=added+gt+%272017-06-01T00%3A00%3A00Z%27&filter=added+lt+%272017-06-30T23%3A59%3A59Z%27&filter=isDraft%20ne%20true | CC-MAIN-2020-40 | refinedweb | 2,538 | 50.87 |
Cloning from Github repo with SSH key auth (using StaSh toolset)
Just wanted to know if anyone's gotten git-clone working against a github repo of theirs using some kind of auth method?
(Edit: I'm using the latest StaSh set of tools from ywangd/stash and the vanilla gittle, dulwich packages from jsbain)
The current stash/bin/git.py utility doesn't include anything in the auth kwarg by default, so I first tried hacking it by modifying the method to include:
auth=gittle.GittleAuth(username="me", pkey=(os.path.join(os.environ['HOME'], '.ssh/pkey')))
... and adding
auth=authto the Gittle.clone() call, but that returns a duplicate keyword error. Finding this annoyingly hard to debug or fix. What am I doing wrong, here?
What happens when you set
authbut do not add
auth=auth?
Using it straight with the ~/.ssh/config set and keys available, only passes back SSHException "Authentication Method Not Available" (from paramiko, I believe, but it would help if there were verbose modes to see the full traceback)
Do you have ?
I do not. Been burnt by too many git client clones on the app store before, but thanks for the recommendation. Is there a decent method for connecting it to pythonista? for now but see on the potential for future improvements.
Strangely, all of my git ssh keys in pythonista seemed to stop working recently . Don't know what that's all about, but the following did fix the issue:
I deleted my existing keys in ~/.ssh If you use ssh in stash for other things, this could be a problem, in which case go into github and delete your keys.
[~/Documents]$ gh create_key newipadkey Creating a ssh key in ~/.ssh/ ssh-keygen -d rsa -b2048 ssh keys generated with rsa encryption [~/Documents]$ git clone ssh://git@github.com/jsbain/stash.git stash
And this successfully cloned.
It is possible you may need to add github to known hosts (copy the following to your ~/.ssh/known_hosts file) if you havent before==
By the way, in stash you can use
stashconf py_traceback 1
to print full tracebacks, and
stashconf py_pdb 1
to automatically start interactive pdb when exceptions occur.
These turn out to be not very useful for troubleshooting dulwich auth issues.
For paramiko issues, you could, in the 2.7 interpreter in the console, type
import paramiko paramiko.util.log_to_file('paramikolog.txt')
(this has to be the 2.7 interpreter, because stash runs in 2.7 by default)
This forces paramiko to log to the above named file, which you can open in the editor and see what is happening. With my old key(s) i was getting the super helpful
DEB [20170618-07:37:36.987] thr=2 paramiko.transport: Trying discovered key cb06eb8641f4ca3ff73f806d8bdd7c22 in /private/var/mobile/Containers/Shared/AppGroup/C534C622-2FDA-41F7-AE91-E3AAFE5FFC6B/Pythonista3/.ssh/id_rsa DEB [20170618-07:37:37.075] thr=1 paramiko.transport: userauth is OK INF [20170618-07:37:37.581] thr=1 paramiko.transport: Authentication (publickey) failed.
I had to delete the offending key before it would move onto another one.
i should also mention that the gh command does require that you have your github https user/pass stored in the keychain (see help for gh command), which could be set up by running clone at least once using https, then running push. | https://forum.omz-software.com/topic/4141/cloning-from-github-repo-with-ssh-key-auth-using-stash-toolset | CC-MAIN-2018-13 | refinedweb | 561 | 66.94 |
In 1.11.1.89 NSSavePanel.BeginSheet has two overloads that take equivalent args - namely the continuation.
Once it's specified as NSSavePanelCompletion (which is great), and another is Action<int> which is the same delegate type.
Any calls to this function using a lambda gives an unspecified overload error.
Please just pick one.
I have checked this issue and observed that NSSavePanel.BeginSheet has only one overload. To check this issue I have implemented the code below and run the app successfully without any error.
public class TestClass : NSSavePanel
{
public TestClass()
{
}
public override void BeginSheet (NSWindow window, NSSavePanelComplete onComplete)
{
}
}
I have also checked in assembly browser and observed that we have only one method named 'BeginSheet' in class 'NSSavePanel'.
Screencast :
Note : I have checked this issue with both Classic and Unified templates and observed the same behaviour.
Could you please have a look on the screencast and let me know if I missed anything.
Environment Info :
===.11.1.89 (Enterprise Edition)
=== Xamarin.iOS ===
Version: 8.4.0.16 (Enterprise Edition)
Hash: 80e9ff7
Branch:
Build date: 2014-10-22 15:09:12-0400
===
> I have checked this issue and observed that NSSavePanel.BeginSheet has only one
overload. To check this issue I have implemented the code below and run the app
successfully without any error.
1) You could just look at the assembly and see the duplication. NSSavePanel has a BeginSheet and NSWindow (which it inherits) as a BeginSheet. They take two different but equivalent continuation types. I have attached 3 screen shots to demonstrate this.
2) Your test case is invalid. I specifically mentioned the problem of using lambdas (that require type inference), but your test just overrides one of the overloads. Overriding is not the problem.
-Frank
Created attachment 8830 [details]
Shows overload resolution can't work
Created attachment 8831 [details]
Shows BeginSheet in NSWindow
Created attachment 8832 [details]
BeginSheet in NSSavePanel
Sorry for the confusion from our QA guy. I can confirm there are two overloads, which can conflict.
This is a bug. We'll get it fixed up. Thanks for the bug report and trying out the alpha!
Tim, I think you were looking at this?
It is still here. From my point of view we should rid of custom delegate type | https://bugzilla.xamarin.com/show_bug.cgi?id=24700 | CC-MAIN-2018-13 | refinedweb | 376 | 67.96 |
Routes Dispatcher doesn't work with Routes 1.12.1
I tried a simple HelloWorld example for the routes dispatcher and kept running intro trouble. In the end it turns out that the current version of Routes (1.12.1) was incompatible. Every URL I tried, including "/", explicitly defined and implicitly defined were all 404.
After discussing it in #cherrypy I downgraded to Routes 1.10.3 and everything worked perfectly. Further testing reveals that routes 1.11 works too. It seems to be 1.12 that breaks the RoutesDispatcher.
Example app: {{{
!python
import cherrypy import random
class Example: @cherrypy.expose def index(self): return "Hello World!"
class Random: @cherrypy.expose def index(self, stuff): return "Random %s: %s" % (stuff, random.random())
mapper = cherrypy.dispatch.RoutesDispatcher() mapper.connect('index', '', Example()) mapper.connect('index', '/', Example()) mapper.connect('index', 'foobar', Example()) mapper.connect('random', '/:stuff', Random())
conf = { '/' : {'request.dispatch' : mapper}, }
if name == "main": cherrypy.tree.mount(root=None, config=conf) cherrypy.quickstart(None, config=conf) }}}
In Routes 1.12 a default was changed that made the route mapper “explicit” by default. See []. This means (I believe) that routes will not be given the defaults of "action=index" and "controller=content". As a result cherrypy isn’t able to figure out what method to dispatch in your example app because it doesn’t know what “action” the route corresponds to.
You should be able to fix any of the routes by adding either
action="index"(to explicitly define an action), or
_explicit=False(to re-enable the default controller and action) as keyword arguments for your
connectcall.
After inspecting the code, I found that the old behavior can be re-enabled by setting the `explicit` attribute to False on the mapper. | https://bitbucket.org/cherrypy/cherrypy/issues/1010/routes-dispatcher-doesnt-work-with-routes | CC-MAIN-2016-07 | refinedweb | 288 | 54.18 |
Re: What I don't like about C# so far, compared to C++ (managed or
- From: raylopez99 <raylopez99@xxxxxxxxx>
- Date: Tue, 07 Aug 2007 03:00:14 -0700
On Aug 6, 2:16 pm, Jon Skeet [C# MVP] <sk...@xxxxxxxxx> wrote:
Then tell us what you don't like about C# Jon.
I've done so several times in the past, but briefly:
1) The "lock" statement should have been "using" with an appropriate
locking type. See
That's some advanced MoJo there, Jon. Multithreading. I'm a little
less advanced--for example today I found out that C# has a neat and
compact "forward reference" that means you don't have to declare the
forward referenced class as a composite member in your class--but can
actually simply define/use it for the first time in a method parameter
list (assuming it's part of the same namespace). A little different
from traditional C++.
2) Switch needs to be brought into the 21st century - even if the
current behaviour is appropriate, the syntax and scoping could be
significantly improved
Yes, I agree--I've never actually used Switch in any of my programs--
seems so limited, using integers/char for control statements. I use If/
then (nested) instead, same thing. I'm still trying to figure out
(and will experiment today) with identifying objects in C# dynamically
at run-time (do you use "if(object_passed_to_your_function is
MyClass)"?? Seems that way. I thought it might be MyClass.GetType(),
but that just gives you the general (too general) Type of the object
it seems, thought that might be the same thing (another demo project
for today). At some point I'll give in and actually buy a book on C#
(I have on preordered, a nutshell guide due to be published this fall,
by O'Reilly). In the meantime I'll ask this group, which is faster
and easier than looking it up. Forget about "Help" function in Visual
Studio 2005--too much information, usually too generic also.
3) I'd like object-oriented enums, similar to Java's:
Same thing I suppose.
4) I'd like "private-to-property-code" variables which can't be
accessed by the rest of the class, like those introduced with automatic
properties in C# 3, but available for non-trivial properties too
Yes, somewhere I saw that "properties" are the new "global variables".
5) I'd like non-nullable reference types which can be used as
parameters etc, eg: "void Foo (string! x)". Ideally the compiler should
deal with this at compile time, but at the very least it could generate
code to throw ArgumentNullException where appropriate
Why? I have no idea why non-nullable is important. Must be a multi-
thread thing.
6) I'd like named indexers
Instead of the named IEnumerator class (which you can rename) I take
it? A small point for code clarity I presume.
7) I'd like extension properties like C# 3's extension methods - handy
for writing fluent interfaces
No idea what you're saying here. A quick look at Wiki "http://
en.wikipedia.org/wiki/Fluent_interface" shows a rather confusing
example, that's not at all easy to read, especially since no main()
program "using" the interface is show (hate it when that happens).
Looks too obscure to me--I vote with the people that say "fluent
interfaces" are too hard to read. As for IConfiguration, I'll
probably never use it ("The IConfiguration interface defines
properties and methods used to access configuration information for
Collaboration Data Objects (CDO) objects.)
(obscure Server stuff--too specialised for my taste)
BTW, inline class definitions really *are* ridiculous. I'm going
through a mess of such a class definition right now,
Sounds like you're dealing with a badly written class - which can
happen in any language.
In C++ you need to keep two bits of identical information in sync -
practically the definition of redundancy. If you want that behaviour,
however, you could always create an interface for every single class
you write.
I used to write C and C++, then moved to Java and then to C#. I've
never looked back with *any* fondness at the .c/.h split, and any time
I've had to work with C or C++ since I've found that to be one of the
pain points.
You're way ahead of me of course. I code as a hobby when I have spare
time from my real job. Right now I'm awaiting some projects so I'm
building an N-ary tree to prove some geneology stuff (see here:). Amazing that my home grown tree is
similar to the C# cookbook's tree, independently derived.
RL
.
- Follow-Ups:
- Re: What I don't like about C# so far, compared to C++ (managed or
- From: Jon Skeet [C# MVP]
- References:
- What I don't like about C# so far, compared to C++ (managed or otherwise)
- From: raylopez99
- Re: What I don't like about C# so far, compared to C++ (managed or otherwise)
- From: Peter Duniho
- Re: What I don't like about C# so far, compared to C++ (managed or
- From: raylopez99
- Re: What I don't like about C# so far, compared to C++ (managed or
- From: Jon Skeet [C# MVP]
- Re: What I don't like about C# so far, compared to C++ (managed or
- From: raylopez99
- Re: What I don't like about C# so far, compared to C++ (managed or
- From: Jon Skeet [C# MVP]
- Prev by Date: Re: How to limit program can only run one instance.
- Next by Date: wizard
- Previous by thread: Re: What I don't like about C# so far, compared to C++ (managed or
- Next by thread: Re: What I don't like about C# so far, compared to C++ (managed or
- Index(es): | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2007-08/msg00873.html | crawl-002 | refinedweb | 976 | 66.07 |
The class writes logs to the system EventLog, a database, a text file, or any combination of the three, depending on how it’s configured. Let’s dive in and see what’s needed to make this work.
Global.asax
I wanted this class to be usable in any web application, regardless of where that app was deployed. However, I may not always be able to write to the EventLog, or maybe I won’t have a database for an application. I may not have file permissions to write to a file, either. Instead of commenting out code, I used boolean constants to turn on and off each logging routine. These constants are defined and set in the Global file like this:
public static boolLogErrorToDatabase = true;
public static boolLogErrorToFile = false;
public static bool LogErrorToEventLog = false;
The Custom Error Class
The following class is attached for download and license-free usage: error-custom-class-code. Since you can view it in its entirety there, I’ll only post the most relevant text here to save space.
To access the EventLog, you need to use the System.Diagnostics namespace by placing a using statement at the top of the class. We also need the System.IO one for writing a text file:
using System.Diagnostics;
using System.IO;
We’re also accepting 4 parameters. First is the Exception followed by the screen and event or method where the error occurred. Finally we’re saving the user’s name. These can be changed or added to in order to fit your own business needs.
public voidLogError(Exception ex, stringsScreen, stringsEvent, stringsUsername)
{
//code discussed below
}
Logging the Error
Inside the LogError method, we’re going to provide three separate functions: one each for logging to the EventLog, the database, and to a file. Since any combination of the three may be desired, we’re evaluating the global variables we set earlier.
Writing to the EventLog
if (Global.LogErrorToEventLog == true)
{
// Write error to log file.
stringsAppName = sScreen + ” :: “+ sEvent;
EventLogoEventLog = new EventLog();
if (!EventLog.SourceExists(sAppName))
{ EventLog.CreateEventSource(sAppName, “Ellefson Consulting Log”); } string sMessage = ex.ToString();
//log the entry
oEventLog.Source = sAppName;
oEventLog.WriteEntry(sMessage, EventLogEntryType.Error);
}
Looking at the code, we can see that we’re combining the sScreen and sEvent parameters into the sAppName variable that will be used in the EventLog. We then use this to see if the EventSource is registered in the computer’s registry and if not, register it. This is not something you otherwise need to worry about, but this check must be done to avoid an error in the event the source is not registered.
The log we want to write to will be called “Ellefson Consulting Log”, which will be created if it doesn’t exist. The rest is self-explantory.
When you go to Computer Management and view the Event Log, this is what you will see:
Writing to a Database
After the EventLog code, we have another block that writes to a database, which is SQL Server 2005 in this case. Here I’m using the SQLHelper file to encapsulate my data access object usage, but any data connection code will work. In my database is a stored procedure called “uspLogError”, which accepts the same parameters as the other code here, writing the results to a table.
if (Global.LogErrorToDatabase == true)
{
intiErrorID = Convert.ToInt32(SqlHelper.ExecuteScalar(Global.ConnectionString, “uspLogError”, ex.ToString(), sScreen, sEvent, sUsername));
}
Writing to a File
Finally, the code writes to a text file. In this sample, the file is located in the C directory but you may want to put it somewhere else. The “true” option indicates we want to append to the file if it exists so we don’t lose the record of past errors. Without this the file would be overwritten. I’ve separated the parameters onto their own lines to make the text file more readable.
if (Global.LogErrorToFile == true)
{
// create a writer and open the file
TextWritertw = new StreamWriter(“C:\\ErrorLog.txt”, true);
// write a line of text to the file
tw.WriteLine(“Error: “+ ex.ToString());
tw.WriteLine(“Error location: “+ sScreen + sEvent);
tw.WriteLine(“Username: “ + sUsername);
tw.WriteLine(“Application: “ + Global.ApplicationName);
// close the stream
tw.Close();}
Using the Class
At the top of my example .aspx page, I need a using statement to reference the custom class I’ve created. Since my application’s namespace is EllefsonConsulting and I’ve created my class in the Business Logic Layer folder I set up, my using statement looks like this:
using EllefsonConsulting.BLL;
Now I need to create an object from my class to be used throughout my .aspx page. This is done just above the Page_Load event that should already be part of your page by default:
ErrorscError = new Errors();
The last step is to use the cError object in my try-catch block:
try
{
//some code
}
catch (Exception ex)
{
//some code to handle the error
//then log the error
cError.LogError(ex, Page.ToString(), “grdNews_SelectedIndexChanged”, Convert.ToString(Session[“Username”]));
}
Let’s look at this final line item by item. First we are refering to the cError object and using its LogError method. Then we are passing in all the needed parameters. First is the Exception “ex”, so we know what went wrong.
Next is the Page title. In this case, the page is my “news.aspx” page, which is what will be written to the log. This let’s me know where the error occured. By using the Page object we don’t have to keep changing this parameter for every method call.
Since the page isn’t enough, I also want to know what method caused the error, so I’ve copied and pasted the event handler title. In this case, that’s grdNews_SelectedIndexChanged. This will need to be changed for each method.
Finally, I want to know which user experienced the error in case I need to follow up with them and learn exactly what they were trying to do when it ocurred. Here I am copying their name out of a session variable.
Conclusion
With code reuse being one of the big advantages of object oriented programming, having all your error logging handled by an identical routine is smart, consistent, and saves time while also giving you flexibability in how you process the logs. This class can be altered to provide other information as you see fit, but it should give you a good start on logging your errors with only one line of code per method. Happy coding! | https://ellefsonconsulting.wordpress.com/2009/03/19/custom-error-logging-class-in-c/ | CC-MAIN-2018-22 | refinedweb | 1,085 | 64.71 |
Build a typing indicator in ASP.NET
Neo Ighodaro
When building chat apps, knowing when the person you are chatting with is typing a message can improve the user experience. It gives you some feedback that you’re not alone in the conversation and a message is coming your way. In this tutorial, we will go through some simple steps to achieve this feature using C# .NET and Pusher.
At the end of this tutorial we will have something like this:
This tutorial assumes prior knowledge of:
- C#
- .NET MVC and
- JavaScript (jQuery)
When you’re ready, let’s begin.
Setting up Our Project
We’ll be using Visual Studio, which is an IDE popularly used for building .NET projects. Visual Studio 2017 is free and available for popularly used Operating Systems. You can view installation details here.
After installing Visual Studio, launch it and create a new project by clicking New Project from the dashboard. Following the New Project wizard we:
- Set C# as our language to use,
- Select .NET MVC Project as the template,
- Fill in the Project name e.g. HeyChat (any name would do),
- Fill in the Solution name i.e. application name (HeyChat or any name would do).
Writing the server-side (C#) Code
To achieve a typing indicator, our chat app needs to be able to recognize who is typing at any given time. For this, we will add some limited form of identification. We’re not doing any authentication at all because this tutorial does not require it.
💡 For the purpose of this tutorial, we will assume this chat is open to all users and all that is required is that our user specifies their name on first entry.
Route definition
We can define some of the routes that we need to make this feature, which are:
- A home route which renders the first page that takes the user’s name.
- A login route which accepts a
POSTrequest of the user’s name.
- A chat route which renders the chat view.
💡 We may need some other routes as we go along but this is enough for starters.
To add these routes, we open the
RouteConfig.cs file in the
App_Start directory of our application. And in it, we add the routes we have defined.
routes.MapRoute( name: "Home", url: "", defaults: new { controller = "Home", action = "Index" } ); routes.MapRoute( name: "Login", url: "login", defaults: new { controller = "Login", action = "Index" } ); routes.MapRoute( name: "ChatRoom", url: "chat", defaults: new {controller = "Chat", action="Index"} );
Using the Home route as a sample, the route definition states that
/ requests will be handled by the
HomeController which is found in the
Controllers/HomeController.cs file and the
Index method of that controller. Next, we create the controllers we need.
Creating controllers and action methods
To create a new controller, right-click the Controller directory and select
Add → Controller. In the resulting form, we type in the name of our controller and select the empty template.
💡 When our application is created, it includes a HomeController with an Index action method by default, so we’ll perform the above steps to create our LoginController and ChatController.
In our LoginController class, we create the Index action method specifying
[HttpPost] at the top of the action method to indicate that it handles
POST requests.
public class LoginController : Controller { [HttpPost] public ActionResult Index() { } }
The Index action of the LoginController will receive the request payload, read the username from the payload and assign it to the current user session, then redirect our user to the chat page. When we add this to our action method we’ll have
public class LoginController : Controller { [HttpPost] public ActionResult Index() { string user = Request.Form["username"]; if (user.Trim() == "") { return Redirect("/"); } Session["user"] = user; return Redirect("/chat"); } }
💡 In a real-world chat app, we would add the user to a database and mark the user as logged in for other users to see available chat options, but that is beyond the scope of this tutorial so adding to a session will suffice.
In our ChatController class, we will add the Index action method. The Index action of the ChatController will render our chat view and pass along the current user to the view.
public class ChatController : Controller { public ActionResult Index() { if (Session["user"] == null) { return Redirect("/"); } ViewBag.currentUser = Session["user"]; return View (); } }
💡 By default, action methods handle
GETrequests so we will not need to add
[HttpGet]to the top of our method. We’ve also added a simple check to prevent access to the chat page if there is no logged in user.
Let’s not forget about our Home route. In the HomeController we’ll add the code to render the front page.
public class HomeController : Controller { public ActionResult Index() { if ( Session["user"] != null ) { return Redirect("/chat"); } return View(); } }
💡 We’ve also added a small check to prevent multiple logins in the same user session.
At this point, we’ve created the Controllers and methods to serve our views (which we haven’t created yet) so trying to run this will give you some errors! Let’s fix that.
Implementing the application’s views
Based on the routes we’ve defined so far, we will need two views:
- The front page view with the login form - served by the
Indexaction method of the
HomeControllerclass
- The chat view where the typing indicator feature will be seen - served by
ChatControllerclass’
Indexaction method
Front page/log in page
For our front page, we create a page with a form consisting of a field to type in your username and a button to submit for login. Referring to our controller code:
public class HomeController : Controller { public ActionResult Index() { if ( Session["user"] != null ) { return Redirect("/chat"); } return View(); } }
💡 The View function creates a view response which we return. When View().
To create our
HomeController default view, we:
- Right-click on the Views directory and select
Add New Folder,
- Fill in Home as the folder name,
- Right click the newly created Home folder and select
Add New View,
- Fill in the view name (in our case index), select
Razoras the view engine and click ok.
Now that we’ve created our front page view file, we’ll add the markup for the login form.
<div class="container"> <div class="row"> <div class="col-md-5 col-md-offset-4"> <div class="panel panel-default"> <div class="panel-body"> <form action="/login" method="post" style="margin:0"> <div class="form-group"> <input type="text" name="username" id="username" placeholder="Enter Username" class="form-control" required </div> <button type="submit" class="btn btn-primary btn-block"> Enter Chat </button> </form> </div> </div> </div> </div> </div>
The chat page
We’ll create the view for the chat page following the same steps as above but using
Chat as our folder name rather than
In the chat view, we add markup up to give us a sidebar of available users and an area for chatting.
<!DOCTYPE html> <html> <head> <title>pChat — Private Chatroom</title> <link rel="stylesheet" href="@Url.Content("~/Content/app.css")"> </head> <body> @{ var currentUser = ViewBag.currentUser; } <!-- Navigation Bar --> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">pChat</a> </div> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Log Out</a></li> </ul> </div> </nav> <!-- / Navigation Bar --> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-3"> <aside class="main"> <div class="row"> <div class="col-xs-12"> <div class="panel panel-default users__bar"> <div class="panel-heading users__heading"> Online Users (1) </div> <div class="panel-body users__body"> <ul class="list-group"> @if( @currentUser == "Daenerys" ) { <li class="user__item"> <div class="avatar"></div> <a href="#">Jon</a> </li> } else if( @currentUser == "Jon") { <li class="user__item"> <div class="avatar"></div> <a href="#">Daenerys</a> </li> } </ul> </div> </div> </div> </div> </aside> </div> <div class="col-xs-12 col-md-9 chat__body"> <div class="row"> <div class="col-xs-12"> <ul class="list-group chat__main"> <div class="row __chat__par__"> <div class="__chat__ from__chat"> <p>Did you see Avery's sword???</p> </div> </div> <div class="row __chat__par__"> <div class="__chat__ receive__chat"> <p>Err Looked normal to me...</p> </div> </div> <div class="row __chat__par__"> <div class="__chat__ receive__chat"> <p>maybe I'm a hater</p> </div> </div> <div class="row __chat__par__"> <div class="__chat__ from__chat"> <p>Lmaooo</p> </div> </div> </ul> </div> <div class="chat__type__body"> <div class="chat__type"> <textarea id="msg_box" placeholder="Type your message"></textarea> </div> </div> <div class="chat__typing"> <span id="typerDisplay"></span> </div> </div> </div> </div> </div> <script src="@Url.Content("~/Content/app.js")"></script> </body> </html>
We’re using the razor template engine, which gives us the ability to read data passed from the C# code and assign them to variables that can be used in our frontend. Using
@{ var currentUser = ViewBag.currentUser } we have passed in the name of the current user which will come in handy shortly.
💡 To keep things quick and simple we have assumed there are only two possible users: Daenerys or Jon. So using the razor
@if{ }condition we are showing who is available to chat with.
Now that we have our views in place we can move on to our typing indicator feature!
Implementing the typing indicator
Listening for the typing event
On most chat applications, the feature becomes visible when someone is typing, so to implement we’ll start off by listening to the typing event in the chat text area using jQuery. We'll also pass the
currentUser variable we defined earlier with razor to our script.
var currentUser = @currentUser; $('#msg_box').on('keydown', function () { //stub });
We added a listener to the
keydown event on our typing area to help us monitor when someone is typing.
Now that we’ve created our listeners, we’ll make our listeners send a message that someone is typing to the other members of the chat. To do this, we’ll create an endpoint in our C# code to receive this request and broadcast it via Pusher.
We’ll implement all the client code (assuming that our C# endpoint exists, then we’ll actually create the endpoint later).
💡 To prevent excessive requests to our C# code i.e. sending a request as every key on the keypad is pressed or released, we’ll throttle the sending of the requests using a debounce function. This debounce function just ignores a function for a while if it keeps occurring.
// Debounce function // Credit: //); }; };
Now that we have a debounce function we’ll create the callback function for our
keydown event:
var isTypingCallback = debounce( function() { $.post('/chat/typing', { typer: currentUser, }); }, 600, true);
and pass the callback to our event listeners.
$('#msg_box').on('keydown',isTypingCallback);
Creating the endpoint triggered by the typing event
Earlier, we had our event listeners send a POST request to the
/chat/typing Route on the client side. Now we’ll create this Route, which will transmit the typing event to other client users using Pusher.
First, we’ll create the route for the endpoint in our
RouteConfig.cs file.
... routes.MapRoute( name: "UserTyping", url: "chat/typing", defaults: new { controller = "Chat", action = "Typing" } );
💡 We’ve created this endpoint to be handled by the Typing action method of the ChatController
Next, we’ll create our Typing action method in the
ChatController:
[HttpPost] public ActionResult Typing() { //stub }
Using Pusher to make our application update in realtime
Our
/``chat``/``typing endpoint will receive a post payload of the user who is doing the typing. We’re going to use Pusher to transmit this to everyone else.
On our Pusher dashboard, we’ll create a new app filling out the information requested i.e. App name, frontend tech, etc. You can register for free if you haven’t got an account. Next, we’ll install the Pusher Server package in our C# code using NuGet, a packer manager for .NET.
💡 To install the package we right-click the Packages directory; Select the add Package option and select the Pusher Server package.
Then we’ll add the Pusher broadcasting to our Typing action event. To use Pusher we’ll have to import the Pusher Server namespace in our code.
... using PusherServer; namespace HeyChat.Controllers { public class ChatController : Controller { ... [HttpPost] public ActionResult Typing() { string typer = Request.Form["typer"]; string socket_id = Request.Form["socket_id"]; var options = new PusherOptions(); options.Cluster = "PUSHER_APP_CLUSTER"; var pusher = new Pusher( "PUSHER_APP_ID", "PUSHER_APP_KEY", "PUSHER_APP_SECRET", options); pusher.TriggerAsync( "chat", "typing", new { typer = typer }, new TriggerOptions() { SocketId = socket_id }); return new HttpStatusCodeResult(200); } ...
We initialized Pusher using our PUSHER_APP_ID, PUSHER_APP_KEY, PUSHER_APP_SECRET, and PUSHER_APP_CLUSTER (be sure to replace these with the actual values from your dashboard); and then broadcast an object containing the* typer - which is the person typing - on the*
typing event via the
chat channel.
💡 We’ve added
new TriggerOptions() { SocketId = socket_id }to our Pusher triggerAsync function. This is to prevent the sender of the broadcast from receiving the broadcast as well. To do this we’ve assumed we’re receiving
socket_idin our payload along with
typer, so on our client side, we’ll add it to the payload sent.
Now, whenever there’s a typing event our C# code broadcasts it on Pusher, all that is left is to listen to that broadcast and display the ‘xxxx is typing…’ feature.
First, we’ll initialize Pusher in the script section of our chat page using our PUSHER_APP_KEY and PUSHER_APP_CLUSTER (once again replace these with the values from your dashboard).
var pusher = new Pusher('PUSHER_APP_KEY', { cluster:'PUSHER_APP_CLUSTER' });
To implement the broadcaster exemption we mentioned earlier, we’ll get the socket id from our client
pusher instance and amend our payload for the typing request to the server to include it.
var socketId = null; pusher.connection.bind('connected', function() { socketId = pusher.connection.socket_id; }); var isTypingCallback = debounce( function() { $.post('/chat/typing', { typer: currentUser, socket_id: socketId // pass socket_id parameter to be used by server }); }, 600, true);
Now that Pusher is initialized on our client side, we’ll subscribe to the chat channel and implement our feature using the
typer passed.
var channel = pusher.subscribe('chat'); channel.bind('typing', function(data) { $('#typerDisplay').text( data.typer + ' is typing...'); $('.chat__typing').fadeIn(100, function() { $('.chat__type__body').addClass('typing_display__open'); }).delay(1000).fadeOut(300, function(){ $('.chat__type__body').removeClass('typing_display__open'); }); });
Conclusion
In this tutorial, we’ve walked through implementing the popular a typing indicator feature using Pusher, .NET, C# code and some jQuery. We’ve also seen how to broadcast messages and avoid the sender responding to a message it sent.
Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at Eighth Floor 6 New Street Square, New Fetter Lane, London, England, EC4A 3AQ. | https://pusher.com/tutorials/typing-indicator-aspnet/ | CC-MAIN-2021-10 | refinedweb | 2,433 | 61.16 |
Introduction to Python Contextlib
Contextlib is a Python module that contains context manager utilities that work for context managers and the “with” statement. In Python, the allocation and releasing or resource management is done using context manager using “with” statement. This “with” keyword is used because it automatically closes any file that is open and releases the resources. Contextlib is one of the whole standard library modules that contains tools for creating and works similar to context manager class which uses @contextmanager as a decorator. This is one of the shortcut methods for creating context managers.
Examples of Contextlib Module
A context manager is created or implemented using two methods in the class and they are __enter__() method and __exit__()method. In this library module, the __enter__() method will be defined as the decorator of the library is used in the generator function that calls the yield statement exactly once. So the statements before the yield statements or statements before the call to yield are considered as the code for the __enter__() method. The statements after the yield statements or statements after the call to yield statement are considered as the code for the __exit__ ()method.
1. contextmanager decorator
Now we can create context manager using __enter__() and __exit__() methods is not much difficult but it is more overhead sometimes. So we can use @contextmanager decorator to convert generator functions into a context manager.
Code:
from contextlib import contextmanager
@contextmanager
def open_file(path, mode):
the_file = open(path, mode)
yield the_file
the_file.close()
files = [] for x in range(100000):
with open_file('foo.txt', 'w') as infile:
infile.write('Hello Educba')
for f in files:
if not f.closed:
print('not closed')
files =open('foo.txt', 'r+')
contents = files.read()
print(contents)
Output:
This above code implementation is shorter when compared to creating a class for context manager. It is just as to open a file, yield the contents, and close it. As we are using with the statement here again, in fact, all the files are indeed closed in this above code.
2. Nested Implementation
So many times it is needed to maintain multiple contexts simultaneously. This process can be done by nesting with statements one inside another. There is a method called nested() which nests the context using a single with statement.
Code:
import contextlib
@contextlib.contextmanager
def multicontext(ctxt):
print 'entering contents:', ctxt
yield ctxt
print 'exiting contents:', ctxt
with contextlib.nested(multicontext('Educaba'), multicontext('Training'), multicontext('Intitute')) as (X, Y, Z):
print 'inside with statement:', X, Y, Z
Output:
In the above code, the nested() method is used to print the multiple contents this method returns the result of the contents in reverse order as we can see in the output. The contextlib library module was used in earlier versions of Python. As Python 2.7 and later versions, the working of the nested() method is now done using a statement only. So without nested() method the example is modified as below:
Code:
import contextlib
@contextlib.contextmanager
def multicontext(ctxt):
print 'entering contents:', ctxt
yield ctxt
print 'exiting contents:', ctxt
with multicontext('Educba') as X, multicontext('Training') as Y, multicontext('Institute') as Z:
print 'inside with statement:', X, Y, Z
Output:
So we can see its results are the same as the previous code output using the nested() method.
3. Class-based approach for using contextlib
contextlib.ContextDecorator is used to define the context managers using a class-based approach. By using this it can be used as a normal function or as a function decorator. Let’s take an example for it:
Code:
from contextlib import ContextDecorator
class htmlparagraph(ContextDecorator):
def __enter__(self):
print('<p>')
return self
def __exit__(self, *exc):
print('</p>')
return False
@htmlparagraph()
def emit_html():
print('Here is some non-HTML ')
emit_html()
Output:
4. Closing open handles
There are many classes to close these files or handlers like a close() method but this is not supported by the context manager API so there is another method called closing() which is used as a closing () method in context managers. Let’s see the example of how the closing() method is used:
Code:
import contextlib
class contxt(object):
def __init__(self):
print 'inside the init() method'
def close(self):
print 'inside the close() method'
with contextlib.closing(contxt()) as ctxt:
print 'inside the with statement'
print
print 'Error handling:'
try:
with contextlib.closing(contxt()) as ctxt:
print ' raising from inside the with statement'
raise RuntimeError('There is a runtime error')
except Exception, err:
print ' Had an error:', err
Output:
The above code is closed irrespective of whether there is an error or not in with a statement.
Conclusion
In this article, we have discussed how the context manager can be created not and only using classes but also there is another shortcut method in Python known as contextlib. This is the Pythons standard library for creating and working of context managers similar to declaring classes. In this library, there are other sub-modules used such as contextmanager for creating context managers using with statement, which has nested() method to release the multiple contexts but this method is depreciated from Python 2.7 and later versions because the working of this nested() method is now done by with statement itself. There is another method used with this module is a closing() method which helps you close the files or handler irrespective of errors in with statements that are handled by the exceptions.
Recommended Articles
This is a guide to Python Contextlib. Here we discuss how to create context manager and implementing Contextlib Module with its examples. You may also have a look at the following articles to learn more – | https://www.educba.com/python-contextlib/ | CC-MAIN-2020-24 | refinedweb | 942 | 52.19 |
Hi monks!
I've still got a problem. I was looking for a way to apply an explanatory comment to an entry or a label widget when the mouse is "hover" it. Zentara told me that in Tk that's named Balloon. It's part of the Tk's Tix extension. I found how to apply it in tk, but the GUI I'm greating uses Tkx, and I really can't make the translation from Tk to Tkx. I can't understand why. I've tried every combination: i've required the package Balloon, etc, but it always gives me an error. Balloon is not recognised. So I would like to know if there's another rule to translate on Tkx the tk's extentions or if tkx doesn't support Ballons, or this widget got another name or what else.
Just in case, Tk's code is the following :
use Tk;
use Tk::Balloon;
$mw = MainWindow->new(-title => "Simple Balloon example");
$button = $mw->Button(-text => "Exit", -command => sub { exit })->pack
+;
$msgarea = $mw->Label(-borderwidth => 2, -relief => 'groove')
->pack(-side => 'bottom', -fill => 'x');
$balloon = $mw->Balloon(-statusbar => $msgarea);
$balloon->attach($button, -balloonmsg => "Exit the App",
-statusmsg => "Press the Button to exit the application");
$balloon->attach($msgarea, -msg => 'Displays the help text for a widge
+t');
MainLoop;
[download]
Thanks for helping me!
Quoting using Tcl packages from Tkx::Tutorial:
"When the Perl application starts up and loads Tkx, the only functions available in the Tkx:: namespace are those commands provided by core Tcl/Tk."
I am not familiar with Tkx myself, but I suggest that you read Tkx::Tutorial and go through CPAN too.
Ouh, I just forgot to post it!
I I found how to write it, thanks a lot!
Here is an example :
use Tkx;
Tkx::package_require('tooltip');
Tkx::namespace_import("::tooltip::tooltip");
my $mw = Tkx::widget->new(".");
my $nameDTDlbl = $mw->new_ttk__label(-text => "The following entry wid
+get got a tooltip :");
$nameDTDlbl->g_grid( -column => 0, -row => 0, -sticky => "we", -pady=>
+5);
my $nameDTDcase= $mw->new_ttk__entry(-width => 35,);
$nameDTDcase->g_grid( -column => 0, -row => 1, -sticky => "w", -padx=>
+10, -pady => "0 3");
Tkx::tooltip($nameDTDcase, "Example : \"tei_corpus.dtd\"");
Tkx: | http://www.perlmonks.org/?node_id=824504 | CC-MAIN-2015-14 | refinedweb | 358 | 60.14 |
In one sense, the C programming language is an inexcusable language with an exemplary heritage and some depressing consequences.
The Algol 60 programming language, developed by a committee made up of the greatest computer scientists of the late 1950's introduced some key ideas, the if-then-else statement, for example. In the early 1960's, Christopher Strachey at Cambridge led a group that developed a language called CPL, Christopher's Programming Language (to his students), or the Cambridge Programming Language (to many), or the Combined Programming Language (to those who didn't like Cambridge getting all the credit).
CPL was never implemented. It existed on paper only. CPL was a reaction to shortcomings of Algol 60. One of Christopher Strachey's students implemented a subset of CPL, called Basic CPL or BCPL. BCPL was practical and attracted a small but interesting following in the late 1960's. BCPL was implemented on Multics as an alternative to PL/1, the official systems programming language of the Multics project, and several defense contractors began using it for at least some of their projects.
An interesting aside in the history of BCPL is that Strachey's group began experimenting with object-oriented programming using it, despite the fact that it had no built-in support for objects. BCPL gave use curly braces as brackets for blocks of statements. Algol 60 used the keywords begin and end for this.
One group that got interested in BCPL was at Bell Labs. Kernighan and Ritchie, experienced developers from the Multics system, were working there on the early prototype of the Unix system. They decided to invent a new language based on BCPL for use in the re-implementation Unix. This language was christened C because an earlier subset of BCPL developed at Bell Labs was called B. The first compiler was written for the DEC PDP-11 computer, and some features of the language were based on ideas from that machine.
C became a success for two reasons: First, Unix was a success. A Unix academic license cost only a few dollars, and universities around the country began to experiment with Unix systems. Second, C was small enough and clean enough that microcomputer implementations became available.
In the early 1980's, it was not at all clear that C and Unix would become major forces. Pascal was the dominant programming language for academic research, and it was, technically, far superior. It was strongly typed, so it was far less prone to the kinds of security nightmares that C programs are notorious for. Pascal was also widely available on microcomputers.
The force that drove C into the limelight was the early Internet. Digital Equipment Corporaton's VAX, a 32-bit successor to the 16-bit PDP-11, was priced right, and when the University of California at Berkeley ported Unix to the VAX -- BSD Unix, VAXes running Unix quickly became the dominant computer used for E-mail. As the Internet was created, these became the dominant Internet host.
C and Pascal were not object oriented. Another language dating from the late 1960's, Simula 67, was the first programming language that was designed to support object oriented programming. For a decade, hardly anyone appreciated this language outside of Scandinavia, where it had been developed. Many thought of it as a special-purpose simulation language based on Algol 60. While simulation motivated the development of the language, it was definitely not special purpose.
Many programmers in the late 1970's and early 1980's began building object-oriented extensions to C and Pascal. Objective C, Object-Oriented Pascal, and many others came from this effort. One of those was C++, a language developed by Bjarne Stroustrup. He had been a Simula 67 programmer, and he was not happy programming in C in his new job at Bell Labs, so he wrote a preprocessor that took C with extensions to support good features from Simula 67 and produce C output. This extended language was known as C++.
The success of C++ was sealed by the development of the Gnu C++ compiler, a compiler that generated better code, for the VAX, than almost any other compiler, and that was a free open-source product. As the Internet grew, Unix and the Gnu C++ compiler were ported to many other computers, and C and C++ became the dominant languages for system implementation.
C++ has its problems. Many of these are problems it inherited from C. One group that was bothered by this was a group at Sun Microsystems. The result of their work, released in the mid 1990's was Java. Java preserves much of the syntax of C++, cleaning up the semantics of the language and a few ugly bits of syntax. Unfortunately, it preserves many ugly features of C -- this was considered necessary in order to make it easy for C++ programmers to migrate to Java.
Modern type-safe languages such as Java have a serious vulnerability hiding under them. They tend to run on operating systems with a Unix heratige (this includes Windows and Linux) that are implemented in a mix of C and C++. This means that, even though the language itself may be safe, the operating system interface on which it sits may contain numerous vulnerabilities, and any calls to external code (Java, for example, contains hooks allowing Java programs to call C or C++ code) introduce all of the potential insecurity of C and C++ into these more modern languages.
The standard Introduction to C begins with the program to output the string "Hello World" to the standard output stream:
#include <stdio.h> int main() { printf("Hello World!\n"); }
We'll extend this dull little program with some declarations. Consider this version:
#include <stdio.h> int main() { int i; char s[] = "Hello World!\n"; for (i = 0; s[i] != '\0'; i++) { putchar(s[i]); } }
Now, our main program has two local variables. The first, i is an integer. We're going to use it as the index to count through a for loop. The second, s is an un-dimensioned array of characters initialized to the string "Hello World!". All strings in C implicitly have a null byte at the end, represented in C as '\0'. The for loop terminates when it finds this null byte.
Notice that the array really is undimensioned! If our program elects to use index values outside the range defined by the string, it will find some byte of memory.
Here is another variant on the program that is even more unsafe:
#include <stdio.h> int main() { char *s = "Hello World!\n"; for (; *s != '\0'; s++) { putchar(*s); } }
Here, we didn't declare s as an array of characters, we declared it as a pointer to a character. Now, our for loop has no initialization, and we step through the string "Hello World" using the character pointer to pick successive characters out of the string. The character pointer can point to any memory address at all, but because we were careful, it remained pointing only to characters within the string (including the null byte).
Notice that we're doing arithmetic on the pointer with the operation s++. This is exactly equivalent to s=s+1. Adding one to a pointer in C doesn't always add one to the representation of that pointer -- it adds the size of one element of the type pointed to. In this case, because it's a pointer to a character, it adds 1 because characters are of size 1 byte.
We can do worse, taking some serious risks:
#include <stdio.h> int main() { int i; char *s = "Hello World!\n"; while (*s != '\0') { putchar(*s); i = (int)s; i = i + sizeof(char); s = (char *)i; } }
Here, we have used integer addition to increment the pointer s. We did this by using a very dangerous C (and c++) feature called casting to take the representation of s and make the compiler treat that representation as an integer. Without the cast, the assignment of a pointer to an integer (or visa versa) would be illegal. With the cast, we've told the compiler, "yes, I really want you to do this unsafe thing."
The above program is verbose. We can shorten it, keeping it just as unsafe, by rewriting it as follows:
#include <stdio.h> int main() { char *s = "Hello World!\n"; for (; *s != '\0';s = (char *)((int)s + sizeof(char))) { putchar(*s); } }
Here is another version, illustrating many of the above features, but incorporating a subroutine to print out the string:
#include
char * s = "Hello World!"; /* a global variable */ void output( char * p ) /* a function returning void */ { char ch; /* a local variable */ for (;;) { /* an infinite loop */ ch = *p; /* get the char p points to */ if (ch == '\0') break; /* exit the loop on null character */ putchar(ch); /* output the character */ /* p++; */ /* increment the character pointer */ p = (char *)((long int)p + sizeof( char )); } putchar( '\n' ); /* output newline at end of string */ } int main() { output( s ); /* call the function */ }
The above examples are not written to suggest that you ever write this kind of code in any commercial product you are ever involved in writing. In most contexts, the above code is dangerous and any programmer who writes such code should be severely repremanded.
the above programs are progressively more dangerous, offering progressively more severe opportunities to make serious programming errors. We will use them as a launching point for something else, an exploration of how unsafe programming methods can explore the implementation of the programming language in order to allow an outsider to attack the behavior of a program.
On a typical Unix system, if your test program (any of the programs above) is in a source file called, say hello.c, you'd compile it as follows:
cc t.c
There are several C and C++ compilers on most Unix systems. Typical names are cc, for C and cpp for C++. The above programs should work under all of them, unless your machine uses 64-bit pointers. On such machines, change the declaration of int to long int so that the integer and pointer variables have the same size. Having compiled the program, the output of the compiler is, by default, stored in a file called a.out.
This file is just that, a file. It is easy to change its contents. Here is an example session where such a change was made:
% cc t.c % a.out Hello World! % modify "Hello" "H---o" < a.out > b.out % chmod +x b.out % b.out H---o World!
Here, I wrote my own command (just another program) called modify that was applied to the input file a.out, giving the output file b.out. I used a utility called SED to write this command. My modify command substituted the text H---o for any occurances of Hello it happened to find. The second to the last command in the above example makes the file b.out executable, because it isn't executable by default.
Why did we do this? To demonstrate that programs, even after they are compled, are just files. Object programs under most computer systems can be easily modified. Such modifications can make arbitrary changes to the file! Many classic viruses, for example, search out object files and attach themselves to those files by editing the object files they find.
The Definitive reference on the C language is the slim little text that launched the language:
The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie, Prentice Hall, 1978 and subsequent editions.
This slim little book is a classic, demonstrating the clear distinction between tutorial introductions to a programming language and reference material, and demonstrating how concise and clean a language definition can be. The current edition describes ANSI C, and it remains in print. Note that Kernighan and Ritchie wrote the first C compiler as well as writing the book.
Another interesting on-line source giving one man's take on the C++ language is:
Bjarne Stroustrup's FAQ
Note that Bjarne Stroustrup was the developer of C++, so his take on the language is important.
If you ever have to write big programs in C, consider the advice given here:
Douglas W. Jones Manual of C Style
New Unix users may find the following tutorials to be useful.
A vi tutorial. There are other editors, but the two leading editors for Unix programmers are still VI and Emacs. There's no need to learn both, but Unix programmers ought to know one or the other.
A Unix tutorial. There are many introductory Unix tutorials, this one has only one virtue, it is short. | http://homepage.divms.uiowa.edu/~jones/security/notes/02.shtml | CC-MAIN-2017-43 | refinedweb | 2,113 | 63.7 |
how to write identifiers for A grade on mid-term exam, The total number of courses, The total numbers of classmates, and the Average grade of the test.
thats good
this program is rong.............!!!!!!
class
{
public static void main(String[] args)
{
int i=0;
i = i--;
System.out.println("i");
}
}
Post your Comment
Java Primitive Datatype
Java Primitive Datatype what is the size of boolean datatype ? please explain in detail
Datatype convertion
Datatype convertion it possible to convert long datatype into string in java if possible means how
Java Datatype
Java Datatype What will be the output of following java program and why?
class Datatype{
public static void main(String[] args.... Therefore it displays its corresponding integer value.
class Datatype{
public
Boolean DataType
Boolean DataType What is the Size of the Boolean datatype in Java
size of all primitive data
size of all primitive data java program for to find the size of all primitive data types in java
datatype - Java Beginners
datatype how i convert char datatype in string format
for ex.(convertion of int datatype)
int variable_name=Integer.parseInt(br.readLine()); Hi Friend,
Try the following code:
import java.io.*;
public class
Primitive Data Types
In this section we will discuss about Primitive Data Types in Java 7
what is difference between objectan primitive? - Java Beginners
what is difference between objectan primitive? whatis difference between object and primitive
Primitive Data Types
Primitive Data Types
In java, all the variables needs to be declared first... operations of java are performed. This behavior specifies
that, Java is a strongly-typed programming language.
For More details Click on the link below :
Java
how to write to file primitive type double
how to write to file primitive type double Hi,
How to write to file primitive type double in java program?
thanks
Hi,
To write a file primitive data type double there is a class DataOutputStream that provides
Autoboxing/unboxing of primitive types
Autoboxing/unboxing of primitive
types
When adding a primitive data type,conversion between primitive types and
wrapper classes is necessary ...;();
The autoboxing and auto-unboxing of Java primitives
produces code that is more concise
Mysql Alter Column Datatype
Mysql Alter Column Datatype
Mysql Alter Column Datatype is used to modify the table and change the
datatype of field.
Understand with Example
The Tutorial illustrate
Mysql Decimal Datatype
Mysql Decimal Datatype
Mysql Decimal Datatype is used to specify the numeric values.
Understand with Example
The Tutorial give you an example from 'Mysql Decimal Datatype
parse a file into primitive binary format
parse a file into primitive binary format Hi, I need help converting an audio file or any other file to its primitive binarty format, and when I read the inputstream I find it some integers and I don't know its binary
Reference Data Types
;
As we discussed that the Java programming language are divided into two
categories :
Primitive Data Types
... Data Types in brief
In Java a reference data type is a variable that
can
Mysql nchar Datatype
Mysql nchar Datatype
MySQL nchar define the datatype nchar that stores fixed-length character
data. The data can be a string single-byte or multibyte letters, digits
Java Methods
Java Methods
... of operator returns the datatype of an operand. You can see in the given example....
In Java, java.lang.reflect.*; package
how to use float datatype in mysql? - SQL
how to use float datatype in mysql? how to use float datatype in mysql? hi Chitra
this code help u
CREATE TABLE `paging` (
`Id` float(10,2) NOT NULL default '0.00',
`name` varchar(255) default NULL
The byte Keyword
;
The byte Java Keyword defines the 8-bit integer primitive type.
The keyword byte in Java is a primitive type that designates with eight bit signed integer
in java primitive type. In java keyword byte will be stored as an integer
Java - Arithmetic Operation, Conversion and Casts in java
Java - Arithmetic Operation, Conversion and Casts in java
This example illustrates that what is type casting? Type Casting
refers to changing an entity of one datatype
Convert Object to Int
Object into a primitive type int and Integer Object to primitive type int.
. ... into primitive type int and Integer type object to primitive type int.
The parseInt... the primitive type int value. Again, this program
converts an Integer object into
Java Write To File Double
Java Write To File Double
In this tutorial you will learn how to write to file primitive type double.
Write to file primitive data type double... process to execute a java program write simply on
command prompt as :
javac
Java Integer class
Java Integer class
Java provides wrapper classes corresponding to each primitive data types
in its "lang" package. These classes represent the primitive values
Wrapper
in Java are immutable. Converting primitive types into the
corresponding wrapper...
Wrapper
Java provides wrapper classes corresponding to each primitive data types in
its "
Autoboxing in Java
Autoboxing in Java is the automatic transformation of primitive data types... types into Wrapper class
by Java compiler takes place when:
a primitive data..., Float, Double)
by Java compiler.
One must also know about Unboxing, which means
can we add primitive data to wrapper class object
can we add primitive data to wrapper class object Hi,
Here is my code:
class Myclass{
public static void main(String args[]){
int i=2;
Integer a= new Integer(3);
a=a+i;
System.out.println("a"+a);
} }
Thanks
Hello
The long keyword
;
long is a keyword in java that is used to store 64-bit
integer (Java primitive... in java programming language wraps a long
type primitive value in an object. An Long... relevant to a compiler.
The keyword long in java is also used to declare
java programmingClinton Smith September 20, 2011 at 5:29 AM
how to write identifiers for A grade on mid-term exam, The total number of courses, The total numbers of classmates, and the Average grade of the test.
javaAisha Abubakar Shema June 8, 2012 at 10:22 AM
thats good
weong...........!!!!!!!!!rajat September 18, 2012 at 1:28 PM
this program is rong.............!!!!!!
javasandeep rai November 14, 2012 at 7:05 PM
class { public static void main(String[] args) { int i=0; i = i--; System.out.println("i"); } }
Post your Comment | http://roseindia.net/discussion/18635-Java---Identifier-and-primitive-datatype-in-java.html | CC-MAIN-2016-07 | refinedweb | 1,042 | 52.09 |
Consuming GraphQL APIs with React Hooks (useQuery) & Apollo Client
Throughout this tutorial, we'll see by example how to consume and fetch a GraphQL API with React Hooks and Apollo Client.
We'll particularly see how to use the
useQuery hook to send GraphQL queries to the server and the
gql tag to write GraphQL queries.
The GraphQL API is hosted in this link and provides information about Pokémons.
These are the steps of this tutorial:
- Step 1 - Setup
- Step 2 - Initializing a New React Project
- Step 3 - Setting up The Apollo Client
- Step 4 - Initializing the Apollo Client with The In-Memory Cache and HTTP Link
- Step 5 - Linking the Apollo Client to React Component(s)
- Step 6 - Sending GraphQL Queries & Consuming the API
- Step 7 - Building the React Application
Before we can start, we'll need to have a few things.
Requirements
if you want to follow this tutorial step by step, you will need to have the following requirements
- Node.JS and NPM installed on your development machine,
- Familiarity with modern JavaScript/ES6+,
- Working experience of React.
You can easily get the binaries of Node and NPM from the official website or better yet use NVM, a POSIX-compliant bash script to install and manage multiple active versions of Node.
Step 1 - Setup
Let's get started with the first step where we'll set up
create-react-app, the official tool for quickly creating and working with React projects.
Open a new command-line interface and execute the following command:
$ npm install -g create-react-app
Note: In case you get any EACCESS errors when installing the package globally on your system. make sure to add
sudobefore your command in Linux and macOS, or use a command prompt with administrator access in Windows. You can also just fix your npm permissions.
When writing this tutorial create-react-app v3.1.1 was installed.
Step 2 - Initializing a New React Project
In the second step, we'll initialize a new React project.
Head over to your command-line interface and execute the following command:
$ create-react-app react-graphql-example
Next, run the local development server using the following commands:
$ cd react-graphql-example $ npm start
The development server will be running from the address.
This is a screenshot of the React application in a web browser:
Check out how to consume a REST API with React and Axios.
Step 3 - Setting up The Apollo Client
In this step, we'll set up the Apollo client.
Apollo Client is a data management solution designed for GraphQL.
Apollo provides intelligent caching that enables it to be a single source of truth for the local and remote data in your application.
These are the required libraries for setting up Apollo:
- graphql: The GraphQL implementation in JavaScrip,
- apollo-client: A GraphQL client that supports React and other libraries,
- apollo-cache-inmemory: A cache implementation for Apollo Client,
- apollo-link-http: The most common Apollo Link, a system of modular components for GraphQL networking.
- react-apollo: This library provides the integrations for Apollo in React,
- graphql-tag: This library exports multiple utilities for working with GraphQL queries.
Head over to a new command-line interface and install the mentionned libraries using the following commands:
$ npm install graphql --save $ npm install graphql-tag --save $ npm install apollo-client --save $ npm install apollo-link-http --save $ npm install apollo-cache-inmemory --save $ npm install react-apollo --save
Step 4 - Initializing the Apollo Client with The In-Memory Cache and HTTP Link
In this step, we'll initialize the Apollo client.
Go to the
src/index.js file in your React project and start by adding the following imports:
import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { HttpLink } from 'apollo-link-http';
We simply import the Apollo client, in-memory cache and HTTP link libraries.
Next, initialize both the in-memory cache and the HTTP link as follows
const cache = new InMemoryCache(); const link = new HttpLink({ uri: '' })
We provide the URI of our GraphQL API to the HTTP link via the
uri parameter. This library is responsible for networking.
Finally, initialize the Apollo client as follows:
const client = new ApolloClient({ cache, link })
We simply create an instance of
ApolloClient and we pass the cache and link objects we previously created.
Step 5 - Linking the Apollo Client to React Component(s)
In this step, we'll link the Apollo Client, we created in the previous step, with our React component(s) using the new Apollo's hooks which allows us to easily make GraphQL operations from the UI.
Head back to the
src/index.js file in your React project and start by importing
ApolloProvider as follows:
import { ApolloProvider } from '@apollo/react-hooks';
Next, wrap the
App component with
ApolloProvider as follows:
/* [...] */ ReactDOM.render(<ApolloProvider client={client}><App /></ApolloProvider>, document.getElementById('root'));
Step 6 - Sending GraphQL Queries & Consuming the API
In this step, we'll see how to send GraphQL queries to consume the API.
Head to the
src/App.js file in your React project and add the following imports:
import { useQuery } from '@apollo/react-hooks'; import gql from "graphql-tag";
The
useQuery hook allows you to send a GraphQL query to the server while the
gql tag enables you to write multi-line GraphQL queries.
The
useQuery hook exposes the error, loading and data properties from a result object.
Next, add the following example GraphQL query in the
src/App.js file:
const EXAMPLE_QUERY = gql` { pokemons(first: 90) { id number name, image } }
This query will allow you to get the first 90 pokémons with their id, number, name, and image.
Next, execute the GraphQL query using the
useQuery hook as follows:
function App() { const { data, loading, error } = useQuery(EXAMPLE_QUERY); if (loading) return <p>Still loading..</p>; if (error) return <p>There is an error!</p>;
We simply destructure the object returned from the
useQuery() hook to get the data, loading and error attributes.
When
true i.e when data is still being received, the
App component will render Still loading...
If there is an error the component will render There is an error!.
Otherwise we'll have our data in the data variable which we can render as follows:
return ( <React.Fragment> <div className="container"> {data && data.pokemons && data.pokemons.map((pokemon, index) => ( <div key={index}> <img src={pokemon.image} /> <div> <h3>{pokemon.name}</h3> </div> </div> ))} </div> </React.Fragment> );
Step 7 - Building the React Application
In this step, we'll see how to build your application.
Head over to your command-line interface and run the followng command:
$ npm run build
This command will output an optimized production-ready bundle in the
build folder of your React project that you can upload to your hosting server.
Conclusion
In this step by step tutorial, we've seen how to consume a GraphQL API in a React example application using the Apollo client and React hooks. | https://www.techiediaries.com/consuming-graphql-with-react-hooks-and-apollo-client/ | CC-MAIN-2021-39 | refinedweb | 1,156 | 50.46 |
gamma(), gamma_r(), gammaf(), gammaf_r()
Log gamma function
Synopsis:
#include <math.h> double gamma( double x ); double gamma_r( double x, int* signgam); float gammaf( float x ); float gammaf_r( float x, int* signgam);
Since:
BlackBerry 10.0.0
Arguments:
- x
- An arbitrary number.
- signgam
- (gamma_r(), gammaf_r() only) A pointer to a location where the function can store the sign of Γ(x).
Description:
The gamma() and gamma_r() functions return the natural log (ln) of the gamma() function and are equivalent to lgamma(). These functions return ln|Γ( x )|, where Γ(x) is defined as follows:
- For x > 0:
- For x < 1:
- n / (Γ( 1-x ) * sin( nx ))
The results converge when x is between 0 and 1. The Γ function has the property:
Γ(N) = Γ(N-1)×N
The gamma* functions compute the log because the Γ function grows very quickly.
The gamma() and gammaf() functions use the external integer signgam to return the sign of Γ(x), while gamma_r() and gammaf_r() use the user-allocated space addressed by signgamp.
The signgam variable isn't set until gamma() or gammaf() returns. For example, don't use the expression:
g = signgam * exp( gamma( x ));
to compute g = Γ( x )'. Instead, compute gamma() first:
lg = gamma(x); g = signgam * exp( lg );
Note that Γ(x) must overflow when x is large enough, underflow when -x is large enough, and generate a division by 0 exception at the singularities x a nonpositive integer.
Returns:
ln|Γ( x )|
Classification:
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/g/gamma.html | CC-MAIN-2018-17 | refinedweb | 265 | 62.27 |
Bless:
No installation instructions: this port has been deleted.
The package name of this deleted port was:
PKGNAME: bless
ONLY_FOR_ARCHS: nil
NOT_FOR_ARCHS: nil
distinfo: There is no distinfo for this port.
NOTE: FreshPorts displays only information on required and default dependencies. Optional dependencies are not covered.
===> The following configuration options are available for bless-0.6.0_4,1:
DOCS=on: Build and/or install documentation
===> Use 'make config' to modify these settings
gmake mono pathfix pkgconfig
Number of commits found: 45
Remove expired ports:
2015-12-30 www/ocsigen: Broken for more than 6 months
2015-12-30 devel/monodevelop-database: Broken for more than 6 months
2015-12-30 lang/cduce: Broken for more than 6 months
2015-12-30 science/hdf-java: Broken for more than 6 months
2015-12-30 math/p5-Math-Geometry-Planar-GPC-Polygon: Broken for more than 6
months
2015-12-30 www/eliom: Depends on broken and expiring www/ocsigen
2015-12-30 audio/py-fastaudio: Broken for more than 6 months
2015-12-30 devel/jgoodies-common: Broken for more than 6 months
2015-12-30 graphics/pinta: Broken for more than 6 months
2015-12-30 games/kanatest: Broken for more than 6 months
2015-12-30 editors/bless: Broken for more than 6 months
2015-12-30 security/burpsuite: Broken for more than 6 months
Deprecate ports broken for more than 6 months
- Fix configure with mono 4
- Mark BROKEN: Fails to build with mono 4
/usr/local/bin/mono builder/bless-builder.exe Bless -nowarn:0169
-d:ENABLE_UNIX_SPECIFIC
>> Building module Bless.Util...
Unhandled Exception:
System.ComponentModel.Win32Exception: Cannot find the specified file
at System.Diagnostics.Process.Start_shell (System.Diagnostics.ProcessStartInfo
startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
at System.Diagnostics.Process.Start_common
(System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process
process) [0x00000] in <filename unknown>:0
...
Reported by: pkg-fallout
Cleanup plist
Stagify.
Approved by: portmgr@ (blanket)
Remove indefinite articles and trailing periods from COMMENT, plus
minor COMMENT typos and surrounding whitespace fixes. Categories D-F.
CR: D196
Approved by: portmgr (bapt)
Convert to USES=mono
With hat: portmgr
-
Remove the created by me and update those header at the same time. I never
care about those header, so you even can claim that those were created by
you instead of me.
- packing list when NOPORTDOCS is defined.
Reported by: QAT
-.5.0
Changes from the 0.4.1 release include:
* Brand new plugin architecture (GUI and export).
* Export functionality (text and html, others with plugins).
* Reduced memory usage.
* Fixed garbled display issue.
* Localization support.
* New ways to select data ranges.
PR: 111586
Submitted by: Phillip Neumann
Project by: BSD# <>
- Move to LOCALBASE
- USE_GNOME+=gtksharp20
Project by: BSD# ()
Update to 0.4.1
- Patches have been merged upstream
Project by: BSD#
Remove USE_REINPLACE from all categories starting with E
Fix for increased language strictness introduced with Mono 1.1.13.6.
Fix for namespace changes in Mono 1.1.13
Mono.Unix.Statvfs => Mono.Unix.Native.Statvfs
Mono.Unix.Syscall.statvfs => Mono.Unix.Native.Syscall.statvfs
Project by: BSD# <>
Update to 0.4.0
- Uses GTK# 2 (gtk-sharp20)
- New toolbar added
- Pattern highlighting based on current selection
Project by: BSD# <>
Add SHA256 to my BSD# ports
Project by: BSD# <>
- Update to 0.3.6
- to 0.3.5.
Update to 0.3.4.
BSD# - Project by:
Backout my previous commit, it required mono 1.1.x. I will have to move the
update 0.3.3 to BSD# ports tree.
Reported by: pointyhat via kris
Update to 0.3.3.
Bump PORTREVISION to chase the glib20 shared lib version change.
Update to 0.3.1.
Update to 0.3.0.
Update to 0.2.3.
Bump PORTREVISION to chase the gtkhtml3 shared library version.
Update to 0.2.2.
Bless:
Project by: BSD# -
Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD
14 vulnerabilities affecting 21 ports have been reported in the past 14 days
* - modified, not new
All vulnerabilities | http://www.freshports.org/editors/bless/ | CC-MAIN-2017-09 | refinedweb | 666 | 50.33 |
As part of managing binary and source backwards compatibility, we have @Internal, @Deprecated (and @deprecated javadoc), annotations.
We usually keep deprecated features around for at least 2 final releases before removing, but sometimes never get around to removing the deprecated features.
This bug will try to better track the revisit of deprecated elements.
From David North on the dev mailing list [1]:
> * Use the @Deprecated annotation in addition to the JavaDoc tag (which
> is useful for some IDEs anyway)
> * Invent our own @Removal annotation to contain the date/POI version of
> expected removal
>
> Then it would be easy to write a functional test which used reflection
> to check all @Deprecated annotated elements had an @Removal too, and to
> tell us when things come up as due to be removed.
Related: [2] finding the version when a feature was deprecated
[1]
[2]
Added @Removal annotation class in r1751569.
Usage:
/**
* @since POI 3.6
* @deprecated POI 3.15 beta 3
*/
@Removal(version="3.17")
public class SomeDeprecatedClassOrMethod() { }
Todo: write code that uses reflection to find code that is overdue for removal, and build this into a unit test.
Created attachment 34767 [details]
Find @Deprecated and @Removal annotations with reflection
The ClassFinder class in the patch uses non-free code. Do we have something already in POI test scaffolding that could give us a list of every org.apache.poi class (bonus points if it can include the o.a.p junit test code)?
If not, is there an ASL-2.0-licensed version that does something similar? Otherwise, we'll need to rewrite these couple lines of recursive class finding via reflection from scratch.
Doesn't the OOXMLLite code do something much like that only for the schema classes?
(In reply to Nick Burch from comment #4)
> Doesn't the OOXMLLite code do something much like that only for the schema
> classes?
Probably. The JDK, IDE, and JUnit also find all classes through recursive reflection, if OOXMLLite doesn't pan out. | https://bz.apache.org/bugzilla/show_bug.cgi?id=59804 | CC-MAIN-2020-40 | refinedweb | 329 | 54.83 |
Welcome to the next chapter in the series of tutorials on Log4j Loggers. I hope you have read at least Log4j Introduction and LogManager,
Lets get started. The next object in the Log4j component list is the Logger class. This is the most important class that you will need. This is the object which lets you log information to the required Log location, be it console or a file or even a database.
Logger objects follow hierarchy similar to class hierarchy in any OOP language. The naming convention of Logger hierarchy is in the name. Each object name decide which hierarchy it follows. For example, we have a logger named "Main.Utility". So Utility is the child of Main and Main is the father of Utility. Also, all Loggers are derived from root Logger. The actual hierarchy will be root.Main.Utility with root being an ancestor of Utility and Father of Main. This can be shown in a diagram as
These relationships are managed by the LogManager class. Let's illustrate it using an example
package Log4jSample; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; public class SampleEntry { public static void main(String[] args) { // TODO Auto-generated method stub Logger chance = LogManager.getLogger(SampleEntry.class.getName()); Logger logger1 = LogManager.getLogger("Child1"); Logger logger1Child = logger1.getLogger("Child1.ChildOfLogger1"); Logger loggerGrandChild = LogManager.getLogger("Child1.ChildOfLogger1.GrandChild"); System.out.println("logger1's full name is " + logger1.getParent().getName()); System.out.println("logger1Child's full name is " + logger1Child.getParent().getName()); System.out.println("loggerGrandChild's full name is " + loggerGrandChild.getParent().getName()); } }
Output will be
As you can see that logger1 is the parent of logger1Child and grandparent of loggerGrandChild's. This is how we can create hierarchy of logger objects based on the application need.
Logging levels
Logger class have following print methods that help you log information.
- Trace
- Debug
- Info
- Warn
- Error
- Fatal
So let's say you want to print a Debug log you would just do it by saying, Logger.Debug("This is a debug log"). You may choose to use any other overloaded Logger.Debug() method. All these print statements are called Levels.
Question comes, why do we need log levels?
Each log level expects a certain type of information for e.g Debug level expects logging of that information which may help a programmer debug the application in case of failures. Similarly Error Level expects all the Errors to be logged using this level.
You can set log level of a logger using the Logger.setLevel method. Once you set the Log level of your logger only loggers with that and higher level will be logged. Log levels have following order TRACE < DEBUG < INFO < WARN < ERROR < FATAL.
Let's understand this with an example, in the code below we have set the level to DEBUG first and than WARN. You will see that only the logs which are at that or higher level will be logged. Here is Mylogger = LogManager.getLogger("DebugLogger"); //Setting up the log level of both loggers Mylogger.setLevel(Level.DEBUG); Mylogger.trace("This is the trace log - DEBUG"); Mylogger.debug("This is debug log - DEBUG"); Mylogger.info("This is info log - DEBUG"); Mylogger.warn("This is Warn log - DEBUG"); Mylogger.error("This is error log - DEBUG"); Mylogger.fatal("This is Fatal log - DEBUG"); Mylogger.setLevel(Level.WARN); Mylogger.trace("This is the trace log - WARN"); Mylogger.debug("This is debug log - WARN"); Mylogger.info("This is info log - WARN"); Mylogger.warn("This is Warn log - WARN"); Mylogger.error("This is error log - WARN"); Mylogger.fatal("This is Fatal log - WARN"); } }
Output looks like this
You can see that when Log level was DEBUG all the logs DEBUG to FATAL are displayed. Once the log level is set to WARN all the logs from WARNS to FATAL are displayed.
Log level Inheritance
As discussed in the previous chapters we know that Loggers follow hierarchy. Similarly, Log levels also follow a hierarchy, what I mean is that if a Level Hierarchy of a logger is not defined then it is picked from the Level of parent. Let's say we have two loggers
LoggerParent and LoggerParent.Child and let's say Logger LoggerParent has log level set to LoggerParent.setLevel(Level.WARN) to warn. Now if we don't set the Level of Logger child than the default logging Level of Child will be set to Level.WARN which is the Level of its parent.
Let's see this with"); Logger LoggerChild = LogManager.getLogger("LoggerParent.Child"); //Setting up the log level of both loggers LoggerParent.setLevel(Level.WARN); LoggerParent.trace("This is the trace log - PARENT"); LoggerParent.debug("This is debug log - PARENT"); LoggerParent.info("This is info log - PARENT"); LoggerParent.warn("This is Warn log - PARENT"); LoggerParent.error("This is error log - PARENT"); LoggerParent.fatal("This is Fatal log - PARENT"); LoggerChild.trace("This is the trace log - CHILD"); LoggerChild.debug("This is debug log - CHILD"); LoggerChild.info("This is info log - CHILD"); LoggerChild.warn("This is Warn log - CHILD"); LoggerChild.error("This is error log - CHILD"); LoggerChild.fatal("This is Fatal log - CHILD"); } }
Output of this sample is
Logging run time Exceptions
This is a very important feature of a Logger class, it enables you to pass on the exception to the output. This comes handy specifically in the cases where we have intentionally caught the exception but we also want to log the information about the exception. Every print method (TRACE, DEBUG.... FATAL) has an overload which is Logger.Debug(Object message, Throwable t), off course we have just taken the example of .Debug only, this allows us to pass the exception. Let's see how it's beneficial using"); try { // We will get a divide by zero exception her int x = 200 / 0; } catch(Exception exp) { LoggerParent.warn("Following exception was raised", exp); } } }
As you can see that in the output you will see exception details being logged. This information is very handy while debugging. Important point to observe is that Exception message and the Line number of exception is printed automatically. Output of above code is
I hope this tutorial gives you an idea about Logger class. If you have any comment do drop me an email. Hope to see you in the next tutorial.
Similar Articles
| https://www.toolsqa.com/selenium-webdriver/log4j-loggers/ | CC-MAIN-2022-27 | refinedweb | 1,047 | 52.26 |
Given a frame of 8-bit 4:2:2 YUV pixels, does anyone have some code that would read the Y, U and V components of the individual pixels?
Thank you.
Try DVDFab Video Downloader and rip Netflix video! Or Try DVDFab and copy Blu-rays! or rip iTunes movies!
+ Reply to Thread
Results 1 to 30 of 67
Thread
-
Last edited by pandy; 6th Nov 2018 at 13:41.
I can't get this to work:
Code:
indx = 0 For ycoord = 0 To #HEIGHT - 1 For x = 0 To #WIDTH - 1 y = frame(indx) ;// y is an unsigned 8-bit byte Plot (x, ycoord, RGB(y,y,y)); DRAW BLACK & WHITE MONITOR indx + 2
I see an image but it is misframed. The video was encoded at 4:2:2 using ffmpeg's pix_fmt yuv422p. The frame is read in using ffmpeg.
I got similar code to work in 4:2:0.
What am I doing wrong?
-
I recoded it as follows to read consecutive planar pixels and no joy:
Code:
indx = 0 For ycoord = 0 To #HEIGHT - 1 For x = 0 To #WIDTH - 1 y = frame(indx) ;// y is an unsigned 8-bit byte Plot (x, ycoord, RGB(y,y,y)); DRAW BLACK & WHITE MONITOR indx + 1
According to the Microsoft page I linked to, YUY2 is the preferred format.
There is no YUY2 in ffmpeg's list of pixel formats:
Code:
Pixel formats: I.... = Supported Input format for conversion .O... = Supported Output format IO... uyvy422 3 16 ..... uyyvyy411 3 12 IO... bgr8 3 8 .O..B bgr4 3 4 IO... bgr4_byte 3 4 IO... rgb8 3 8 .O..B rgb4 3 4 IO... rgb4_byte 3 4 IO... nv12 3 12 IO... nv21 3 12 IO... argb 4 32 IO... rgba 4 32 IO... abgr 4 32 IO... bgra 4 32 IO... gray16be 1 16 IO... gray16le 1 16 IO... yuv440p 3 16 IO... yuvj440p 3 16 IO... yuva420p 4 20 IO... rgb48be 3 48 IO... rgb48le 3 48 IO... rgb565be 3 16 IO... rgb565le 3 16 IO... rgb555be 3 15 IO... rgb555le 3 15 IO... bgr565be 3 16 IO... bgr565le 3 16 IO... bgr555be 3 15 IO... bgr555le 3 15 ..H.. vaapi_moco 0 0 ..H.. vaapi_idct 0 0 ..H.. vaapi_vld 0 0 IO... yuv420p16le 3 24 IO... yuv420p16be 3 24 IO... yuv422p16le 3 32 IO... yuv422p16be 3 32 IO... yuv444p16le 3 48 IO... yuv444p16be 3 48 ..H.. dxva2_vld 0 0 IO... rgb444le 3 12 IO... rgb444be 3 12 IO... bgr444le 3 12 IO... bgr444be 3 12 IO... ya8 2 16 IO... bgr48be 3 48 IO... bgr48le 3 48 IO... yuv420p9be 3 13 IO... yuv420p9le 3 13 IO... yuv420p10be 3 15 IO... yuv420p10le 3 15 IO... yuv422p10be 3 20 IO... yuv422p10le 3 20 IO... yuv444p9be 3 27 IO... yuv444p9le 3 27 IO... yuv444p10be 3 30 IO... yuv444p10le 3 30 IO... yuv422p9be 3 18 IO... yuv422p9le 3 18 IO... gbrp 3 24 IO... gbrp9be 3 27 IO... gbrp9le 3 27 IO... gbrp10be 3 30 IO... gbrp10le 3 30 IO... gbrp16be 3 48 IO... gbrp16le 3 48 IO... yuva422p 4 24 IO... yuva444p 4 32 IO... yuva420p9be 4 22 IO... yuva420p9le 4 22 IO... yuva422p9be 4 27 IO... yuva422p9le 4 27 IO... yuva444p9be 4 36 IO... yuva444p9le 4 36 IO... yuva420p10be 4 25 IO... yuva420p10le 4 25 IO... yuva422p10be 4 30 IO... yuva422p10le 4 30 IO... yuva444p10be 4 40 IO... yuva444p10le 4 40 IO... yuva420p16be 4 40 IO... yuva420p16le 4 40 IO... yuva422p16be 4 48 IO... yuva422p16le 4 48 IO... yuva444p16be 4 64 IO... yuva444p16le 4 64 ..H.. vdpau 0 0 IO... xyz12le 3 36 IO... xyz12be 3 36 ..... nv16 3 16 ..... nv20le 3 20 ..... nv20be 3 20 IO... rgba64be 4 64 IO... rgba64le 4 64 IO... bgra64be 4 64 IO... bgra64le 4 64 IO... yvyu422 3 16 I.... ya16be 2 32 I.... ya16le 2 32 IO... gbrap 4 32 IO... gbrap16be 4 64 IO... gbrap16le 4 64 ..H.. qsv 0 0 ..H.. mmal 0 0 ..H.. d3d11va_vld 0 0 ..H.. cuda 0 0 IO... 0rgb 3 24 IO... rgb0 3 24 IO... 0bgr 3 24 IO... bgr0 3 24 IO... yuv420p12be 3 18 IO... yuv420p12le 3 18 IO... yuv420p14be 3 21 IO... yuv420p14le 3 21 IO... yuv422p12be 3 24 IO... yuv422p12le 3 24 IO... yuv422p14be 3 28 IO... yuv422p14le 3 28 IO... yuv444p12be 3 36 IO... yuv444p12le 3 36 IO... yuv444p14be 3 42 IO... yuv444p14le 3 42 IO... gbrp12be 3 36 IO... gbrp12le 3 36 IO... gbrp14be 3 42 IO... gbrp14le 3 42 IO... yuvj411p 3 12 I.... bayer_bggr8 3 8 I.... bayer_rggb8 3 8 I.... bayer_gbrg8 3 8 I.... bayer_grbg8 3 8 I.... bayer_bggr16le 3 16 I.... bayer_bggr16be 3 16 I.... bayer_rggb16le 3 16 I.... bayer_rggb16be 3 16 I.... bayer_gbrg16le 3 16 I.... bayer_gbrg16be 3 16 I.... bayer_grbg16le 3 16 I.... bayer_grbg16be 3 16 ..H.. xvmc 0 0 IO... yuv440p10le 3 20 IO... yuv440p10be 3 20 IO... yuv440p12le 3 24 IO... yuv440p12be 3 24 IO... ayuv64le 4 64 ..... ayuv64be 4 64 ..H.. videotoolbox_vld 0 0 IO... p010le 3 15 IO... p010be 3 15 IO... gbrap12be 4 48 IO... gbrap12le 4 48 IO... gbrap10be 4 40 IO... gbrap10le 4 40 ..H.. mediacodec 0 0 IO... gray12be 1 12 IO... gray12le 1 12 IO... gray10be 1 10 IO... gray10le 1 10 IO... p016le 3 24 IO... p016be 3 24 ..H.. d3d11 0 0 IO... gray9be 1 9 IO... gray9le 1 9 ..... gbrpf32be 3 96 ..... gbrpf32le 3 96 ..... gbrapf32be 4 128 ..... gbrapf32le 4 128 ..H.. drm_prime 0 0 ..H.. opencl 0 0
-
FFmpeg pixel format constants with exhaustive explanations.
Thanks fellas, but no improvement with YUYV422.
The image should fill the window in the upper left corner of the screen as it does in my 4:2:0 version.
Here is the complete code:
Code:
D:\Programs\ffmpeg\BroadcastVideo\ffmpeg -y -i "D:\Videos\Trains\December_6_2018_San_Jose"
-
-
-
-
-
-
-
-
btw camera sensors to read faster from sensor can provide interleaved samples... check this if there is no vertical/horizontal interleaving.
What are eye bulbs, Pandy?
Here, you tell me if it's interlaced.
Code:
ffprobe version 4.1 Copyright (c) 2007-2018 the FFmpeg developers built with gcc 8.2.1 (GCC) 20181017-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth, avi, from '12M.avi': Metadata: encoder : Lavf58.12.100 Duration: 00:00:59.06, start: 0.000000, bitrate: 335746 kb/s Stream #0:0: Video: utvideo (ULH2 / 0x32484C55), yuv422p(bt709/unknown/unknown), 1280x720, 333514 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 59.94 tbn, 59.94 tbc Stream #0:1: Audio: pcm_s24le ([1][0][0][0] / 0x0001), 48000 Hz, stereo, s32 (24 bit), 2304 kb/s
You need to analyse motion (difference between fields over time) to say if this is interlace or progressive. It can be progressive but interleaved then you need to deinterleave RAW video. Sensor may read values as ODD/EVEN in Horizontal and ODD/EVEN in Vertical direction.
you should have detailed information from camera sensor vendor - it is called datasheet - for example
And eye bulbs are your own eyes - this is final judge so analyse few frames even manually for dependencies...
-
The video is being resized by ffmpeg to 1280 x 720. Here is the ffmpeg command:
ffmpeg -y -i"
Take note of the -r 59.94. Does that mean 59.94 fields (interlaced) or frames (progressive)?
Would a video player need to know if interlaced or not to play back correct images, unlike the ones I'm getting? A video player can't determine this by staring with its eye bulbs.
What does the image look like when viewed in a media player or other editor?
I'm still not sure what that image is supposed to be showing. I originally thought it was two videos viewed side by side, like a before and after comparison (with chroma channels at the top, luma below). But now I think you're saying it's just one video. But why is the greyscale area 32:9, not 16:9 like source your video?
I checked ffmpeg's yuyv422 output and it is indeed the same as YUY2. At least when I exported as AVI. Even if the video was interlaced it would not show up as two videos side by side. You would just see comb artifacts when viewing at full scale.
Maybe you should upload a raw source clip and your ffmpeg conversion.
-
-
- What does the image look like when viewed in a media player or other editor?
My program scans the bitmap from y = 0 to 719 and from x = 0 to 1279. It then draws to the screen at y/2 and x/2 to fit in the upper quadrant of the screen (360 x 640) and that's what you're seeing. This technique works wonderfully well if the pixels are 4:2:0, so it's not the way I'm drawing to screen.
I posted my code previously.
Your feedback made me laugh as i realised how hilarious this may look for English speaker.
Apologies for being OT - sorry chris319
A possible issue is that your source is compressed with UT. What comes out of the decompressor may not be YUY2, even if that's what went in. Attached a raw 1280x720 YUY2 file (the first frame of processed.mkv) and an AviSynth that reads it with RawSource(). See if you can render that raw YUY2 data correctly.
- The code in post #3 plots at x,y, not y/2,y/2.
A possible issue is that your source is compressed with UT. What comes out of the decompressor may not be YUY2, even if that's what went in.
Similar program with 4:2:0 pixels in full color, what it's supposed to look like when finished.
Right now I can't even get the black-and-white pixels to render properly.
Oops, got distracted and forgot the attachment.
Also verified with a quick and dirty C program:
Code:
#include <stdio.h> #include <stdlib.h> #define IMAGE_WIDTH 1280 #define IMAGE_HEIGHT 720 unsigned char YUY2[IMAGE_HEIGHT][IMAGE_WIDTH*2]; unsigned char Y8[IMAGE_HEIGHT][IMAGE_WIDTH]; int main(void) { FILE *infd, *outfd; infd = fopen("1280x720yuy2.raw", "rb"); outfd = fopen("1280x720y8.raw", "wb"); fread(YUY2, 1, IMAGE_HEIGHT*IMAGE_WIDTH*2, infd); for (int y=0; y<IMAGE_HEIGHT; y++) { for (int x=0; x<IMAGE_WIDTH; x++) { Y8[y][x] = YUY2[y][x*2]; } } fwrite(Y8, 1, IMAGE_WIDTH*IMAGE_HEIGHT, outfd); fclose(infd); fclose(outfd); }
Similar Threads
Confused about the pixelsBy patrick in forum Newbie / General discussionsReplies: 36Last Post: 13th Feb 2017, 18:32
Game lag pixels.By Jappyanime in forum ComputerReplies: 13Last Post: 20th Nov 2015, 14:04
Block of pixels!By alkoon in forum CapturingReplies: 3Last Post: 12th Aug 2015, 22:22
Twinkling pixels - 59iHz vs 59pHzBy VFRBoy in forum ComputerReplies: 2Last Post: 11th Jul 2015, 04:38 | https://forum.videohelp.com/threads/390789-Reading-4-2-2-Pixels?s=186479da6b6ce17ae8cf847422c028c7 | CC-MAIN-2021-04 | refinedweb | 1,806 | 89.85 |
Tutorials > C++ > Arithmetic Operators
It is almost impossible to create a program that has any use without needing to
use some sort of arithmetic. A great deal of mathematics is involved with programming.
This tutorial will explain how to accomplish basic arithmetic in C / C++.
Contents of main.cpp :
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
We will be using integers for this tutorial.
Many other data types such as floats and doubles may also be used.
Even a char has a numerical value known as the ascii
value.
// Variable Declarations
//-----------------------
int x = 10;
int y = 5;
int z = 0;
The basic arithmetic operators can be shown in the following table :
An arithmetic expression can consist of static values as well as variables. You can
imagine that the result of the expression replaces it eg.
If x = 5 and y = 10, then z = x + y will evaluate to z = 5 + 10 which will
consequently evaluate to z = 15.
I have purposely placed the * and / first as they
are in the order of precedence. At school you learnt that multiplication and division should be
calculated before addition and subtraction. 5 - 3 * 2 is therefore calculated
as 5 - (3 * 2) and NOT as (5 - 3) * 2.
You can also place brackets in your expression to explicitly state what operations should occurr when. This is better
practice, even if it is not necessary.
// Add, Subtract,
// Multiply & Divide
//-------------------
z = x + y;
cout << "10 + 5 = " << z << endl;
z = x - y;
cout << "10 - 5 = " << z << endl;
z = x * y;
cout << "10 + 5 = " << z << endl;
z = x / y;
cout << "10 / 5 = " << z << endl;
As the var = var {operator} {expression} is used
quite often, other operators are available. Remember that a single number
is also an expression in itself. These operators include
*= /= += -=
If you had to explain the operator, you could say operator by
eg. multiply by, divide by, increase by, etc. Our example below increases z by 5.
z = 5;
z += 5;
cout << "5 + 5 = " << z << endl;
Other operator effects are more easily seen be looking at the binary representation
of a number. If you do not understand why 22 is equal to 10110, please e-mail me
and I'll put up a tutorial on binary numbers. If I do not receive an e-mail, I'll
assume that you know how to represent decimal numbers as binary numbers.
x = 22; // 10110
y = 17; // 10001
Just before we delve into the binary part, another operator MOD can be used.
This operator is used by placing a % character. For those
who do not know what the MOD operator is, it is essentially the
remainder of a division expression.
eg. 10 / 3 = 3 remainder 1
10 / 3 would therefore return 3 and 10 % 3 would return 1.
// Mod
//-----
cout << "10 MOD 5 = " << 10 % 5 << endl;
cout << "11 MOD 5 = " << 11 % 5 << endl;
I am going to briefly explain the binary operators. Once again, if you are not happy
with it, you can e-mail me and I will put up a separate tutorial on binary arithmetic.
The & operator is known as the Bitwise AND operator. The result
is only 1 if both operands are 1.
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
Therefore :
// Binary AND, OR and XOR
//------------------------
cout << "22 & 17 = " << (x & y) << endl;
The | operator is known as the Bitwise OR operator.
The result is 0 only if both operands are 0.
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
cout << "22 | 17 = " << (x | y) << endl;
The ^ operator is known as the Bitwise XOR operator.
The result is 1 only if the operands are different.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
cout << "22 ^ 17 = " << (x ^ y) << endl;
Other operators that we will discuss are the increment (++) and decrement (--)
operators.
This operator has the form :
var++ or var--
These operators will add or subtract exactly 1 from the
variable. You can also place the operator before the variable instead of afterwards.
Placing the operator after the variable will cause the variable to only increment
after the current line has been processed.
Our first line therefore increases x to 23 and then prints it out.
Our second line shows us what happens if we place the ++
after the variable. It displays the current value and then increments it. We
see the new value by looking at the 3rd line.
// Increment Operator
//--------------------
cout << "22 + 1 = " << ++x << endl;
cout << "x = " << x++ << endl;
cout << "x + 1 = " << x << endl;
The next code segment shows the power of operator precedence. The 30 / 20
is calculated before the addition of the 5. If you wanted to add 5 to 30 first, you would
need to rewrite the line as :
z = ((5 + 30) / 20);
z = (5 + 30 / 20);
cout << "5 + 30 / 20 = " << z << endl;
You may have noticed from the above code segment that the 30 / 20
produces 1 and not 1.5 as you
may suspect. This is because you are operating on 2 integers.
The result of an operation is always converted to the biggest of the two operands.
We can therefore solve this problem by using 20.0 instead of 20.
This causes 20 to be seen as a double. This allows the
operation of the 30 / 20 to be converted to a double, therefore
returning the desired result.
cout << "5 + 30 / 20.0 = " <<
(5 + 30 / 20.0) << endl;
system("pause");
return 0;
}
You should now be able to accomplish basic Arithmetic in C / C++. I hope you
found the tutorial useful as it took quite a while to put it together.
Do not forget about how important brackets are and how operator precedence works.
Also remember that the increment and decrement operators can be placed both before
and after the variable.
Please let me know of any comments you may have : Contact Me
Back to Top
Read the Disclaimer | http://www.zeuscmd.com/tutorials/cplusplus/11-ArithmeticOperators.php | CC-MAIN-2016-50 | refinedweb | 985 | 72.16 |
Basemap is a Matplotlib toolkit, a collection of application-specific functions that extends Matplotlib functionalities, and its complete documentation is available at.
Toolkits are not present in the default Matplotlib installation (in fact, they also have a different namespace, mpl_toolkits), so we have to install Basemap separately. We can download it from, under the matplotlib-toolkits menu of the download section, and then install it following the instructions in the documentation link mentioned previously.
Basemap is useful for scientists such as oceanographers and meteorologists, but other users may also find it interesting. For example, we could parse the Apache log and draw a point on a map using GeoIP localization for each connection.
We use the 0.99.3 version of Basemap for our examples.
First example
Let's start playing with the library. It contains a lot of things that are very specific, so we're going to just give an introduction to the basic functions of Basemap.
# pyplot module import
import matplotlib.pyplot as plt
# basemap import
from mpl_toolkits.basemap import Basemap
# Numpy import
import numpy as np
These are the usual imports along with the basemap module.
# Lambert Conformal map of USA lower 48 states
m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64,
urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45,
lon_0=-95, resolution='h', area_thresh=10000)
Here, we initialize a Basemap object, and we can see it has several parameters depending upon the projection chosen.
Let's see what a projection is: In order to represent the curved surface of the Earth on a two-dimensional map, a map projection is needed.
This conversion cannot be done without distortion. Therefore, there are many map projections available in Basemap, each with its own advantages and disadvantages. Specifically, a projection can be:
- equal-area (the area of features is preserved)
- conformal (the shape of features is preserved)
No projection can be both (equal-area and conformal) at the same time.
In this example, we have used a Lambert Conformal map. This projection requires additional parameters to work with. In this case, they are lat_1, lat_2, and lon_0.
Along with the projection, we have to provide the information about the portion of the Earth surface that the map projection will describe. This is done with the help of the following arguments:
The last two arguments are:
# draw the coastlines of continental area
m.drawcoastlines()
# draw country boundaries
m.drawcountries(linewidth=2)
# draw states boundaries (America only)
m.drawstates()
We start adding features to the map. In this case, we have just added:
- The coast lines
- The country borders (with a bigger line style)
- The state borders inside the country (they are only available for America)
# fill the background (the oceans)
m.drawmapboundary(fill_color='aqua')
# fill the continental area
# we color the lakes like the oceans
m.fillcontinents(color='coral',lake_color='aqua')
We give some colors to our map. We color the ocean with aqua color and the interior of the continents are coral (but lakes have the same color of the ocean).
# draw parallels and meridians
m.drawparallels(np.arange(25,65,20),labels=[1,0,0,0])
m.drawmeridians(np.arange(-120,-40,20),labels=[0,0,0,1])
We draw a 20 degrees graticule of parallels and meridians for the map. Note how the labels argument controls the positions where the graticules are labeled. labels is an array having four elements:
[left, right, top, bottom]
These elements define the label of the parallels and the meridian when they intersect the borders of the plot. In this case, parallels are labeled when they intersect the left border and meridians are labeled at the bottom.
After adding a title to it, the result is as shown:
Using satellite background
Basemap can also use a terrain image as a map background.
m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64,
urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45,
lon_0=-95, resolution='h', area_thresh=10000)
We are using the same map as before.
# display blue marble image (from NASA) as map background
m.bluemarble()
We add the satellite images taken from the NASA images library.
# draw the coastlines of continental area
m.drawcoastlines()
# draw country boundaries
m.drawcountries(linewidth=2)
# draw states boundaries (America only)
m.drawstates()
Then, we draw the Basemap features over it, as done before, and this results in a very pretty image, as shown in the following screenshot:
Plot data over a map
We got to know Matplotlib as a tool that can plot datasets easily. It would be really nice if we can mix this with Basemap projections. Well, of course it's possible, and this is how it is done.
We need some geographical data to plot over a map, so we take a group of cities, and we'll plot them on a map. The cities along with their coordinates (taken from Wikipedia) are:
From the previous table, we can prepare these three lists:
# Cities names and coordinates
cities = ['London', 'New York', 'Madrid', 'Cairo', 'Moscow',
'Delhi', 'Dakar']
lat = [51.507778, 40.716667, 40.4, 30.058, 55.751667,
28.61, 14.692778]
lon = [-0.128056, -74, -3.683333, 31.229, 37.617778,
77.23, -17.446667]
where we have recorded the names and coordinates of different cities.
# orthogonal projection of the Earth
m = Basemap(projection='ortho', lat_0=45, lon_0=10)
We now prepare a map using an orthogonal projection that displays the Earth in the way a satellite would see it. The additional arguments, lat_0 and lon_0, represent the points at the center of the projection (what the satellite looks down at).
# draw the borders of the map
m.drawmapboundary()
# draw the coasts borders and fill the continents
m.drawcoastlines()
m.fillcontinents()
We then draw the map's border (the edge of the map projection region) and the coastal lines, and then fill the continents.
# map city coordinates to map coordinates
x, y = m(lon, lat)
Here we convert the latitude and longitudes of the different cities into map domain coordinates—in particular, note that the resulting lists are values in meters on the map.
Calling a Basemap instance with arrays of longitudes and latitudes returns those locations in the native map projection coordinates.
# draw a red dot at cities coordinates
plt.plot(x, y, 'ro')
Now that we have the cities' locations in the map coordinates, we can plot a red dot at their positions.
# for each city,
for city, xc, yc in zip(cities, x, y):
# draw the city name in a yellow (shaded) box
plt.text(xc+250000, yc-150000, city,
bbox=dict(facecolor='yellow', alpha=0.5))
We also want to display the name of the city next to the point in the map. In order to do this, we use the text() function to write the name of the city (inside a nice yellow box, a bit translucent because of the alpha channel) next to the points position. Note the big numbers that are used to adapt the text's position. They need a little bit of hand tweaking and remember that they are in meters.
The following image is created as a result of executing the preceding code:
Plotting shapefiles with Basemap
Through the DATA.gov portal, the US government is releasing a huge quantity of high quality datasets that are free to use and analyze. Some of the datasets contain geographical information in a particular format: Shapefile.
A Shapefile, which commonly refers to a collection of files, is a popular geospatial data format for Geographical Information Systems (GIS).
Shapefiles store geometrical primitives such as points, lines, and polygons (the shapes) to represent a geographical feature in a dataset. Each item can also have attributes and information associated to it, which are used to describe what it represents.
We will use the dataset available at the URL. It represents the locations of the copper smelters in the world (it also contains several other attributes and characteristics about the smelters, but we are not going to use them here).
# the map, a Miller Cylindrical projection
m = Basemap(projection='mill',
llcrnrlon=-180. ,llcrnrlat=-60,
urcrnrlon=180. ,urcrnrlat=80.)
We use a map from a Miller cylindrical projection. We limit the latitude (while keeping the world-wide longitude) because the excluded areas don't have smelters, and so we have more space for the zones where they are present.
# read the shapefile archive
s = m.readshapefile('<location of shapefile>/copper', 'copper')
Reading a shapefile is as simple as calling the readshapefile() function and passing the shapefile location. The additional argument (in this case, copper) is the name of the map attribute that will be created to hold the shapefiles' vertices and features. m.copper will contain the smelters locations in map domain coordinates, while s contains only general information about the Shapefile.
# prepare map coordinate lists for copper smelters locations
x, y = zip(*m.copper)
We prepare a list of coordinates (in the map domain) for the copper smelters locations; zip() receives the m.copper array unpacked (each sublist is passed as a separate parameter to zip()).
# draw coast lines and fill the continents
m.drawcoastlines()
m.fillcontinents()
We draw the coast lines and fill the continents
# draw a blue dot at smelters location
plt.plot(x, y, 'b.')
We can then draw a blue dot at the smelters' locations.
When we run the example, we can see a map with dots (in blue) that represent the places where the smelters are located:
Summary
In this article, we have seen how to plot geographical data using Basemap.
If you have read this article you may be interested to view : | https://www.packtpub.com/books/content/plotting-geographical-data-using-basemap | CC-MAIN-2015-32 | refinedweb | 1,597 | 54.63 |
0
vb.net: I have a task to take the given xsd file and use that to validate my generated xml file. But now this xsd file has complex type attributes and I cant get to append this complex type to my declared xmlnode.
My Code:
Dim namespaceURI As String = "" Dim odoc As New XmlDocument Dim aschema As XmlSchema = XmlSchema.Read(New FileStream(xsdFilePath, FileMode.Open), Nothing) odoc.Schemas.Add(aschema) Dim oRoot As XmlNode = odoc.CreateNode(XmlNodeType.Element, "RootName", namespaceURI) odoc.AppendChild(oRoot) ... ... ' HERES MY PROBLEM Dim oSubRoot As XmlNode = odoc.CreateNode(XmlNodeType.Element, "SubRootName", namespaceURI) oRoot.AppendChild(oSubRoot)
This oSubRoot has a Complex Type "Person" ~ I then create this Persons Class but how do I append this class to the oSubRoot node? When I run my code I get this error on my xml file validation
Error: The element '' is abstract or its type is abstract.
I am still new in xml and would like to know what is the best practice for achieving this task. | https://www.daniweb.com/programming/software-development/threads/265151/xsd-to-xml-using-net | CC-MAIN-2017-17 | refinedweb | 168 | 67.25 |
Learning Python by example: list comprehensions
My friend, who is starting to learn Python 2.x, asked me what this snippet did:
def collapse(seq): # Preserve order. uniq = [] [uniq.append(item) for item in seq if not uniq.count(item)] return uniq
This is not a snippet that should be emulated (i.e. it's bad); however, it makes me happy: there are so many things that can be informatively corrected!
What is a list comprehension?
A list comprehension is a special brackety syntax to perform a transform operation with an optional filter clause that always produces a new sequence (list) object as a result. To break it down visually, you perform:
new_range = [i * i for i in range(5) if i % 2 == 0]
Which corresponds to:
*result* = [*transform* *iteration* *filter* ]
The filter piece answers the question, "should this item be transformed?" If the answer is yes, then the transform piece is evaluated and becomes an element in the result. The iteration [*] order is preserved in the result.
Go ahead and figure out what you expect new_range to be in the prior example. You can double check me in the Python shell, but I think it comes out to be:
>>> new_range = [i * i for i in range(5) if i % 2 == 0] >>> print new_range [0, 4, 16]
If it still isn't clicking, we can try to make the example less noisy by getting rid of the transform and filter — can you tell what this will produce?
>>> new_range = [i for i in range(5)]
So what's wrong with that first snippet?
As we observed in the previous section, a list comprehension always produces a result list, where the elements of the result list are the transformed elements of the iteration. That means, if there's no filter piece, there are exactly as many result elements as there were iteration elements.
Weird thing number one about the snippet — the list comprehension result is unused. It's created, mind you — list comprehension always create a value, even if you don't care what it is — but it just goes off to oblivion. (In technical terms, it becomes garbage.) When you don't need the result, just use a for loop! This is better:
def colapse(seq): """Preserve order.""" uniq = [] for item in seq: if not uniq.count(item): uniq.append(item) return uniq
It's two more lines, but it's less weird looking and wasteful. "Better for everybody who reads and runs your code," means you should do it.
Moral of the story: a list comprehension isn't just, "shorthand for a loop." It's shorthand for a transform from an input sequence to an output sequence with an optional filter. If it gets too complex or weird looking, just make a loop. It's not that hard and readers of your code will thank you.
Weird thing number two: the transform, list.append(item), produces None as its output value, because the return value from list.append is always None. Therefore, the result, even though it isn't kept anywhere, is a list of None values of the same length as seq (notice that there's no filter clause).
Weird thing number three: list.count(item) iterates over every element in the list looking for things that == to item. If you think through the case where you call collapse on an entirely unique sequence, you can tell that the collapse algorithm is O(n2). In fact, it's even worse than it may seem at first glance, because count will keep going all the way to the end of uniq, even if it finds item in the first index of uniq. What the original author really wanted was item not in uniq, which bails out early if it finds item in uniq.
Also worth mentioning for the computer-sciency folk playing along at home: if all elements of the sequence are comparable, you can bring that down to O(n * log n) by using a "shadow" sorted sequence and bisecting to test for membership. If the sequence is hashable you can bring it down to O(n), perhaps by using the set datatype if you are in Python >= 2.3. Note that the common cases of strings, numbers, and tuples (any built-in immutable datatype, for that matter) are hashable.
From Python history
It's interesting to note that Python Enhancement Proposal (PEP) #270 considered putting a uniq function into the language distribution, but withdrew it with the following statement:.
Remember that sets can only contain hashable elements (same policy as dictionary keys) and are therefore not suitable for all uniq-ifying tasks, as mentioned in the last paragraph of the previous section. | http://blog.cdleary.com/2010/04/learning-python-by-example-list-comprehensions/ | CC-MAIN-2017-30 | refinedweb | 784 | 70.02 |
Decoupling HTML From CSS
- By Jonathan Snook
- April 20th, 2012
- 63 Comments
For1.
In this way, we haven’t really separated the two, have we? We have to make our changes in two places.
Exploring Approaches
Over the course of my career, I’ve had the pleasure and privilege to work on hundreds of different websites and Web applications. For the vast majority of these projects, I was the sole developer building out the HTML and CSS. I developed a way of coding websites that worked well for me.
Most recently, I spent two years at Yahoo working on Mail, Messenger, Calendar and other projects. Working on a much larger project with a much larger team was a great experience. A small team of prototypers worked with a larger team of designers to build out all of the HTML and CSS for multiple teams of engineers.
It was the largest-scale project I had worked on in many aspects:
- Yahoo’s user base is massive. Mail alone has about 300 million users.
- Hundreds of people spread across multiple teams were working with the HTML and CSS.
- We were developing a system of components to work across multiple projects.
It was during my time at Yahoo that I began to really examine how I and the team at Yahoo build websites. What pain points did we keep running into, and how could we avoid them?
I looked to see what everyone else was doing. I looked at Nicole Sullivan’s Object-Oriented CSS2, Jina Bolton’s presentation on “CSS Workflow3” and Natalie Downe’s “Practical, Maintainable CSS4,” to name just a few.
I ended up writing my thoughts as a long-form style guide named “Scalable and Modular Architecture for CSS5.” That sounds wordy, so you can just call it SMACSS (pronounced “smacks”) for short. It’s a guide that continues to evolve as I refine and expand on ways to approach CSS development.
As a result of this exploration, I’ve noticed that designers (including me) traditionally write CSS that is deeply tied to the HTML that it is designed to style. How do we begin to decouple the two for more flexible development with less refactoring?
In other words, how do we avoid throwing
!important at everything or falling into selector hell?
Reusing Styles
In the old days, we wrapped
font tags and applied
background attributes to every HTML element that needed styling. This was, of course, very impractical, and thus CSS was born. CSS enabled us to reuse styles from one part of the page on another.
For example, a navigation menu has a list of items that all look the same. Repeating inline styles on each item wouldn’t be practical. As a result, we begin to see CSS like this:
#nav { margin: 0; padding: 0; list-style: none; } #nav li { float: left; } #nav li a { display: block; padding: 5px 10px; background-color: blue; }
Sure beats adding
float:left to every list item and
display:block; padding:5px 10px; to every link. Efficiency, for the win! Just looking at this, you can see the HTML structure that is expected:
<ul id="nav"> <li><a href="/">Home</a></li> <li><a href="/products">Products</a></li> <li><a href="/contact">Contact Us</a></li> </ul>
Now, the client comes back and says, “I want a drop-down menu to appear when the user clicks on ‘Products.’ Give them easy access to each of the pages!” As a result, our HTML changes.
<ul id="nav"> <li><a href="/">Home</a></li> <li><a href="/products">Products</a> <ul> <li><a href="/products/shoes">Shoes</a></li> <li><a href="/products/jackets">Jackets</a></li> </ul> </li> <li><a href="/contact">Contact Us</a></li> </ul>
We now have a list item within a list item, and links within it. Our menu has a horizontal navigation when the client wants a vertical list, so we add some rules to style the inner list to match what the client wants.
#nav ul { margin: 0; padding:0; list-style:none; } #nav li li { float: none; } #nav li li a { padding: 2px; background-color: red; }
Problem solved! Sort of.
Reducing The Depth Of Applicability
Probably the most common problem with CSS is managing specificity. Multiple CSS rules compete in styling a particular element on the page. With our menu, our initial rules were styling the list items and the links in the navigation and the menu. Not good.
By adding more element selectors, we were able to increase specificity and have our menu styles win out over the navigation styles.
However, this can become a game of cat and mouse as a project increases in complexity. Instead, we should be limiting the impact of CSS. Navigation styles should apply to and affect only the elements that pertain to it, and menu styles should apply to and affect only the elements that pertain to it.
I refer to this impact in SMACSS as the “depth of applicability6.” It’s the depth at which a particular rule set impacts the elements around it. For example, a style like
#nav li a, when given an HTML structure that includes our menus, has a depth of 5: from the
ul to the
li to the
ul to the
li to the
a.
The deeper the level of applicability, the more impact the styles can have on the HTML and the more tightly coupled the HTML is to the CSS.
The goal of more manageable CSS — especially in larger projects — is to limit the depth of applicability. In other words, write CSS to affect only the elements that we want them to affect.
Child Selectors
One tool for limiting the scope of CSS is the child selector (
>). If you no longer have to worry about Internet Explorer 6 (and, thankfully, many of us don’t), then the child selector should be a regular part of your CSS diet.
Child selectors limit the scope of selectors. Going back to our navigation example, we can use the child selector to limit the scope of the navigation so that it does not affect the menu.
#nav { margin: 0; padding: 0; list-style: none; } #nav > li { float: left; } #nav > li > a { display: block; padding: 5px 10px; background-color: blue; }
For the menu, let’s add a class name to it. This will make it more descriptive and provide a base for the rest of our styles.
.menu { margin: 0; padding: 0; list-style: none } .menu > li > a { display: block; padding: 2px; background-color: red; }
What we’ve done is limited the scope of our CSS and isolated two visual patterns into separate blocks of CSS: one for our navigation list and one for our menu list. We’ve taken a small step towards modularizing our code and a step towards decoupling the HTML from the CSS.
Classifying Code
Limiting the depth of applicability helps to minimize the impact that a style might have on a set of elements much deeper in the HTML. However, the other problem is that as soon as we use an element selector in our CSS, we are depending on that HTML structure never to change. In the case of our navigation and menu, it’s always a list with a bunch of list items, with a link inside each of those. There’s no flexibility to these modules.
Let’s look at an example of something else we see in many designs: a box with a heading and a block of content after it.
<div class="box"> <h2>Sites I Like</h2> <ul> <li><a href="">Smashing Magazine</a></li> <li><a href="">SMACSS</a></li> </ul> </div>
Let’s give it some styles.
.box { border: 1px solid #333; } .box h2 { margin: 0; padding: 5px 10px; border-bottom: 1px solid #333; background-color: #CCC; } .box ul { margin: 10px; }
The client comes back and says, “That box is great, but can you add another one with a little blurb about the website?”
<div class="box"> <h2>About the Site</h2> <p>This is my blog where I talk about only the bestest things in the whole wide world.</p> </div>
In the previous example, a margin was given to the list to make it line up with the heading above it. With the new code example, we need to give it similar styling.
.box ul, .box p { margin: 10px; }
That’ll do, assuming that the content never changes. However, the point of this exercise is to recognize that websites can and do change. Therefore, we have to be proactive and recognize that there are alternative elements we might want to use.
For greater flexibility, let’s use classes to define the different parts of this module:
.box .hd { } /* this is our box heading */ .box .bd { } /* this is our box body */
When applied to the HTML, it looks like this:
<div class="box"> <h2 class="hd">About the Site</h2> <p class="bd">This is my blog where I talk about only the bestest things in the whole wide world.</p> </div>
Clarifying Intent
Different elements on the page could have a heading and a body. They’re “protected” in that they’re a child selector of
box. But this isn’t always as evident when we’re looking at the HTML. We should clarify that these particular
hd and
bd classes are for the
box module.
.box .box-hd {} .box .box-bd {}
With this improved naming convention, we don’t need to combine the selectors anymore in an attempt to namespace our CSS. Our final CSS looks like this:
.box { border: 1px solid #333; } .box-hd { margin: 0; padding: 5px 10px; border-bottom: 1px solid #333; background-color: #CCC; } .box-bd { margin: 10px; }
The bonus of this is that each of these rules affects only a single element: the element that the class is applied to. Our CSS is easier to read and easier to debug, and it’s clear what belongs to what and what it does.
It’s All Coming Undone
We’ve just seen two ways to decouple HTML from CSS:
- Using child selectors,
- Using class selectors.
In addition, we’ve seen how naming conventions allow for clearer, faster, simpler and more understandable code.
These are just a couple of the concepts that I cover in “Scalable and Modular Architecture for CSS7,” and I invite you to read more.
Postscript
In addition to the resources linked to above, you may wish to look into BEM8, an alternative approach to and framework for building maintainable CSS. Mark Otto has also been documenting the development of Twitter Bootstrap, including the recent article “Stop the Cascade9,” which similarly discusses the need to limit the scope of styles.
(al) (il)
Footnotes
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
↑ Back to topShare on Twitter | http://www.smashingmagazine.com/2012/04/20/decoupling-html-from-css/ | CC-MAIN-2014-42 | refinedweb | 1,806 | 69.92 |
This question has already been solved: Start a new discussion instead
computerbear
Junior Poster in Training
69 posts since Oct 2010
Reputation Points: 3 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
0
Question Self-Answered as of 2 Years Ago
Reputation Points: 5 [?]
Q&As Helped to Solve: 14 [?]
Skill Endorsements: 0 [?]
0
call
throw new BookException(Title, Price, Numpages);
declare
public class BookException : Exception { public BookException(string Title, double Price, double NumPages) : base (String.Format("Ratio for {0} is invalid. Price is {1} for {2} pages.", Title, Price, Numpages)) { } }
Why not inherit from ApplicationException in stead of the more generic Exception: you exception is actually a very particular ApplicationException.
You | http://www.daniweb.com/software-development/csharp/threads/362447/custom-exception-and-messaging | CC-MAIN-2014-15 | refinedweb | 113 | 52.26 |
XML-RPC Server App for the Django framework.
Project Description
Django_xmlrpc offers a means by which a Django developer can expose their views (or indeed any other function) using XML-RPC.
This is a fork of the original version made by Svetlyak40wt compatible with Django >= 1.8.
There are two ways to register methods that you want to handle:
In your project’s settings.
XMLRPC_METHODS = (('path.to.your.method', 'Method name'), ('path.to.your.othermethod', 'Other Method name'),)
In a file called xmlrpc.py in your application directory.
XMLRPC_METHODS = (('path.to.your.method', 'Method name'), ('path.to.your.othermethod', 'Other Method name'),)
A registered method should look like this:
from django_xmlrpc.decorators import xmlrpc_func @xmlrpc_func(returns='string', args=['string']) def test_xmlrpc(text): """Simply returns the args passed to it as a string""" return "Here's a response! %s" % str(text)
Finally we need to register the url of the XML-RPC server. Insert something like this in your project’s urls.py:
from django_xmlrpc.views import handle_xmlrpc url(r'^xmlrpc/$', handle_xmlrpc, name='xmlrpc'),
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-xmlrpc/ | CC-MAIN-2018-17 | refinedweb | 194 | 52.05 |
Good news: With the very latest gcc from Apple everything compiles without errors. Bad news: The problems in running the examples persist. For one fleeting moment I had everything in the example-directory up and running... Then I changed something :-( and broke my setup! However, I am confident that somewhat more knowledgeable can figure out the right flags for linking actions. (Yes, I was playing -undefined suppress -flat_namespace games when my house of cards fell apart.) Cheers, Harri Setup: [naghdi:local/src/boost] hhakula% uname -a Darwin naghdi.hut.fi 6.6 Darwin Kernel Version 6.6: Thu May 1 21:48:54 PDT 2003; root:xnu/xnu-344.34.obj~1/RELEASE_PPC Power Macintosh powerpc [naghdi:local/src/boost] hhakula% gcc --version gcc (GCC) 3.3 20030304 (Apple Computer, Inc. build 1493) Copyright (C) 2002 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [naghdi:local/src/boost] hhakula% python2.3 Python 2.3 (#1, Sep 18 2003, 11:31:43) [GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin Type "help", "copyright", "credits" or "license" for more information. | https://mail.python.org/pipermail/cplusplus-sig/2003-September/005219.html | CC-MAIN-2016-40 | refinedweb | 201 | 62.24 |
The objective of this tutorial is to show how use the cpplinq any operator, using the ESP32 and the Arduino core. The tests shown here were performed using an ESP32 board from DFRobot.
Introduction
The objective of this tutorial is to show how use the cpplinq any operator, using the ESP32 and the Arduino core.
This operator allows to check if at least one element of an array fills a certain criteria. It will return a Boolean value depending on the result: true if at least an element fills the criteria and false if none does.
The tests shown here were performed using an ESP32 board from DFRobot.
The code
We will start the code by importing the cpplinq library, so we have access to the functions we need.
#include "cpplinq.hpp"
Then we will declare the using of the cpplinq namespace, so we avoid having to use the C++ scope resolution operator.
using namespace cpplinq;
Moving on to the Arduino setup function, we will open a serial connection to later output the result of our program.
Serial.begin(115200);
Then we will declare an array containing some arbitrary integer values. We will include some values that are lesser than 100, so there are some elements that fill our criteria.
int array1[] = {5,5,2,100,200};
In order for us to be able to apply the cpplinq operator we need, we first need to convert the previous array to a range object. We do this by calling the from_array function, passing as argument the previously declared array of integers.
from_array(array1)
Then we will use the cpplinq any operator, which will return true if at least one of the elements of the array fills our condition (thus the name any).
Our condition is specified as a function that will be passed as input of the any operator. This function will be applied to each element of the array and it should return true if the element fills the criteria, and false otherwise.
As mentioned, the any operator will return true if this function returns true for at least one of the elements of the array.
any([](int i) {return i < 100;})
The full expression tree can be seen below. Note that the result of the any operator is a Boolean, which we will store in a variable. Note that since there are some elements of the array that fill the criteria, we expect that the any operator returns true.
bool resultArray1 = from_array(array1) >> any([](int i) {return i < 100;});
Now we will apply the same procedure to a second array which doesn’t contain any element that fills our criteria. In this case, the any operator should return false.
int array2[] = {345,100,200,477}; bool resultArray2 = from_array(array2) >> any([](int i) {return i < 100;});
To finalize, we will print both results to the serial port.
Serial.print("Array 1: "); Serial.println(resultArray1); Serial.print("Array 2: "); Serial.println(resultArray2);
The final source code can be seen below.
#include "cpplinq.hpp" using namespace cpplinq; void setup() { Serial.begin(115200); int array1[] = {5,5,2,100,200}; bool resultArray1 = from_array(array1) >> any([](int i) {return i < 100;}); int array2[] = {345,100,200,477}; bool resultArray2 = from_array(array2) >> any([](int i) {return i < 100;}); Serial.print("Array 1: "); Serial.println(resultArray1); Serial.print("Array 2: "); Serial.println(resultArray2); } void loop() {}
Testing the code
To test the code, compile it and upload it to your device, using the Arduino IDE. When the procedure finishes, open the serial monitor to obtain the outputs from the program.
You should see a result similar to figure 1. For the first array it returns the value true, since there’s at least one element lesser than 100 in that array. On the second array, since there is no element lesser than 100, the operator returns the value false.
>
One Reply to “ESP32 Arduino cpplinq: the any operator”
I would like to thank your for your efforts in producing clear and well thought out tutorials, its much appreciated. When you have time could you produce a tutorial on cpplinq with two dimensional arrays? | https://techtutorialsx.com/2019/04/25/esp32-arduino-cpplinq-the-any-operator/ | CC-MAIN-2020-40 | refinedweb | 686 | 54.02 |
Originally published on my personal:
When one tries continuously, one ends up succeeding. Thus, the more one fails, the greater the chance that it will work
or:
Every advantage has its disadvantages and vice versa
or even:
If there is no solution, it is because there is no problem.
But most importantly:
Why do it the easy way when you can do it the hard way?
Why the Shadoks reference ?
I've been writing Java professionally for the last 13 years.
Luckily, I also work with other languages, mostly Go and Javascript.
Working with Go made me notice a pattern in the Java ecosystem:
it is a wide and rich one, with very solid & technically impressive libraries & frameworks.
But the thing is, many of those libraries & frameworks are impressive solutions for a problem which didn't need exist in the first place: trying to use a declarative approach everywhere.
Case in hand: JUnit tests
In the following, I'll be using a (unit) test written in Java and showcasing JUnit, which is arguably the most popular and used testing framework in the Java land, in its latest version at the time this post was written, version 5 codenamed Jupiter.
There will be a couple of code snippets, so please bear with me till I make my point at the end.
In java, everything is a class
The same applies to tests:
import org.junit.jupiter.api.Test; public class ExampleTest { @Test void test_login() { assertThat(login("username", "p@$$w0rd")).isTrue(); } }
As can be seen in the code snippet above, a test is:
- a class
- with a method
- annotated with
@Testto tell JUnit that this is the test code we'd like to exercise.
Test cases
What if we'd like to test our
login logic against multiple
username and
password combinations ?
One way to do it would be to create a new test method for every combination:
import org.junit.jupiter.api.Test; public class ExampleTest { @Test void accepts_correct_login1() { assertThat( login("username", "p@$$w0rd") ).isTrue(); } @Test void rejects_incorrect_username() { assertThat( login("incorrect-username", "p@$$w0rd") ).isFalse(); } @Test void rejects_incorrect_password() { assertThat( login("username", "incorrect-password") ).isFalse(); } }
This quickly gets unwieldy when:
- The test method body is long, forcing us to duplicate it
- There are a lot of test cases, e.g. dozens of username/password combinations for example
- Dynamically generated test cases, e.g. random values, fuzzing, ...
Parameterized tests
That's why JUnit offers a way to write the test method only once, and invoke it as many times as we provide test cases:
import org.junit.jupiter.api.Test; public class ExampleTest { @ParameterizedTest @MethodSource("loginTestCases") void test_login(String username, String password, boolean expected) { assertThat( login(username, password) ).isEqualTo(expected); } private static Stream<Arguments> loginTestCases() { return Stream.of( Arguments.of("username", "p@$$w0rd", true), Arguments.of("incorrect-username", "p@$$w0rd", false), Arguments.of("username", "incorrect-p@$$w0rd", false) ); } }
Lots of noise, but basically:
loginTestCasesreturns the list of test cases
test_loginis a parametrized test method that gets fed the different combinations
Test case naming
In the testing report, and by default, parameterized test methods will get a dynamically generated name which is the combination of all the parameters it receives.
This can be tweaked using a templated string:
@ParameterizedTest(name = "login({0}, {1}) => {2}")
Where
{0},
{1}, ... get replaced by the method argument in the corresponding position.
Execution order
Say we have 2 cases that must run in a specific order, e.g.:
- first test method logs the user in and obtains a token
- second test method uses that token to test the system further
The code would look like this:
public class ExampleTest { private String token; @Test void testLogin() { String token = login("username", "p@$$w0rd") assertThat(token).isNotNull(); this.token = token; } @Test void testApiCall() { int res = apiCall(this.token); assertThat(res).isEqualTo(42); } }
Except this won't work as expected:
- JUnit doesn't guarantee the test method execution order
- JUnit doesn't guarantee that the same test instance would be reused between the 2 test methods (needed to share the
tokenfield)
But not to worry: more annotations to the rescue:
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ExampleTest { private String token; @Test @Order(1) void testLogin() { String token = login("username", "p@$$w0rd") assertThat(token).isNotNull(); this.token = token; } @Test @Order(2) void testApiCall() { int res = apiCall(this.token); assertThat(res).isEqualTo(42); } }
Conditional tests
What if we want to only run a specific test method when a certain condition is set ?
Say for example we have a slow test we would like to only run on a beefy CI agent, based on
E2E env var for example.
@Test @EnabledIfEnvironmentVariable(named = "E2E", matches = "true") void testSlowApiCall() { int res = apiCall(this.token); assertThat(res).isEqualTo(42); }
What's the Go way of doing the same ?
Test cases
Go has:
- slices/arrays
- for loops
func TestLogin(t *testing.T) { type Case struct { Username string Password string Expected bool } for _, tt := range []Case{ {"username", "p@$$w0rd", true}, {"incorrect-username", "p@$$w0rd", false}, {"username", "incorrect-p@$$w0rd", false}, } { t.Run(fmt.Sprintf("login(%s, %s) => %v", tt.Username, tt.Password, tt.Expected), func(t *testing.T) { require.Equal(t, tt.Expected, login(tt.Username, tt.Password)) }) } }
I make use of testify toolkit to simplify assertions.
Order, keeping state
Go executes instructions from top to bottom.
Unless you exit the current scope, the variables keep their values.
func TestLoginAPICall(t *testing.T) { token := "" t.Run("login", func(t *testing.T) { token = login("username", "p@$$w0rd") require.NotEmpty(t, token) }) t.Run("api call", func(t *testing.T) { res := apiCall(token) require.Equal(t, 42, res) }) }
Conditional execution
Go has
if switch:
func TestLogin(t *testing.T) { token := "" t.Run("login", func(t *testing.T) { token = login("username", "p@$$w0rd") require.NotEmpty(t, token) }) if os.Getenv("E2E")!="" { t.Run("slow api call", func(t *testing.T) { res := slowApiCall(token) require.Equal(t, 42, res) }) } }
Closing words
Something went very wrong in the Java ecosystem:
for some reason, we as a community, collectively decided that:
- we should only be using the language's constructs (
if,
for, ...) in the business/functional code
- for anything else, e.g. tests, configuration, frameworks, etc., we instead have to invent a half-assed declarative language, preferably annotation based
It is most impressive that we got so far with these self-imposed limitations.
I am not picking on JUnit.
On the opposite: what they are able to achieve is simply impressive.
Everything is very extensible and configurable, and it must have taken lots of time & effort to reach this point.
Yet, the Go testing library achieves the same level of power/flexibility while being much simpler and with a tinier surface area simply by choosing an imperative model (
t.Run() vs
@Test), making it possible to use the full power of the host language.
Discussion (28)
This is such an interesting observation!
I learned Java in school and have used it tangentially at work for the last ~2 years, but I've always bounced off how unnecessarily complex the ecosystem has always seemed. I've used Go for substantially less time, but I definitely find it far more intuitive and simple to use.
Thank you for the insight!
Java the language is okay, but everything "surrounding" it (tools, frameworks, ecosystem) is horribly overengineered - just look at tools like Eclipse or Maven, or frameworks like J2EE and Spring with their infinite "flexibility" and configurability (99% of which you rarely need, if ever).
I think the Java world never learned the mantra "less is more".
Exactly ! It's not the language, it's the mindset around it.
Well, I think maven should not be in this list.
Hmm I beg to differ, I think Maven is also more complicated than it should be (compared to package managers in other languages like npm, gem, composer and so on).
But maybe that's not entirely Maven's fault, Java's build process is a lot more complex than for the other languages (which largely don't even have a build process), and Maven is of course not just a dependency manager but also a build tool.
Well, Maven is definitely not a simple tool to grasp and use efficiently, but it extremely powerful and versatile while still rather compact and fast. What is even more important, it's one of the most reliable build/dependency management tool in the long run. It's hard to underestimate this property for projects living for many years. Fancy attempts to replace Maven (I'm looking at you, Groovy) do not hold this property, unfortunately, although they somewhat address Maven steep learning curve.
Thank you <3
It was very pleasant to hack on side projects in Go after a full day working with Java: its simplicity comes as a breath of fresh air.
Instead of switching language I've decided to try to change approach. In spare time I'm working on the project which takes significantly different approach to writing code in Java.
Haha brilliant, I completely agree that in the Java world "we" tend to horribly overcomplicate things, and the "declarative" approach is one of the biggest culprits.
To give an example of this other than JUnit:
I once worked on a project where the backend part was a REST API made with Spring. I didn't develop that part myself, but I had to read the code and make a few small changes to it.
What I noticed is that more than half of the code of that REST API was not Java code but Spring annotations (so the '@' stuff). What I observed was that the Java code was extremely trivial, but the annotations horribly complicated and opaque.
The biggest problem is when something goes wrong (doesn't work as expected), because how on earth are you then going to debug this stuff?
Suffice to say that I hated this style of coding. There is of course no reason why it has to be like this, Java does not mandate this style of coding, but it's become a bit of a "tradition" in the Java world (probably influenced by both JavaEE and Spring).
Which reminds me of annotatiomania.com/ :D
Exactly: you end up starting at a multi-hundred line stacktrace with layer after layer of Tomcat stuff, Spring security stuff, Spring MVC stuff, various proxies around your own code, ....
This is a very salient point.
I think the problem is the opinionated frameworks in the Java ecosystem. Spring, for example, does away with a lot of "boilerplate" code... but in doing so, you have to do things the "Spring way" - unless you spend the inordinate amount of time learning what's happening under the hood, and then optimising your code.
In a business environment, no Project Manager on the planet will care about Spring optimisations, because there is no direct business benefit (vs simply choosing a less opinionated approach).
Most experienced Java developers (that I've spoken to) passionately hate JavaEE. Some senior developers are slowly realising that Spring is a bit of a bell curve. In the early days, you don't understand Spring enough to see the benefits... in the middle, you love it... and towards the end, you realise just how much it gets in your way.
As with everything else in our world, it's the appropriate tool for the job, at the appropriate time. Unfortunately, deciding what's appropriate up front is a lot more difficult than with hindsight.
I couldn't have put it better 👍
This is exactly it.
Once you've learned the ropes with Spring:
GET /tax/{code}with something with a dot in it, e.g.
vat.20, I get a 500 error
No serializer configured for the "20" media type
I'm yet to find a valid reason to include Spring Security in any corporate project. It's simply not maintainable enough for our use-case(s).
the fear factor: "Are you really sure you want to reimplement your own security stack instead of going of the industry standardm battle-proven 15 year old Acegi/Spring Security stack ?" ¯_(ツ)_/¯
Re-inventing the wheel is not a good thing. There's options that aren't Spring Security. For example, for those that for some reason like XML, there's Shiro.
Our model though is that Front End applications implement security properly, and the middleware/backend treats the front end as a trusted component with very basic security requirements. This way, the Front End gets penetration tested and we don't have duplicated code/effort in the security layer. We don't have any Front End applications in Spring, and very few in Java.
I've used Spring since circa 2008 and better I knew it then more I disliked it. It poorly designed and even worse implemented. I really impressed how Spring guys were able to screw up every single idea they've implemented. They implemented slowest possible DI container (about 10x times slower than reflection-based class istantiation!). They made using string constants as a code and exceptions in business logic a everyday norm - which is just insane. Moreover, classic "business exceptions" (let's keep aside for the moment that this concept should not even exist) assumes that "business exceptions" are checked ones and present in method prototypes. Spring uses "technical exceptions" derived from RuntimeException in the place of "business exceptions" and hides remaining signs of business error handling. In other words, they were able to screw up even the idea which is already screwed up. I'm really, really impressed.
Haha totally agree, Spring is vastly overrated ... the point is of course that back then J2EE was so horrible that Spring felt like an improvement :-) but that doesn't say much, it only proves what an incredibly low bar was set by J2EE.
Maybe it could even be argued that Spring was quite okay in the beginning, but over the years it became more and more bloated and overcomplicated.
And at some point J2EE was improved and simplified so much that it was probably better and simpler (more "lightweight" even) than Spring ... but by then Spring had become totally dominant as the new "incumbent" and J2EE didn't stand a chance anymore.
But even years ago there were already Java frameworks which were much, much better than both J2EE and Spring ... Play (playframework.com) is an example, it does away with all the Servlets and container baggage and is much simpler and easier than either Spring or J2EE.
Well, I understand how Spring achieved it's popularity. I just realize that there are rarely any justification to use it in new projects. For those who can't imagine their project without Spring "magic" there is a modern alternative (Micronaut) which solves significant amount of Spring issues and shifts huge part of run time reflection to compile time.
There are a lot of Java Web frameworks which are better than Spring - Spark, Jooby, Vert.x, etc. Vert.x, for example usually one of the top performers in Techempower benchmarks.
In my spare time I'm working on similar framework which is based on Promise-based asynchronous processing model and asynchronous I/O API present in recent Linux kernels - io_uring. I hope it will be extremely fast while easy to use.
Spring is a great example how Java should not be used.
Hello, great post! I was just wondering how can you share the parameters in go with multiple tests. In junit the parameters can be shared with any test. This way you can test multiple aspects with the same data. The idea is to separate the data from the test. The go example is not exactly the same.
The data is in the test and even
Caseis defined in the test. Im not saying junit is better in any way, i'm just wondering if there is a way to separate the data from the test so it can be shared.
Hi John and thank you for the kind words.
Right !
To achieve the same using the host language's constructs, you could:
1. define a package-level variable with the various cases:
2. generate the test cases from a function
3. load the test cases from a JSON/Yaml/CSV/.. file
Again, you have the full standard library to achieve whatever you need :)
Yes! I think the same style could also be done in junit but it probably wouldn't pass a review. I do think that junit provides some nice ways to remove verbose code and just declare the parameters you want in the test. In some cases it is probably just better not to use it though. It depends on how common the code is and how much time is saves.
In graphs I was able to take advantage of these features in junit here, for example, but it is not for everyone.
I presume that the basis for your debate is this:
Fortunately, both are factually wrong (at least for my 20 year career in Java). There is certainly nothing wrong with
ifor
forwithin a unit test - I do that all the time, e.g.
Of course, the above code violates SRP, but other than that, for illustrative purposes, the point stands.
Re your point about annotations, I refer you to Annotation Hell. E.g., almaer.com/blog/hibernate3-example... (no affiliation, just the first result in Google).
I actively prefer not to use Parametized Tests, regardless of the language I'm writing in, but horses for courses there. If pushed to, I would prefer a
forloop within a test method, using a field variable within the Test class. It's not a strong preference though, and I wouldn't argue the point in a PR etc. My approach in Java is pretty close the the Go code you posted, funnily enough...
I've never understood the point of a conditional test, I typically want all my tests to run, and the tests can setup pre-conditions as necessary (such as pretending that the environment variable has been run). Conditional tests (to me) imply that the build server might not run them, but then the condition will be true when running in the Production environment.
The fact that JUnit doesn't guarantee order of test execution is positively a good thing. I don't want my tests to bleed through to each other. Sure, my tests might take longer to run (e.g., Spring context bootstrap...) but that's simply an optimisation problem, and we're talking about CPU cycles on the build server (as a developer, I should only be running the tests that I care about during this iteration, the build server can run the rest).
Now, typically I would add another framework into the mix to help with test setup, Mockito, and that kind of leads us into Dependency Hell too, but I'm sure there's many other ways to achieve the same too.
Heya Dave,
I mustn't have expressed my meaning clearly, apologies !
I wasn't referring to the code inside the test methods,
Rather, I was referring to the usage of annotations, e.g.
@Test,
@ParameterizedTest,
@Get,
@Post, ... to declare tests, rest endpoints, change the behaviour of methods, etc.
compared to the Go libraries philosophy of doing it explicitly & imperatively, e.g.
t.Run("dynamic test case", func(t) { /* test code here */ }, or
router.GET("/path", func() {}to declare a HTTP handler etc.
W.r.t. the annotation hell, I have a nice one: annotatiomania.com/ :D
I agree there: I'd rather whip out a for loop rather than have to google how ti use JUnit parameterized test.
The problem is: if a single case inside the for loop fails, the whole test is marked as red, and you have to go through the logs to identify which particular case failed (assuming you had the necessary logging set up).
The tooling (the in-IDE test runner, Jenkins, Surefire test reports, ...) does not accommodate this style very well.
The choice to use annotations, at any level, isn't mandated by Java. That's mandated by choices made during design of the application (or maybe mandated by corporate code-style agreements).
As of Java 8 onwards, I've actually been writing far more "functional programming" style Java, so my code probably looks a lot more like Go - because I love lambda's. Some, typically more junior, developers do tend to struggle with lambdas though, in my experience.
I'd argue that's a good thing. Fail fast. I'd argue that tests shouldn't write any logs. The point of failure should make it explicitly clear at which point the test failed (at least down to the line). If this is within a loop/stream/lambda then yes, things can get complicated, but then you're just asking a developer to run the test case in debug, with the IDE set to halt execution on exception. Further, most JUnit assertions will allow you to put an explicit statement in the exception's message.
Logs are useful for support purposes, but there's nothing wrong with a developer hooking up to a remote JVM using JDPA to find out the internal state of an application.
There, we certainly agree. All of the tooling (except perhaps javac itself) is strongly opinionated about how it expects the application design to be laid out.
PS., no need to apologise for anything - we're both entitled to hold different opinions, that's the point of a debate! It might be that one (or both) reconsiders, but equally, we can still respect each other's opinions without any change.
Well, with Go you often have no choice. With Java often you have too much choices. Go-like ways are present as well.
Unit tests should be independent of each other. shouldn't they?
99.99% of the time yes.
I was thinking more in the lines of an integration test, where you would like to test a more complex workflow, e.g.:
1., test a
GET /documentsendpoint, and assert that the response is empty
POST /documentsendpoint and assert that the response is
201, and capture/store the created document id
GET /documentsa second time and ensure that the created document appears there | https://practicaldev-herokuapp-com.global.ssl.fastly.net/jawher/technically-impressive-solutions-for-invented-problems-5gcj | CC-MAIN-2021-10 | refinedweb | 3,713 | 63.49 |
Executive Summary: Most of the time, SizeChanged is the right event to use, and LayoutUpdated is the wrong event.
The Silverlight 2 layout system offers two events: SizeChanged and LayoutUpdated. They look the same...here is how they are hooked up in C#:
public Page()
{
InitializeComponent();
LayoutRoot.SizeChanged += LayoutRoot_SizeChanged;
LayoutRoot.LayoutUpdated += LayoutRoot_LayoutUpdated;
}
The handlers are a bit different, though. Note that the LayoutUpdated event just has a standard EventArgs, while the SizeChanged event has the SizeChangedEventArgs, which very helpfully contains the old and new sizes.
void LayoutRoot_LayoutUpdated(object sender, EventArgs e)
private void LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e)
So far, they look pretty much the same, except for the additional information provided by the SizeChanged event. But this is not the case.
SizeChanged
The SizeChanged event is an "instance event" that is raised whenever the size of the element you have attached the handler to has changed. Note that if the position of the element on the screen changes, but not its size, this event does not get raised.
LayoutUpdated
The LayoutUpdated event is a "static event" that is fired every time layout had anything to do anywhere in the tree. You may find that it is getting fired much more often than you thought it would be. That's the reason why.
Sequence of events
The two events are also raised at different times. Here is roughly the way that the layout loop works:
while any element needs to be measured or arranged{ while any element needs to be measured { measure everything that needs measuring }
while anything element needs to be arranged and no element needs to be measured { arrange everything that needs to be arranged } if any element needs to be measured or arranged { continue }
if there are any SizeChanged events to raise { raise the SizeChanged events }
if any element needs to be measured or arranged { continue }
if layout did anything { raise the LayoutUpdated event }}
Layout keeps looping until there was nothing for it to do or until the cycle detection kicks in. This means that you can change properties that affect layout in the SizeChanged and LayoutUpdated event handlers. In fact, it is kind of assumed that you'll be doing that in your SizeChanged handlers. The LayoutUpdated event fires when the layout system thinks it is all finished. I used it for my Snapper element only because I needed to be notified when the Snapper moved, not just when it changed size, and there is no other way to get that information.
Example
Here's an example of an app the handles the SizeChanged and LayoutUpdated events.
Don't forget to modify the x:Class to match your app.
<UserControl x:Class="LayoutEvents.Page"
xmlns=""
xmlns:
<Grid x:
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Rectangle Margin="4" Fill="AliceBlue"/>
<StackPanel x:
<Button Content="Width += 10" Margin="2" Click="ButtonAdd_Click"/>
<Button Content="Width -= 10" Margin="2" Click="ButtonSubtract_Click"/>
</StackPanel>
<Rectangle Fill="Coral" Grid.
<TextBlock x:
</Grid>
</UserControl>
...and here's the code. Don't forget to make sure that the namespace matches the XAML.
using System;
using System.Windows;
using System.Windows.Controls;
namespace LayoutEvents
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
LayoutRoot.SizeChanged += LayoutRoot_SizeChanged;
LayoutRoot.LayoutUpdated += LayoutRoot_LayoutUpdated;
}
void LayoutRoot_LayoutUpdated(object sender, EventArgs e)
if (!updating)
{
updating = true;
++layoutUpdated;
UpdateCaption();
}
else
updating = false;
private void LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e)
caption.Visibility = (e.NewSize.Width < 300 || e.NewSize.Height < 300) ? Visibility.Collapsed : Visibility.Visible;
++sizeChanged;
private void ButtonAdd_Click(object sender, RoutedEventArgs e)
buttonPanel.Width += 10;
private void ButtonSubtract_Click(object sender, RoutedEventArgs e)
buttonPanel.Width -= 10;
private void UpdateCaption()
caption.Text = "LayoutUpdated: " + layoutUpdated + " SizeChanged: " + sizeChanged;
int layoutUpdated, sizeChanged;
bool updating;
}
You will see that the caption area only appears when the browser is large enough. By resizing the browser (assuming that your HTML page autosizes the Silverlight plugin to be fill the page) you can see both events being raised. But when you click on the Buttons, you will notice that the LayoutUpdated event is raised, even though you attached the handler to the LayoutRoot and the LayoutRoot has not changed at all. | http://blogs.msdn.com/b/devdave/archive/2008/05/27/layout-events-sizechanged-and-layoutupdated.aspx | CC-MAIN-2013-48 | refinedweb | 679 | 55.84 |
I was just reading a post by James Surowiecki where he was arguing that “Lehman’s Failure Mattered.” However, he never explained *why* Lehman’s failure was so quickly shattering to the world’s financial markets.
I think of it this way: Wall Street was a feeder fund for the U.S. economy. The massive amounts of money necessary to finance the trade deficit—$680 billion in 2007, or roughly $2 billion per day—were flowing into the country with the Wall Street firms as the main conduits. That includes Treasuries as well, since most foreign purchases of U.S. government bonds go through major banks and investment houses (the so-called ‘primary dealers’).
In other words, there was a high-pressure fire hose of money coming into the country, with most of that flowing through Wall Street on its way to mortgage-backed securities and the like. When Lehman went under, it was if that high-pressure fire hose was suddenly stopped up, with horrific consequences. Nobody wanted to run their money through Wall Street given the threat of failure and loss.
When that happened, the money instaneously backed up, and the whole global financial system came darn near breaking. Think about it. On a typical day, money was being collected by banks all around the globe, and passed back and forth by circuitous routes and in diverse currencies. However, at the end of the day, about half of all the net capital accumulation by trade surplus countries (top five: China, Germany, Japan, Saudi Arabia, Russia) was eventually sent on to the U.S.
Now, this money was flowing to the U.S. because the U.S. was thought to be a low-risk, decent return investment (see my previous post). Investments in other countries were being perceived as higher risk, or lower return (which comes to much the same thing). When Lehman went bankrupt, the low-risk U.S. investment strategy suddenly vanished. For big foreign investors--Saudi Arabia, Russian oil oligarchs, German banks--the world suddenly became a lot riskier, in a very real sense.
Now, there's an interesting implication to this analysis. If I'm right, we could let a major bank fail today without Lehman-like global consequences. The reason is two-fold: First, the trade deficit is a lot smaller, so the fire hose of money coming into the country is operating under lower pressure. The January trade deficit was $36 billion, compared to $58 billion in September 2008.
Moreover, the fire hose is now flowing through Washington rather than New York. According to CBO estimates, the federal government ran a deficit of $78 billion in January, more than twice as much as the size of the trade deficit. So government borrowing could in principle absorb all the foreign demand for U.S. securities, as long as there were enough primary dealers in Treasuries.
From that perspective, a February post on Barry Ritholtz's Big Picture blog is useful. The post argues that the number of primary dealers should be increased, going as far as allowing most banks to participate.
I'm not arguing in favor of allowing a bank to fail. The bankruptcy of a Citi or Bank of America would be extremely messy, painful, and to be avoided if possible. But it may not cause the systemic risk that Lehman does. | http://www.bloomberg.com/bw/stories/2009-03-13/wall-street-as-a-feeder-fund-for-the-u-dot-s-dot | CC-MAIN-2015-18 | refinedweb | 560 | 63.49 |
Tower of Hanoi, is a mathematical puzzle which consists of three towers and more than one disks is as depicted − These disks are of different sizes and stacked upon in an ascending order, i.e. the top most disk is smallest and the bottom most disk is largest in size.
The objective of puzzle is to shift the all rods to the last tower under these constraints ->
- Only one disk may be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
- No disk may be placed on top of a disk that is smaller than it.
Approach:
- First mark the towers as A, B and C. and think for smaller cases, if we have a single disk we can simply put it to tower C from A .
- Think if we have 2 disks what can we do first we put the upper disk and place in tower B and then pick the remaining disk and place it into tower C and then take the disk from B and place it into C now the tower A and B are empty and all disk are in tower C.
- Now for any number of disks we use the upper 2 approaches recursively and its guarantee that for any number of disk this puzzle solved using the upper 2 approaches.
Implementation for the above approach in C++:
#include<iostream> using namespace std; void TOH(int n,int A, int B, int C) { if(n>0) { // From tower 1 to 2 using tower 3 TOH(n-1,A,C,B); cout<<"from tower "<<A<<" tower "<<C<<"\n"; // From tower 2 to 3 using 1 TOH(n-1,B,A,C); } } int main() { int num_of_disk; cin>>num_of_disk; // Tower numbered as 1,2,3. TOH(num_of_disk,1,2,3); }
Input:
4
Output:
from tower 1 tower 2 from tower 1 tower 3 from tower 2 tower 3 from tower 1 tower 2 from tower 3 tower 1 from tower 3 tower 2 from tower 1 tower 2 from tower 1 tower 3 from tower 2 tower 3 from tower 2 tower 1 from tower 3 tower 1 from tower 2 tower 3 from tower 1 tower 2 from tower 1 tower 3 from tower 2 tower 3
Time Complexity:
Tower of Hanoi works on recursion so its take order of 2^(number of disk) i.e., O(2^n).
Read Next: Combinatorial Game Theory | Game of Nim | https://hacktechhub.com/tower-of-hanoi-recursion-based-problem/ | CC-MAIN-2022-40 | refinedweb | 422 | 63.56 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.