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 |
|---|---|---|---|---|---|
Going.
A bit of backstory: back in the day, when I started my SaaS business, I had no idea what multi-tenancy meant. Honestly, the code was a big mess and I was unintentially almost asking for a data breach at some point. I was filtering every query by myself. No helpers, no middleware and no multi-tenancy - huge mistake. No data ever leaked from my application, fortunately, and nowadays, there are very strict privacy and security guide lines that protect customers and users.
A friend of mine showed me multi-tenancy and I was blown away. It was exactly what I needed to have to make data filtering easy and make data breaches much more difficult. Not to mention the fact that queries would be faster due to the smaller tables. Transitioning to a multi-tenancy set up with an app that has over 100 businesses registered isn’t easy though and it took me quite some time to figure it all out. Another friend of mine wanted to make this same transition and we had quite a fun time figuring it all out.
What is multi-tenancy?
Basically, multi-tenancy is a software architect that allows us to separate code and data specifically for different instances or user groups. This means that queries made over a multi-tenancy set up could give different results for different people or groups.
You will need to use
schemas for that. A schema separates the data from other people/groups. You can set this up in three ways:
- Create a separate database for each schema.
- One database, but with separated schemas. Meaning that you will not be able to use any other schema.
- One database, but with shared schemas. This means that you can have both some separated tables, but also a few shared tables. The shared tables are easily accessible for all users.
I picked the 3rd option.
There are two ways to migrate the site to multi-tenancy. One would be through Django and the other would be through plan SQL statements. I prefer and went with the first one. My friend went with the second option. Both can work, but since I don’t have his code, I will only explain the way that I did this.
How to do the migration
Make sure to take a backup of your data and preferably run this on a staging server, before running this on the production server!
As mentioned before, I have tables that will be shared by all tenants, but most of them are private. We need a name for every scheme (so make sure that you have a field that is not nullable and always unique!). I created the names of the schemas based on one of the shared tenants - the one where the name of the organizations is stored.
Set up multi-tenancy, then copy and paste all of the models that should not be shared to one of the not shared apps and run the migrations. Now you have identical models and changed one schema (the default one).
Up next, we will create all of the schemas and then move over our data. We will have to loop over the records of the table that we picked earlier. In my case, this is the table
Org and I will use
Org.name as the unique name to use in the schema.
from django.db import connection from customers.models import Client for org in Org.objects.all(): connection.set_schema('public') tenant = Client.objects.create(schema_name=org.name, name=org.name)
That’s all we need to create the tenants. Don’t run it yet, we will need to add more in the loop.
As you can see, we first set the right schema. This means that with every new iteration in the loop, we will start out in the
public schema. We do this because we need the data from the
public schema first to be able to move it.
Up next, we need to get the data that we need.
from django.core.cache import cache cache.set('TableName', TableName.objects.filter(org=org).values())
This will create a queryset in the cache. You will have to do this with every model you have that you want to get in the new schema. We need to have it in the cache as we will not be able to get it from the model once we are running in the schema. We are currently in the
public schema and will need to go now to the specific with
connection.set_schema(schema_name).
So after that
cache.set(...) part, add this:
connection.set_schema(org.name) for j in cache.get('TableName'): TableName.objects.create(**j)
You will have to repeat the second part for every model you want to move. It will then add the new data in the new model.
There is one issue with doing that; the
id column is not indexed by your database. Will have to do that manually with this:
from django.db import connection cursor = connection.cursor() cursor.execute("SELECT setval(pg_get_serial_sequence('" + tenant.schema_name + ".project_app_model','id'), CAST(max(id) AS INT), max(id) IS NOT null) FROM " + tenant.schema_name + ".project_app_model")
Replace
project with your project name,
app, with the app name and
model with the model name. You will have to repeat the last line for every model you are moving.
And that’s all it takes to change your project from no multi-tenancy to multi-tenancy. | https://djangowaves.com/tips-tricks/migrate-an-application-to-multi-tenancy/ | CC-MAIN-2019-39 | refinedweb | 916 | 74.9 |
Docker is a new approach in application packaging and deployment in many ways. Some quite disturbing paradigms are therefore considered:
Push the image
- Open the Launchpad and locate the Docker Quickstart Terminal icon.
- Click the icon to launch a Docker Quickstart Terminal.
- Place your cursor at the prompt in the Docker Quickstart Terminal window.
- Type
docker imagesto list the images you currently have:
Find the
IMAGE ID for your
docker-whale image.
In this example, the id is
7d9495d03763.
Note: The
REPOSITORY shows the repo name
docker-whale but not the namespace. You need to include the
namespace for Docker Hub to associate it with your account.
The
namespace is the same as your Docker Hub account name. You need to rename the image to
YOUR_DOCKERHUB_NAME/docker-whale.
Use
IMAGE ID and the
docker tag command to tag your
docker-whale image.
The command you type looks like this:
Your account name will be your own. So, you type the command with your image’s ID and your account name and press RETURN.
$ docker tag 7d9495d03763 maryatdocker/docker-whale:latest
Type the
docker images command again to see your newly tagged image.
Use the
docker login command to log into the Docker Hub from the command line.
The format for the login command is:
docker login --username=yourhubusername --email=youremail@company.com
When prompted, enter your password and press enter. So, for example:
$ docker login --username=maryatdocker --email=mary@docker.com
WARNING: login credentials saved in C:\Users\sven\.docker\config.json
Login Succeeded
Type the
docker push command
Return to your profile on Docker Hub to see your new image.
Desired to gain proficiency on Docker? Explore the blog post on Docker training online to become a pro in Docker.
Pull the image
Pull the image you just pushed to hub. Before you do that you’ll need to remove the original image from your local machine. If you left the original image on your machine. Docker would not pull from the hub — why would it? The two images are identical.
Place your cursor at the prompt in the Docker Quickstart Terminal window.
Type
docker images to list the images you currently have on your local machine.
To make a good test, you need to remove the
maryatdocker/docker-whale and
docker-whale images from your local system. Removing them forces the next
docker pull to get the image from your repository.
Use the
docker rmi to remove the
maryatdocker/docker-whale and
docker-whale images.
You can use an ID or the name to remove an image.
$ docker rmi -f 7d9495d03763
$ docker rmi -f docker-whale
Pull and load a new image from your repository using the
docker run command.
The command you type should include your username from Docker Hub.
docker run yourusername/docker-whale
$ docker run maryatdocker/docker-whale
Unable to find image 'maryatdocker/docker-whale:
latest' locally latest: Pulling from maryatdocker/docker-whale
eb06e47a01d2: Pull complete
c81071adeeb5: Pull complete
7d9495d03763: Already exists
e9e06b06e14c: Already exists
a82efea989f9: Already exists
37bea4ee0c81: Already exists
07f8e8c5e660: Already exists
676c4a1897e6: Already exists
5b74edbcaa5b: Already exists
1722f41ddcb5: Already exists
99da72cfe067: Already exists
5d5bd9951e26: Already exists
fb434121fc77: Already exists
Digest: sha256:ad89e88beb7dc73bf55d456e2c600e0a39dd6c9500d7cd8d1025626c4b985011
Status: Downloaded newer image for maryatdocker/docker-whale:latest ________________________________________
/!" /
---------------------------------------- \
\
\
## .
## ## ## ==
## ## ## ## ===
/""""""""""""""""___/ ===
~~~ {~~ ~~~~ ~~~ ~~~~ ~~ ~ / ===- ~~~
\______ o __/
\ \ __/
\____\______/
For indepth understanding of Docker click on | https://tekslate.com/docker-push-pull | CC-MAIN-2020-16 | refinedweb | 554 | 57.47 |
International Standard Book Numbers consist of a string of digits followed by a checksum digit to help detect typos, not unlike schemes used in credit card numbers. Here I show a small Python function to calculate this check digit.
You can pass it a string consisting of 9 or 10 digits. If you pass in a 10 digit number the last digit is ignored. The line returned consists of the first 9 digits plus a final digit that is the checksum (this digit might be an X character).
The most common use case is to check whether a given isbn is well formed by passing it to
isbnchecksum() an comparing the result to the original:
if myisbn == isbnchecksum(myisbn): ... proceed ...
For the last 5 or 6 years 10 digit isbn has been replaced by 13 digit isbn starting with a 978 or 979 sequence. This 13 digit sequence in compatible to so called ean numbers used for marking all kinds of goods, not just books and the first 3 digits represent a country code. For books this country is the fictional Bookland. The checksum for these isbn-13 codes is calculated differently and not shown here but the algorithm can be found on Wikipedia together with additional information on isbn. The small snippet shown below is part of a larger module that I wrote to retrieve information from sources like the Library of Congress and Amazon. That module can be found on homepage.
import string def isbnchecksum(line): """ Calculate the checksum for an isbn-10 number. """" if (len(line) == 10): line = line[0:9] if (len(line) != 9): raise AttributeError('ISBN should be 9 digits, excluding checksum!') sum = 0 count = 0 for ix in line: sum = sum + (10 - count) * string.atoi(ix) count = count + 1 sum = sum % 11 if (sum != 0): sum = 11 - sum if (sum == 10): line = line + 'X' else: line = line + string.digits[sum] return line
After I published this I realized the solution wasn't all that Pythonic. A more elegant implementation (with slightly different semantics) might be the following bit of code (although some people argue that the ternary
x if c else y operator is not Pythonic in any way. Note that the we used the
atoi() function from the locale module for even more portability.
from string import digits from locale import atoi def isbn10checksum(isbn): if len(isbn)!=10 : raise AttributeError('isbn should be 10 digits') return 0 == sum((10-w)*atoi('10' if d == 'X' else d) for w,d in enumerate(isbn.upper()))%11
Just for completeness sake the code for an isbn-13 check. It not very elegant but it is a nice example of Python strides in action:
def isbn13checksum(isbn): if len(isbn)!=13 : raise AttributeError('isbn should be 13 digits') c=(10-(sum(atoi(d) for d in isbn[0:12:2]) +sum(3*atoi(d) for d in isbn[1:12:2]))%10)%10 return atoi(isbn[12]) == c | http://michelanders.blogspot.com/2011/02/checking-isbn.html | CC-MAIN-2017-22 | refinedweb | 493 | 62.58 |
A Python library for generating Media RSS 2.0 feeds.
Project description
A Python library for generating Media RSS 2.0 feeds.
About
This module intents to implement the Media Feed specification from Yahoo. The Media RSS specification is a namespace for RSS 2.0. To accomplish this task it relies heavily on the PyRSS2Gen module. As you might guess this Media RSS module is even nameded after its role model.
Right now this is considered ALPHA! Breaking backwards compatibility is possible at any time, I will try to avoid it though. I started off with a base which can be extended as needed or as we (you and me) have time. See below for a list with specification details and their current implementation status. This way I keep track of what needs to be done and users can see what they can accomplish out of the box and what requires some contributions. Feel free to fork the project, implement a missing feature and send a pull request.
PyMediaRSS2Gen is so far tested to work with Python versions 2.6, 2.7 and 3.4.
Usage
The base class for a media feed is MediaRSS2. It’s attributes represent sub elements, e.g. MediaRSS2.copyright represents the <copyright> element and MediaRSS2.lastBuildDate the <lastBuildDate> element.
For simple elements which contain just a string, boolean or integer just use the according data type. More complicated elements, typically those with attributes and / or sub elements like <media:content> or <media:community>, (will) have their own classes defined.
Probably you will want to import PyRSS2Gen to make use some of it’s helper classes, e.g. for adding a channel image (PyRSS2Gen.Image) or GUIDs to items (PyRSS2Gen.Guid).
Uage is shown by example. For more details check the code and the PyRSS2Gen documentation.
import datetime import PyMediaRSS2Gen mediaFeed = PyMediaRSS2Gen.MediaRSS2( title="A sample Media RSS Feed", link="", description="Description for a feed with media elements" ) mediaFeed.copyright = "Copyright (c) 2014 Foo Inc. All rights reserved." mediaFeed.lastBuildDate = datetime.datetime.now() mediaFeed.items = [ PyMediaRSS2Gen.MediaRSSItem( title="First item with media element", description="An image of foo attached in a media:content element", media_content=PyMediaRSS2Gen.MediaContent( url="", fileSize=123456, medium="image", width="480", height="640" ) ), PyMediaRSS2Gen.MediaRSSItem( title="Second item with media element", description="A video with multiple resolutions", media_content=[ PyMediaRSS2Gen.MediaContent( url="", fileSize=8765432, type="video/mp4", width="1920", height="1080" ), PyMediaRSS2Gen.MediaContent( url="", fileSize=2345678, type="video/mp4", width="1280", height="720" ), ] ), PyMediaRSS2Gen.MediaRSSItem( title="And an item with no media element at all", description="An image of foo attached in an media:content element", link="" ) ] mediaFeed.write_xml(open("rss2.xml", "w"))
Installation
Easiest way to install this module is using pip (as soon as it’s uploaded to the PyPI):
% pip install PyMediaRSS2Gen
If you want to install the module manually, download the package, unzip it and run:
% cd where/you/put/PyMediaRSS2Gen/ % python setup.py install
which uses the standard Python installer. Read the documentation for more details about installing Python modules.
How To Contribute
Every open source project lives from the generous help by contributors that sacrifice their time and PyMediaRSS2Gen is no different.
This project lives on GitHub. You are very welcome to fork this project and submit a pull requests! If you don’t know how to do this you can still report errors by opening an issue.
Look here for more details about contributing to PyMediaRSS2Gen.
Status and Todo
Tests are missing completely so automated testing with tox is a todo item! I’m still new to python and haven’t figured out testing yet.
Below you find the implementation status of the Media RSS elements according to the Media Feed specification.
Changelog
Version 0.1.1 (2014-10-08)
- Fix setup.py to correctly install required modules
Version 0.1.0 (2014-10-06)
- Initial release
- Support for media_content, media_title and media_text
Credits
PyMediaRSS2Gen is written and maintained as a hobby project by Dirk Weise.
This project would not be possible without the work of Andrew Dalke who wrote PyRSS2Gen upon which this module is built.
Project details
Release history Release notifications
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/PyMediaRSS2Gen/ | CC-MAIN-2018-34 | refinedweb | 708 | 50.94 |
I don't know X-G personally, but damn do I respect his drive.
FYI, there is a literal "X-G" member that has been away from the boards for a couple of years, but has been here for many years, is much more well known, and much more respected. You should refer to members with their full name to avoid such ambiguity.
--
@GideonThank you!
@furinkanIf you are an english native speaker, it would greatly help if you translate chapter 2, which i have added as an attachment.
Whatever help anyone gives, it would benefit all allegro users.
While I agree it's a good idea to step back and look at the big picture and structure the book properly. I think at this point it's best for the progress to keep bulldozing through all the features of Allegro, you building good material that you can use in the book puzzle.
Also if you should burn out and say screw this in a few days, you'll have written a whole slew of good material that you can put up right away even if it's not all polished to perfection yet.
Keep going, I think it would be great for Allegro 5 to have a book. You're a hero for actually working on it.
[Flattr this] [My website] [My github]
I assumed AleX-G was the original X-G's reincarnated version, having shifted his skill points from lingual mastery to drive and dedication... Is that not the case? If so, I apologize.
AleX-G: Do you think you could attach a more easily editable format than PDF? I'd be happy to help, even if just a little.
Allegro Game Videos
I am not the X-G you are talking about.Mine is a nickname where G stands for Gangsta, but that is just for fun.I hope all want to help, because i am not going to let the work in the middle.I am on page 133, just for curiosity.
I attached the second chapter on docx format.You can edit the second chapter now.Thanks for consideration!
Everything that Trezker said I'd like to underline. I'm not very good at giving positive feedback... You seem to be going at an impressive pace. Don't forget to take a break after you have this job done.Maybe I'll have a look at the docx.. I was actually needing a lot of help with transformations.I want to include it as a chapter, but since i only got the scale transform to workI think it will not be done, unless someone can help with examples of all kinds of transformations, so i can verify they work and understand them better.There is going to be a lot of work, but i think i will end working on the book on 1st September, because of the exams. I will work on the book in October after i am done with school. So, if you want the book as fast as possible and best possible, pls help!
Hmm, maybe I'm in the minority when I say this, but I always thought books were kind of useless for APIs that are being continuously developed.
By the time the book is done, proof-read, published, etc. The library/language/whatever has another version already released, or in development.
I'd much rather have an online manual or wiki that can be quickly updated or split into versions, than a book that is already somewhat outdated from the day I buy it.
I learned programming with allegro 4. I think, back then, it was really what a beginner needs to know, I could paste some commands, allocate some memory, write to it, blast it to the screen and write messy code. It was ideal for hacking.
I remember that I tried allegro 5 once, it worked immediately, but I feel its concepts are (probably obviously) more advanced than those of allegro 4. For me the point is: when I am able to understand and use allegro 5, I am probably also able to use other advanced libraries to create games and "surpass" it. For example, I use a lot of Qt with OpenGL directly, so I have no reason to come back to allegro 5 again, althought in itself, it is not bad. Since a long time, Qt does the event loop stuff, platform-independent threading, networking stuff, GUI and a lot of other neat things for me. For an advanced game I probably would look into readily available engines and adapt them.
The "hacking it together"-mentality of allegro 4 gave it its own validity.
edit:The whole point: allegro 4 was so simple you did not need a book to understand it.
Qt is great for games. It has Android and iOS ports, 90% of the drawing operations you need in OpenGL for 2D games, the list just goes on. Oh wait, that's Allegro 5!
For fun, I reformatted the given chapter using a more standard textbook page size and formatting style. It reduces the chapter from nine pages to two and a half, which is still, in my opinion, a bit too long to devote to showing how to create a dialog box.
I was going to edit the text to a language style that I considered more appropriate for such a book, but then I realized I'd have to rewrite everything, so didn't bother. Especially since, as I already mentioned, I think this topic is given far more length than it deserves.
Also, the code sample given needs to be rewritten:
#include <allegro5\allegro.h>
#include <allegro5\allegro_native_dialog.h>
int main(void)
{
al_show_native_message_box(NULL, "3.5", "321World!",
"Hello world!", "Whatever|Maybe","ALLEGRO_MESSAGEBOX_YES_NO");
return -1;
if(!al_init())
{
al_show_native_message_box(NULL, NULL, NULL, "Error!", NULL,
NULL);
return -1;
}
}
I haven't really done any A5 programming, but I'm sure this is what you want:
#include <allegro5/allegro.h>
#include <allegro5/allegro_native_dialog.h>
int main()
{
if(!al_init())
{
al_show_native_message_box(NULL, NULL, NULL, "Error!", NULL,
ALLEGRO_MESSAGEBOX_ERROR);
return -1;
}
al_show_native_message_box(NULL, "3.5", "321World!",
"Hello world!", "Whatever|Maybe",ALLEGRO_MESSAGEBOX_YES_NO);
return 0;
}
Even then, will the al_show_native_message_box(NULL, NULL, NULL, "Error!", NULL, NULL); line even work if al_init() fails?
edit: Apparently the answer to that last question is yes, going by the manual.
Qt is great for games. It has Android and iOS ports, 90% of the drawing operations you need in OpenGL for 2D games, the list just goes on. Oh wait, that's Allegro 5!
I think you are not up-to-date. Qt also offers a powerful 2D object engine, btw. Forget about writing low-level object handling stuff, place your objects and run your game. What about networking in allegro 5?
I have tested Necessitas and it works great. Afaik, there are also efforts to have Qt on the iPhone, but I am too lazy to google for it.
edit:Another link:
None of that is actually good for games, aside from the networking. But I remember, you couldn't compile A5 yourself so you found something easier.
Just to demonstate. Here are the top rated games on qt-apps.org. These are the type of games you'd get with an operating system, but far from anything complex:
As someone who has been using Allegro 5 for about 2 weeks, I can safely say from MY point of view that I wont ever want for another "games" library. It's easy to build under Windows with CMake, easy to link under Code::Blocks, and a pleasure to work with using events & blenders. Plus the options of integrating your own shaders makes it a 2D powerhouse. All input is handled, and addons include .ttf fonts and audio.
Anyone who doesn't like Allegro can't understand Allegro. No, can't build & install Allegro.
----------------------------------------------------Please check out my songs:
But I remember, you couldn't compile A5 yourself so you found something easier.
There is no reason to be that arrogant. I had issues with cmake, since I never used it before at that time. Of course, I got it to compile. I am not Super-Trent, sorry.
While it's true that not many people use Qt for games, it is more than capable for this. Look here for what's possible with Qt: (Under Industry select "Games/Entertainment")
The whole point: allegro 4 was so simple you did not need a book to understand it.
Yes, it's so simple nobody has written tons of tutorials on it and a book. Why would they? In addition, since Allegro 5 is so complex, that currently, without a book, positively nobody is using it.
While it's true that not many people use Qt for games, it is more than capable for this.
So's Excel, and it's hardly an alternative to Allegro . I really don't see your point... you can use OpenGL with Qt? You could use OpenGL with Allegro 4 too. The point of Allegro 5 is that you don't have to use OpenGL directly... Allegro will use OpenGL on Linux/OSX, Direct3D/OpenGL on Windows, OpenGL ES on Android/iOS... all while abstracting the differences between those frameworks.
As for there being high level engines out there (like QGraphicsScene), A4 had the same issue, so it's hardly a point of comparison between A5 and A4. If you liked using low level features in A4, you'll like using them in A5. If you don't like using low level features, then you weren't/won't be using A4 to begin with.
"For in much wisdom is much grief: and he that increases knowledge increases sorrow."-Ecclesiastes 1:18[SiegeLord's Abode][Codes]:[DAllegro5]:[RustAllegro]
Hey Alex-G, keep up the good work.
Here is some feedback on chapter 2:
Being a string you will have to put between parentheses in order for it to work
-> I think you mean quotes: ", not parentheses: ()
The same thing goes to the third parameter and the fourth
-> The same goes for the third and fourth parameters.
in order for it to work
-> This is correct, but a very dense style that is more appropriate for scientific papers. It might be simpler to write "to make it work", or remove that bit of the sentence all together.
When I write code tutorials, I always like to give the code a distinctive style from the rest of the text. For example create a style in word for code, using a monospace font (such as courier new), and a light-grey background.
Final remark, you use a rather large font size. No wonder you write so many pages so quickly For the final version you will probably want to use a smaller font size.
Anyway, I applaud the effort. You probably won't make any money on this, but if it helps somebody, than it's totally worth it. I wrote a couple of tutorials myself a long time ago, and I still occasionally get positive feedback on it.
--Martijn van Iersel | My Blog | Sin & Cos | Food Chain Farm | TINS 2022 is Aug 5-8
Thanks for the feedback.
I use large font size, because there may be people with problems in reading bookswith little text. I myself hate little text because it makes your eyes dehydratate.
I think the text has to be big since there is no way the users will want to read little text. The book is going great and i will try to include what i will learn on this forum too. One think i am greatly keen on now is the transformations. I made some nice mods to the old game i made last year and i think the work on the book has to go on.
There were some negative comments with the idea of the book, which i think were extremely stupid and lowered the notoriety of the users writing them.
Again, thanks for all replies even to haterZ!
I read quite quickly (compared to most people, not you guys ), and I find the font being this big an irritant. My eyes are getting sore from moving left to right so quickly, and its difficult to read at my normal speed.
If you want to please people with poor eyesight, then keep it at 12 or 14 pt for regular text. I wouldn't even print this out, because I'd have to use a LOT of paper to get the info I wanted.
I usually take normal-sized pdf books and print them 4-6 pages per sheet to save paper.
EDIT:
I know its asshole-ic of me to ask without reading, but what are you using to write this in? Spinning off of Amarillion, it may be beneficial to syntax-highlight your code, that way it can be analyzed easily. Line numbers are a must.
LinkedIn | "I explain everything possible, which is normally in my knowledge."
I am using word 2010 to write it.The font size is 22 but i will reduce it to 16 and there will be much less pages than expected.
If you write your code in an IDE, they usually have an export to rtf/html action. You can use that to copy your beautifully formatted (and dare I say functional!) code into word.
Personally, I still feel that 16pt is header sized font. There is the 'zoom' feature on the computer, and I'm pretty sure that anyone who has problems reading printed text probably already has reading glasses.
If you are using word 2010, I believe it has a way to index things. A book can never be better than its index!
16pt is still absurdly large. Fonts for print are generally 8 to 9pt. At the current rate, this book is going to be several thousand pages which means it would never be able to exist in physical form as the printing costs would be astronomical.
As much as I like the idea of a book for Allegro 5, I'm afraid I have to consider the current effort to be misguided and far too poorly written to be of practical use.
Since everyone else is being too polite, I'm going to be the one to say it: if you're still at the level of asking questions like this one, you shouldn't be writing books about Allegro 5 or game programming.
-- Move to the Democratic People's Republic of Vivendi Universal (formerly known as Sweden) - officially democracy- and privacy-free since 2008-06-18!
I don't know what size is going to be the font then. I will let you guys choose it, as best as possible.
@gnolamActually, go ask other people, who are very polite to give prices to their books around 20$-60$.
EDIT: BTW, i now know how to make the autoshooter.... so i am the right person to make the book! | https://www.allegro.cc/forums/thread/610865/964150 | CC-MAIN-2022-33 | refinedweb | 2,496 | 73.07 |
How to Raise Funds for Your Nonprofit through Direct Mail
Direct mail, the practice of soliciting donations through large-scale mailings, grows out of a sophisticated and fascinating area of fundraising. Your nonprofit organization may be much too small to make investing in a direct-mail campaign worthwhile, but you can use valuable tips from the big guys and develop small-scale letter-writing efforts that yield good results.
Direct mail
If you want to try large-scale direct-mail fundraising, hire a direct-mail consultant or firm to handle your campaign. Direct-mail fundraising can be an expensive investment, and you want the best, most up-to-date professional advice available.
Successful direct mail depends on the following:
A cause that’s meaningful to many thousands of people across your state or the country
A compelling, well-presented letter that makes its reader believe that your nonprofit can make a difference
A well-chosen mailing list, usually purchased from a list broker
Nonprofit bulk-rate postage, which can save you a significant amount over commercial mailing rates
Easy, clear ways your letter readers can respond to the request by using a return envelope, response card, or website
Testing your letter and list at a modest scale before sending the letter to hundreds of thousands of names
A mailing schedule through which you solicit donors several times each year
When writing a fundraising letter, remember that many potential donors will read your letter’s P.S. before they read the body of the letter, so include compelling information there, such as a testimonial from a client, a statistic that demonstrates your organization’s accomplishments, or information about a matching gift.
Successfully raising money through the mail depends on gradual development of a loyal cadre of donors who respond by mail. Fewer than 1 percent of the people you initially mail to may send contributions, but after they give, you add them to your donor list. You can send mail to these generous folks in the future and expect a higher rate of return (between 6 percent and 12 percent).
Donors who make repeat contributions are likely to stick with your organization for several years, making three or four (or more!) contributions in that time, and they’ll likely increase the size of their contributions. Adding to this value, you’ll uncover prospects for major gifts and planned gifts (contributions from bequests) among these donors.
Before your donor list develops into a significant and loyal resource, a direct-mail campaign on your organization’s behalf may only break even on the cost of the initial letter-writing campaign. You may even lose money. That’s why direct mail may not be appropriate for a small or start-up organization: The financial risk is too high.
Letter-writing campaigns
Given the risks and costs of direct mail, borrow some of its techniques and work on a more affordable scale, using your organization’s small but mighty contact list and your own writing skills. The key to success is targeting donors to whom the staff, board, and volunteers are already connected in some fashion.
Your? Is the envelope a different color and size than standard envelopes? The letter itself should give readers enough information that they feel involved in the cause. Most of it should be dedicated to describing the problem that the organization is trying to solve.
After that, it should discuss how things can be turned around for the better and the organization’s specific method or program for doing so. Make the tone personal by using I and you. The letter should close with a vision for how things will look if the plan succeeds. Keep paragraphs short and emphasize key points with underlined or bolded text.
Always make it easy for your donor to respond by offering postage-paid envelopes and clear information about how to give through your website. Always include your mailing address, website, and phone number on the letter in case a donor misplaces the envelope or other materials included in the mailing.
Your nonprofit can get a permit from the post office to offer postage-paid return envelopes.
Try out your letter first on your organization’s internal lists of board contacts, clients, and donors. Then continually build your potential donor list by making it a habit to collect names, addresses, and e-mails at events you present and meetings and conferences you attend.
You want to develop a good system for recording information about new donors in order to thank them, keep in touch with them, and ask for their support again in the future. You’ll find that database programs to manage your donor information come in various degrees of complexity and prices. Choose the one that’s best for your needs. | http://www.dummies.com/how-to/content/how-to-raise-funds-for-your-nonprofit-through-dire.navId-810504.html | CC-MAIN-2015-11 | refinedweb | 799 | 55.68 |
But playing with font size is pretty safe ... No, it is not. Bold sometimes causes problems... Yes, you are right. But the word `sometimes' is not accurate. Bold *always* causes a problem when I change font size to 10x20. In a mode line, `m' becomes unreadable. (That font size is best for the display I mostly use. Everything looks fine in the default font.) Back in December 2002, Miles Bader fixed the problem by providing a patch to emacs/src/xfaces.c and an Emacs Lisp file to load. The patch works fine. I have been incorporating it with the current xfaces.c source ever since. Because I do not understand it, I have held back from committing Miles' change. First, will someone who understands the patch review it? Or should I commit the merged version of xfaces.c and see whether it breaks others people's installations? Here is the patch itself. As I said, the patch works fine with the current CVS. RCS file: /cvsroot/emacs/emacs/src/xfaces.c,v retrieving revision 1.266 diff -u -r1.266 xfaces.c --- src/xfaces.c 17 Nov 2002 23:51:19 -0000 1.266 +++ src/xfaces.c 18 Dec 2002 05:26:34 -0000 @@ -422,6 +422,13 @@ Lisp_Object Vtty_defined_color_alist; +/* A list of functions to perturb faces before final realization. + They are passed a lisp-vector containing all the attributes of the + fully-specified face, and can change any that they wish. */ + +Lisp_Object Vrealize_face_filter_functions; + + /* Counter for calls to clear_face_cache. If this counter reaches CLEAR_FONT_TABLE_COUNT, and a frame has more than CLEAR_FONT_TABLE_NFONTS load, unused fonts are freed. */ @@ -481,7 +488,7 @@ static unsigned char *xstrlwr P_ ((unsigned char *)); static void signal_error P_ ((char *, Lisp_Object)); static struct frame *frame_or_selected_frame P_ ((Lisp_Object, int)); -static void load_face_font P_ ((struct frame *, struct face *, int)); +static void load_face_font P_ ((struct frame *, struct face *, Lisp_Object *, int)); static void load_face_colors P_ ((struct frame *, struct face *, Lisp_Object *)); static void free_face_colors P_ ((struct frame *, struct face *)); static int face_color_gray_p P_ ((struct frame *, char *)); @@ -502,10 +509,10 @@ static int cmp_font_names P_ ((const void *, const void *)); static struct face *realize_face P_ ((struct face_cache *, Lisp_Object *, int, struct face *, int)); -static struct face *realize_x_face P_ ((struct face_cache *, - Lisp_Object *, int, struct face *)); -static struct face *realize_tty_face P_ ((struct face_cache *, - Lisp_Object *, int)); +static void realize_x_face P_ ((struct face *, struct face_cache *, + Lisp_Object *, int, struct face *)); +static void realize_tty_face P_ ((struct face *, struct face_cache *, + Lisp_Object *, int)); static int realize_basic_faces P_ ((struct frame *)); static int realize_default_face P_ ((struct frame *)); static void realize_named_face P_ ((struct frame *, Lisp_Object, int)); @@ -1245,14 +1252,15 @@ #ifdef HAVE_WINDOW_SYSTEM -/* Load font of face FACE which is used on frame F to display - character C. The name of the font to load is determined by lface - and fontset of FACE. */ +/* Load font of face FACE with attributes ATTRS which is used on frame F to + display character C. The name of the font to load is determined by + lface and fontset of FACE. */ static void -load_face_font (f, face, c) +load_face_font (f, face, attrs, c) struct frame *f; struct face *face; + Lisp_Object *attrs; int c; { struct font_info *font_info = NULL; @@ -1262,7 +1270,7 @@ face->font_info_id = -1; face->font = NULL; - font_name = choose_face_font (f, face->lface, face->fontset, c, + font_name = choose_face_font (f, attrs, face->fontset, c, &needs_overstrike); if (!font_name) return; @@ -6678,6 +6686,11 @@ int former_face_id; { struct face *face; + /* The set of attributes this face is know by to the user, as opposed to + the set actually used to render the face. They're usually the same + as, but may be different if some attribute is changed by + realize-face-filter. */ + Lisp_Object *orig_attrs = attrs; /* LFACE must be fully specified. */ xassert (cache != NULL); @@ -6691,41 +6704,70 @@ free_realized_face (cache->f, former_face); } + if (CONSP (Vrealize_face_filter_functions)) + { + /* Call these user-defined functions to perturb the face attributes + before realization. */ + Lisp_Object filters, cycle_check; + Lisp_Object lface = Fmake_vector (make_number (LFACE_VECTOR_SIZE), + Qunspecified); + + bcopy (attrs, XVECTOR (lface)->contents, + LFACE_VECTOR_SIZE * (sizeof *attrs)); + + cycle_check = Qnil; + for (filters = Vrealize_face_filter_functions; + CONSP (filters); + filters = XCDR (filters)) + { + safe_call1 (XCAR (filters), lface); + cycle_check = CYCLE_CHECK (cycle_check, filters, 50); + if (NILP (cycle_check)) + break; /* cycle detected */ + } + + attrs = XVECTOR (lface)->contents; + } + + /* Allocate a new realized face. */ + face = make_realized_face (orig_attrs); + + /* Fill it in. */ if (FRAME_WINDOW_P (cache->f)) - face = realize_x_face (cache, attrs, c, base_face); + realize_x_face (face, cache, attrs, c, base_face); else if (FRAME_TERMCAP_P (cache->f) || FRAME_MSDOS_P (cache->f)) - face = realize_tty_face (cache, attrs, c); + realize_tty_face (face, cache, attrs, c); else abort (); /* Insert the new face. */ - cache_face (cache, face, lface_hash (attrs)); + cache_face (cache, face, lface_hash (orig_attrs)); #ifdef HAVE_WINDOW_SYSTEM if (FRAME_WINDOW_P (cache->f) && face->font == NULL) - load_face_font (cache->f, face, c); + load_face_font (cache->f, face, attrs, c); #endif /* HAVE_WINDOW_SYSTEM */ return face; } -/* Realize. */ +/* Realize into FACE. */ -static struct face * -realize_x_face (cache, attrs, c, base_face) +static void +realize_x_face (face, cache, attrs, c, base_face) + struct face *face; struct face_cache *cache; Lisp_Object *attrs; int c; struct face *base_face; { #ifdef HAVE_WINDOW_SYSTEM - struct face *face, *default_face; + struct face *default_face; struct frame *f; Lisp_Object stipple, overline, strike_through, box; @@ -6733,9 +6775,6 @@ xassert (SINGLE_BYTE_CHAR_P (c) || base_face); - /* Allocate a new realized face. */ - face = make_realized_face (attrs); - f = cache->f; /* If C is a multibyte character, we share all face attirbutes with @@ -6751,7 +6790,7 @@ /* to force realize_face to load font */ face->font = NULL; - return face; + return; } /* Now we are realizing a face for ASCII (and unibyte) characters. */ @@ -6921,7 +6960,6 @@ face->stipple = load_pixmap (f, stipple, &face->pixmap_w, &face->pixmap_h); xassert (FACE_SUITABLE_FOR_CHAR_P (face, c)); - return face; #endif /* HAVE_WINDOW_SYSTEM */ } @@ -7012,17 +7050,16 @@ } -/* Realize the fully-specified face with attributes ATTRS in face - cache CACHE for character C. Do it for TTY frame CACHE->f. Value is a - pointer to the newly created realized face. */ +/* Realize into FACE the fully-specified face with attributes ATTRS in face + cache CACHE for character C. Do it for TTY frame CACHE->f. */ -static struct face * -realize_tty_face (cache, attrs, c) +static void +realize_tty_face (face, cache, attrs, c) + struct face *face; struct face_cache *cache; Lisp_Object *attrs; int c; { - struct face *face; int weight, slant; int face_colors_defaulted = 0; struct frame *f = cache->f; @@ -7030,8 +7067,6 @@ /* Frame must be a termcap frame. */ xassert (FRAME_TERMCAP_P (cache->f) || FRAME_MSDOS_P (cache->f)); - /* Allocate a new realized face. */ - face = make_realized_face (attrs); face->font_name = FRAME_MSDOS_P (cache->f) ? "ms-dos" : "tty"; /* Map face attributes to TTY appearances. We map slant to @@ -7068,8 +7103,6 @@ && face->background == FACE_TTY_DEFAULT_FG_COLOR && face->foreground == FACE_TTY_DEFAULT_BG_COLOR) face->tty_bold_p = 0; - - return face; } @@ -7670,6 +7703,14 @@ Each element is a regular expression that matches names of fonts to ignore. */); Vface_ignored_fonts = Qnil; + + DEFVAR_LISP ("realize-face-filter-functions", + &Vrealize_face_filter_functions, + doc:/* A list of functions to perturb faces before final realization. +They are passed a lisp-vector containing all the attributes of the +fully-specified face, and can change any that they wish. */); + Vrealize_face_filter_functions = Qnil; + #ifdef HAVE_WINDOW_SYSTEM defsubr (&Sbitmap_spec_p); -- Robert J. Chassell Rattlesnake Enterprises As I slowly update it, address@hidden I rewrite a "What's New" segment for | http://lists.gnu.org/archive/html/emacs-devel/2004-05/msg00585.html | CC-MAIN-2013-48 | refinedweb | 1,128 | 53.41 |
#include <wx/choice.h>
A choice item is used to select one of a list of strings.
Unlike a wxListBox, only the selection is visible until the user pulls down the menu of choices.
This class supports the following styles:
The following event handler macros redirect the events to member function handlers 'func' with prototypes like:
Event macros for events emitted by this class:
wxEVT_CHOICEevent, when an item on the list is selected.
Default constructor.
Constructor, creating and showing a choice.
wxPerl Note: Not supported by wxPerl.
Constructor, creating and showing a choice.
wxPerl Note: Use an array reference for the choices parameter.
Destructor, destroying the choice item.
Finds an item whose label matches the given string.
Reimplemented from wxItemContainerImmutable.
Gets the number of columns in this choice item.
Returns the number of items in the control.
Implements wxItemContainerImmutable.
Unlike wxControlWithItems::GetSelection() which only returns the accepted selection value (the selection in the control once the user closes the dropdown list), this function returns the current selection.
That is, while the dropdown list is shown, it returns the currently selected item in it. When it is not shown, its result is the same as for the other function.
Returns the index of the selected item or
wxNOT_FOUND if no item is selected.
Implements wxItemContainerImmutable.
Returns the label of the item with the given index.
Implements wxItemContainerImmutable.
Sets the number of columns in this choice. | http://docs.wxwidgets.org/trunk/classwx_choice.html | CC-MAIN-2015-27 | refinedweb | 234 | 58.48 |
I'd like to know if it is possible in Java to nest Enums.
Here what i'd like to be able to do :
Have an enum Species made of CAT and DOG wich ...
New to java and have a question related to packages.
I like to keep objects organized in namespaces and ran into a problem with enums that I cannot figure out.
Say I have ...
I have seen constructs with an enum declared inside an enum. What is this used for ?
I want to nest some enums. The object i'm representing are Flags, with a type, and a value. There are a discrete number of types, and each type has a distinct ...
I have a data structure in mind that involves nested enums, such that I could do something like the following:
Drink.COFFEE.getGroupName();
Drink.COFFEE.COLUMBIAN.getLabel();
someMethod(Drink type)
someOtherMethod(DrinkTypeInterface type)
someMethod(Drink.COFFEE)
someOtherMethod(Drink.COFFEE.COLUMBIAN)
Hi, I was wondering whether it is possible to nest enums? My problem is that I want an enum called country and then I want a nested enum within that called state/province, is this possible? so you could do a call maybe something like this: State state = Country.US.State.NY; Thanks in advance, John
Hi I am trying to get some nested enums working. My requirement is that I have a n number of groups where each group in itself has set of data like ( string, int, int). I need to first randomly choose a group and then randomly choose a set of data from that group. I tried using nested enums as given ...
The following code works but I would like to somehow be able to nest the FOOVariant and FOOProtAttr enumerated types within the FOOTypeMapping enum, does anyone know if this is possible? I'm not quite sure how to go about embedding those two enums Thanks in advance John public enum FOOVariant { A,B,C,D; } public enum FOOProtAttr { ATTR1, ATTR2, ATTR3; } ... | http://www.java2s.com/Questions_And_Answers/Java-Data-Type/enum/nest.htm | CC-MAIN-2017-30 | refinedweb | 332 | 81.93 |
Open multiple web browser tabs?
I would like my script to be able to open multiple browser tabs. I tried using webbrowser.open, webbrowser.open_new and webbrowser.open_new_tab but each time I get only one tab. Is there way to do what I want and can someone give me a simple example?
Are you using beta? the app store webbrowser only has open(), as far as i can tell....
One approach is to simply use a ui.WebView(), and present to a sheet. You don't get a back button, but thats easy to add. If you want something full featured, @Sebastian wrote a very nice webbrowser (with address bar, back buttons, etc) that is completely ui based, and lives in a panel tab, and you can open multiple such tabs.
@JonB Thanks. I am using the Beta and I was just trying to use webbrowser.open_new and webbrowser_new_tab methods which are there and documented but do not seem to do anything different from what webbrowser.open() does. I thought that perhaps this was a limitation of the in-app browser so I tried the other (documented) feature of specifying a browser to be used. webbrowser._new(safari- does open Safari but I still can't get 2 tabs to be started. Likewise for Chrome. I will look into the Pythonista built browsers.
This works for me.
import ui import webbrowser def show_url_google(sender): webbrowser.get('safari').open_new_tab(' def show_url_python(sender): webbrowser.get('safari').open_new_tab(' def show_url_apple(sender): webbrowser.get('safari').open_new_tab(' v = ui.View(frame=(0,0,600,400)) v.add_subview(ui.Button(title='google', frame=(50,200,100,100), action=show_url_google)) v.add_subview(ui.Button(title='python', frame=(300,200,100,100), action=show_url_python)) v.add_subview(ui.Button(title='apple', frame=(450,200,100,100), action=show_url_apple)) v.present('sheet')
Thank you. I will use your code; however, I am still left wondering why some version of the calls to webbrowser.get (or get_new or get_new_tab)
doesn't work. Why are the subviews necessary? That is, why doesn't this work:
webbrowser.get('safari').open_new_tab('
webbrowser.get('safari').open_new_tab('
webbrowser.get('safari').open_new_tab('
have you tried @on_main_thread? That is one difference between a buttin callback and a regular command...
@jonb I have never used that but I will look into it. I just naively thought that a script with those three lines would work. My coding confidence is eroded when supposedly simple things don't work as expected :-)
My objective is to open 3 tabs in (any) browser. I want the script to open these tabs with 3 different URLs that are partly constructed with speech input. Everything works fine until I try to open the 3 tabs. Only one is opened. I don't want any buttons or anything more to click. I thought that those three lines (obviously with different URLs) would do the trick but apparently this is more complex than it seems.
Here's explanation of what's going on here ...
webbrowser.get('safari').open_new_tab()
This one internally calls
UIApplication.openURL_(), which causes this:
- first call - Pythonista goes to background, because Safari is launched,
- subsequent calls do nothing, because Pythonista (any app) is not allowed to call
openURL_()when the app itself is in the background.
But this works if you have an iPad and both apps (Pythonista, Safari) are open side by side. When you try it, all three URLs are opened in Safari. If you don't have them side by side, there's no way.
See
safari_open_urlsin the attached sample.
webbrowser.open_new_tab
This one does use in app browser -> panel. But it's buggy / unfinished, because it reuses same tab for all subsequent calls. When I check the implementation, it just sends notification with
URL,
revealwithout
newarg (ignored), which should control stuff like new tab, ...
See
default_open_urlsin the attached sample. All three URLs are opened in 3 seconds interval, one by one, in the same tab.
ui.View.present('panel')
See
webview_open_urlsin the attached sample. This one works and nicely opens all three URLs at once. The only con is missing controls, but you can easily add them.
#!python3 def webview_open_urls(urls): # Present custom ui.View as panel, works import ui for name, url in urls: webview = ui.WebView() webview.name = name webview.load_url(url) webview.present('panel') def default_open_urls(urls): # Use default (inapp) webbrowser, which is buggy, because it doesn't open new tab, just one tab is reused import webbrowser import time for name, url in urls: webbrowser.open_new_tab(url) time.sleep(3) def safari_open_urls(urls): # Use Safari webbrowser, which doesn't work, you can't call openURL from background import webbrowser for name, url in urls: webbrowser.get('safari').open_new_tab(url) if __name__ == '__main__': webview_open_urls([ ('OMZ', ' ('Editorial', ' ('Pythonista', ' ])
@zrzka The last construction is exactly what I need. Thank you. I guess that I had no way to know that simply calling webbrowser.open_new_tab multiple times would not work as documented.
@jonb The UI webview solution works but I am interested in understanding what you were suggesting. Is there a way to this without UI that uses either the inapp browser or an external browser by utilizing @on_main_thread? If so, can you elaborate or perhaps give me an example? I tried creating a function that simply called webview.open_new_tab and then "decorating" with @on_main_thread but that didn't help.
I thought you said @enceladus 's code worked, which if true, you should be able to just call one of those methods, wrapped with
on_main_threadand achieve the same result. @zrzka seemed to clarify that this launches safari, not in a tab.
@JonB Did you try running my app? It opens the urls in new tabs if the urls are different. I guess that the explanation for "why it works" is that one has to bring the application to front before pressing the next button and it is not possible with "on_main_thread" .
Here is a stackflow answer for a related question.
If you have editorial, you can use the following script to open multiple urls in editorial's in-app browser.
import webbrowser, clipboard ''' Install this worflow in editorial before running this program. editorial://add-workflow?workflow-data-b64=eNrFk09rwkAQxb9KmXNa7DWXEkWKEFSiIqWUMCajLq67y2bWKCHfvbNSipeeWuppltn3Hr_ZPx1gxcqaBtL3DiqNjaxgbf1hq22bXfdeiUdauY1FX0MCDkNDQ9paT0UwRpkdpFvUDSVQhYbtcalYk6RctR6PxOQlteu_vGvFext4sbetmOc3kmtMn_wEMj6zF9xVkTd35SjIEXK058rQfVlmjowcyG8YIPqlsD2QKdDs6NrtBsnDcy_6iXGBQUj54qIf6xOaiuolnVmyOJYUXqKiRcUrw0rnFmuqvwE8nQj10Nu2IZ8FgUFWFWp9gZR9EIWVOSYG0oEE4mbm4myQPv_1XY3NvzzhjwSMtCQhzlUeg2blNJXB66ZUpqxu_pOq4qSwfJtPRrPp4jHL83Ixz6bTcfHkhKz_BEm5US8~ This workflow is modified version of the following workflow. ''' urls = [ ' ' ' ] clipboard.set('\n'.join(urls)) webbrowser.open('editorial://?command=open_multiple_urls_in_clipboard') | https://forum.omz-software.com/topic/4435/open-multiple-web-browser-tabs/9 | CC-MAIN-2022-21 | refinedweb | 1,049 | 59.5 |
The .NET Stacks, #60: 📝Logging improvements in .NET 6
This week, we're talking about logging improvements that are coming with the .NET 6 release.
Happy Monday! It's hard to believe it's August already. What are we talking about this week?
- One big thing: Logging improvements in .NET 6
- The little things: Notes from the community
- Last week in the .NET world
One big thing: Logging improvements in .NET 6
Over the last few months, we've highlighted some big features coming with .NET 6. Inevitably, there are some features that fly under the radar, including various logging improvements that are coming. Let's talk about a few of them.
Announced with Preview 4 at the end of May, .NET will include a new Microsoft.Extensions.Logging compile-time source generator. The
Microsoft.Extensions.Logging namespace will expose a
LoggerMessageAttribute type that generates "performant logging APIs" at compile-time. (The source code relies on
ILogger, thankfully.)
From the blog post:
The source generator is triggered when
LoggerMessageAttributeis used on
partiallogging methods. When triggered, it is either able to autogenerate the implementation of the
partialmethods it’s decorating, or produce compile-time diagnostics with hints about proper usage. The compile-time logging solution is typically considerably faster at run time than existing logging approaches. It achieves this by eliminating boxing, temporary allocations, and copies to the maximum extent possible.
Rather than using
LoggerMessage APIs directly, the .NET team says this approach offers simpler syntax with attributes, the ability to offer warnings as a "guided experience," support for more logging parameters, and more.
As a quick example, let's say I can't talk to an endpoint. I'd configure a
Log class like this:
public static partial class Log { [LoggerMessage(EventId = 0, Level = LogLevel.Critical, Message = "Could not reach `{uri}`")] public static partial void CouldNotOpenSocket(ILogger logger, string uri); }
There is much, much more at the Microsoft doc, Compile-time logging source generation.
On the topic of HTTP requests, ASP.NET Core has a couple of new logging improvements worth checking out, too. A big one is the introduction of HTTP logging middleware, which can log information about HTTP requests and responses, including the headers and body. According to the documentation, the middleware logs common properties like path, query, status codes, and headers with a call to
LogLevel.Information. The HTTP logging middleware is quite configurable: you can filter logging fields, headers to log (you need to explicitly define the headers to include), media type options, and a log limit for the response body.
This addresses a common use case for web developers. As always, you'll need to keep an eye on possible performance impacts and mask logging sensitive information (like PII data).
Lastly, with .NET 6 Preview 5 the .NET team rolled out subcategories for Kestrel log filtering. Previously, verbose Kestrel logging was quite expensive as all of Kestrel has shared the same category name. There are new categories on top of
*.Server.Kestrel, including
BadRequests,
Connections,
Http2, and
Http3. This allows you to be more selective on which rules you want to enable. As shown in the blog post, if you only want to filter on bad requests, it's as easy as this:
{ "Logging": { "LogLevel": { "Microsoft.AspNetCore.Kestrel.BadRequests": "Debug" } } }
If you want to learn more about ASP.NET Core logging improvements in .NET 6, Maryam Ariyan and Sourabh Shirhatti will be talking about it in Tuesday's ASP.NET standup.
The little things: Notes from the community
AutoMapper is a powerful but self-proclaimed "simple little library" for mapping objects. From Shawn Wildermuth on Twitter, Dean Dashwood has written about Three Things I Wish I Knew About AutoMapper Before Starting. It centers around subtleties when working with dependency injection in models, saving changed and nested data, and changing the models. It's actually a GitHub repo with a writeup and some code samples—highly recommended.
Sometimes one sentence does the trick: Cezary Piątek has a nice MsBuild cheatsheet on GitHub.
This week, Mike Hadlow wrote about creating a standalone
ConsoleLoggerProvider in C#. If you want to create a standalone provider to avoid working with dependency injection and hosting, Mike found an ... interesting ... design. He develops a simple no-op implementation.
Well, it's been 20 years since the Agile Manifesto, and Al Tenhundfeld celebrates it with the article Agile at 20: The Failed Rebellion. I think we can all agree that (1) everybody wants to claim they are Agile, and (2) Agile is a very, um, flexible word—nobody is really doing Agile (at least according to the Manifesto). He explores why; an interesting read.
🌎 Last week in the .NET world
🔥 The Top 3
- Oren Eini writes that System.Threading.Tasks.Task isn’t an execution unit.
- Andrew Lock continues his deep dive on StringBuilder, and so does Steve Gordon.
- Al Tenhundfeld speaks the truth on Agile.
📢 Announcements
- Dapr v1.3 is now available.
- Michael Hawker introduces the Community Toolkit.
- Uno Platform shows off improvements with 3.9.
📅 Community and events
- Jeremy Miller writes about Marten, the generic host builder in .Net Core, and more.
- Mike Brind is writing a book about Razor Pages.
- Sha Ma writes about GitHub's journey from monoliths to microservices.
- Richard Lander posts a discussion about the .NET open source project.
- Matthew MacDonald asks: what if GitHub Copilot worked like a real programmer?
- The .NET Docs Show talks to Vahid Farahmandian about gRPC and .NET 5.
- For community standups: ASP.NET talks to Isaac Abraham about F#, and Entity Framework talks about OData.
- Check out all the Focus on F# sessions on YouTube.
🌎 Web development
- The Code Maze blog writes about Onion Architecture in ASP.NET Core.
- Damien Bowden secures ASP.NET Core Razor Pages and Web APIs with Azure B2C External and Azure AD internal identities.
🥅 The .NET platform
- Mike Hadlow creates a standalone ConsoleLoggerProvider.
- Santosh Hari uses app secrets in .NET Core console apps.
⛅ The cloud
- April Edwards compares Azure Static Web Apps, Azure WebApps, and Azure Blob Storage Static Sites.
- Mark Heath writes about the serverless sliding scale.
- John Kilmister gets started with serverless SignalR and Azure Functions.
- Paul Michaels configures Cloudflare to work with Azure domains.
📔 Languages
- Anthony Giretti writes about extended property patterns in C# 10.
- Gergely Sinka toggles functionality in C# with feature flags.
🔧 Tools
- David Ramel writes about Entity Framework Core 6.
- Rachel Appel writes about Blazor debugging improvements in Rider 2021.2.
- Khalid Abuhakmeh writes an extension method that parses a redis-cli connection string for the StackExchange.Redis library.
- Dmitry Lyalin writes about hot reload in Visual Studio 2022.
- Kat Cosgrove writes about Kubernetes fundamentals.
- Matthew Jones creates a Dapper helper C# class to generate parameterized SQL.
📱 Xamarin
- Leomaris Reyes reproduces a fashion UI in Xamarin.
- Charlin Agramonte creates an expandable paragraph control in Xamarin.
🏗 Design, testing, and best practices
- Oren Eini writes about flexible business systems.
- Derek Comartin uses a message-driven architecture to decouple a monolith.
- Charles Humble writes about the future of microservices.
- Suzanne Scacca uses heatmaps to audit web design.
- Davide Bellone explores the tradeoffs of performance and clean code.
- Ben Nadel writes about feature flags.
- Jimmy Bogard continues his series on domain-driven refactoring.
- Ian Cartwright, Rob Horn, & James Lewis write about feature parity.
- InfoQ talks to Michael Perry about immutable architecture, the CAP theorem, and CRDTs.
🎤 Podcasts
- The 6-Figure Developer Podcast talks to Bryan Hogan about Polly.
- Adventures in .NET talks about the global reach of .NET.
- The Merge Conflict podcast talks about FOSS and .NET MAUI Web with Ooui.
- The .NET Core Podcast discusses Gremlinq With Daniel Weber.
- The Azure DevOps Podcast talks about what's coming for developers.
- Scott Hanselman talks to Don Syme about F#.
- The Azure Podcast talks about Azure Arc.
🎥 Videos
- The ASP.NET Monsters works on accessibility testing with Playwright and Axe.
- Luis Quintanilla rolls out a nice "intro to F#" video series.
- Shawn Wildermuth talks about changes coming to Startup in .NET 6.
- On .NET talks about ValueTask in C#. | https://www.daveabrock.com/2021/08/08/dotnet-stacks-60/ | CC-MAIN-2021-39 | refinedweb | 1,334 | 60.21 |
New order of LoPy - deep sleep issues?
Hi,
I am contemplating ordering a couple more LoPy's. However I was quite dissapointed the last time I ordered when receiving a product that doesn't really live up to the specs.. It says:
– Ultra-low power usage: a fraction compared to other connected micro controllers
However even with the deep sleep shield (which also adds bulk) it seems that this isn't really the case..
Maybe I missed something, but I did not see any disclaimer anywhere when ordering, that it was basically not functioning as advertised - not very cool..
So I was wondering if we can expect a fix on the LoPy so that new orders will receive actual functioning products - or if it is a better bet to go for the LoPy4 maybe?
I'm using an Lopy4 powered by a Lifepo4 battery. For testing purposes I'm reading a sensor (bme280), sending the data using lora and then going to sleep for about 10 minutes.
@sioo can you clarify your setup? LoPy or LoPy 4? Deep Sleep shield, expansion board, Pysense, PyTrack? Power source? Any active sensors?...
Since last time I tried the test script again, with the latest firmware (from 3 days ago). Now I get down to 16.5 uA. Not sure if the firmware is related.
Interesting is that when testing the same board on our custom hardware, I can get down to ~13uA. Maybe because some pins aren't floating anymore?
Anyways, it seems to be possible now to get below 20uA in deep sleep.
Edit: And I also sometimes experience the issue that the LED quickly lights up when waking up from sleep or when powering on the device for the first time.
So, with the simple code below, the heartbeat LED pulses very briefly when my LoPy wakes from deep sleep.
I'll give it a test tonight as well.
@dbrgn All right, so that's two lines are unnecessary:
pycom.heartbeat(False)
pycom.wifi_on_boot(False)
I think I wouldn't even need to disable wifi on boot, since it should be off in deep sleep anyways.
@dbrgn Don't need to disable the Bluetooth/BLE too, like as you did with WiFi (pycom.wifi_on_boot(False)) ?
With nothing but the LoPy4 connected to the Otii (at 3.75V with auto range mode) I measure ~32uA in deep sleep.
Is this the best we can expect, or should it go lower?
This is the code (boot.py):
import machine import pycom pycom.heartbeat(False) pycom.wifi_on_boot(False) machine.deepsleep(15000)
As soon as I connect it to the expansion board (with all jumpers removed, power supply via JST connector) current goes to ~170uA.
@robin I use this device.
You can also use a resistor in series with the 5V input and measure the voltage drop. You just have to size it correctly so you still get enough voltage to run the device. You also have to short it out till the device is asleep.
This tool can be also interesting
or a bit more expensive but more complex
@jmarcelino
I was not aware of such device, are you satisfied with it? What are the most notable issues/drawbacks from you experience?
I am considering to buy it.
- jmarcelino last edited by
@robin
I use this tool now, not the cheapest thing but very convenient.
I use this tool:
Unfortunately, it seems to be out of stock.
@mahe
I have a LoPy4 in front of me and am considering how to test power consumption. Previously i had someone who helped with an oscilloscope, but that is a quite impractical for me at the moment. Is there another way to measure low power current drain from the battery? Presumably a multimeter is too imprecise?
@jmarcelino said in New order of LoPy - deep sleep issues?:
Yes the L01 + baseboard combination will give you very low power deepsleep right now.
Any estimation what very low means? | https://forum.pycom.io/topic/2077/new-order-of-lopy-deep-sleep-issues | CC-MAIN-2022-21 | refinedweb | 659 | 74.49 |
audio_engine_channels(9E)
audio_engine_playahead(9E)
- request to transport a SCSI command
#include <sys/scsi/scsi.h> int prefixtran_start(struct scsi_address *ap, struct scsi_pkt *pkt);
Solaris architecture specific (Solaris DDI).
Pointer to the scsi_pkt(9S) structure that is about to be transferred.
Pointer to a scsi_address(9S) structure.
The tran_start() vector in the scsi_hba_tran(9S) structure must be initialized during the HBA driver's attach(9E) to point to an HBA entry point to be called when a target driver calls scsi_transport(9F).
tran_start() must perform the necessary operations on the HBA hardware to transport the SCSI command in the pkt structure to the target/logical unit device specified in the ap structure.
If the flag FLAG_NOINTR is set in pkt_flags in pkt, tran_start() should not return until the command has been completed. The command completion callback pkt_comp in pkt must not be called for commands with FLAG_NOINTR set, since the return is made directly to the function invoking scsi_transport(9F).
When the flag FLAG_NOINTR is not set, tran_start() must queue the command for execution on the hardware and return immediately. The member pkt_comp in pkt indicates a callback routine to be called upon command completion.
Refer to scsi_pkt(9S) for other bits in pkt_flags for which the HBA driver may need to adjust how the command is managed.
If the auto_rqsense capability has been set, and the status length allocated in tran_init_pkt(9E) is greater than or equal to sizeof(struct scsi_arq_status), automatic request sense is enabled for this pkt. If the command terminates with a Check Condition, the HBA driver must arrange for a Request Sense command to be transported to that target/logical unit, and the members of the scsi_arq_status structure pointed to by pkt_scbp updated with the results of this Request Sense command before the HBA driver completes the command pointed by pkt.
The member pkt_time in pkt is the maximum number of seconds in which the command should complete. Timeout starts when the command is transmitted on the SCSI bus. A pkt_time of 0 means no timeout should be performed.
For a command which has timed out, the HBA driver must perform some recovery operation to clear the command in the target, typically an Abort message, or a Device or Bus Reset. The pkt_reason member of the timed out pkt should be set to CMD_TIMEOUT, and pkt_statistics OR'ed with STAT_TIMEOUT. If the HBA driver can successfully recover from the timeout, pkt_statistics must also be OR'ed with one of STAT_ABORTED, STAT_BUS_RESET, or STAT_DEV_RESET, as appropriate. This informs the target driver that timeout recovery has already been successfully accomplished for the timed out command. The pkt_comp completion callback, if not NULL, must also be called at the conclusion of the timeout recovery.
If the timeout recovery was accomplished with an Abort Tag message, only the timed out packet is affected, and the packet must be returned with pkt_statistics OR'ed with STAT_ABORTED and STAT_TIMEOUT.
If the timeout recovery was accomplished with an Abort message, all commands active in that target are affected. All corresponding packets must be returned with pkt_reason, CMD_TIMEOUT, and pkt_statistics OR'ed with STAT_TIMEOUT and STAT_ABORTED.
If the timeout recovery was accomplished with a Device Reset, all packets corresponding to commands active in the target must be returned in the transport layer for this target. Packets corresponding to commands active in the target must be returned returned with pkt_reason set to CMD_TIMEOUT, and pkt_statistics OR'ed with STAT_DEV_RESET and STAT_TIMEOUT. Currently inactive packets queued for the device should be returned with pkt_reason set to CMD_RESET and pkt_statistics OR'ed with STAT_ABORTED.
If the timeout recovery was accomplished with a Bus Reset, all packets corresponding to commands active in the target must be returned in the transport layer. Packets corresponding to commands active in the target must be returned with pkt_reason set to CMD_TIMEOUT and pkt_statistics OR'ed with STAT_TIMEOUT and STAT_BUS_RESET. All queued packets for other targets on this bus must be returned with pkt_reason set to CMD_RESET and pkt_statistics OR'ed with STAT_ABORTED.
Note that after either a Device Reset or a Bus Reset, the HBA driver must enforce a reset delay time of 'scsi-reset-delay' milliseconds, during which time no commands should be sent to that device, or any device on the bus, respectively.
tran_start() should initialize the following members in pkt to 0. Upon command completion, the HBA driver should ensure that the values in these members are updated to accurately reflect the states through which the command transitioned while in the transport layer.
For commands with data transfer, this member must be updated to indicate the residual of the data transferred.
The reason for the command completion. This field should be set to CMD_CMPLT at the beginning of tran_start(), then updated if the command ever transitions to an abnormal termination state. To avoid losing information, do not set pkt_reason to any other error state unless it still has its original CMD_CMPLT value.
Bit field of transport-related statistics.
Bit field with the major states through which a SCSI command can transition. Note: The members listed above, and pkt_hba_private member, are the only fields in the scsi_pkt(9S) structure which may be modified by the transport layer.
tran_start() must return:
The packet was accepted by the transport layer.
The packet could not be accepted because there was already a packet in progress for this target/logical unit, the HBA queue was full, or the target device queue was full.
The DMA count in the packet exceeded the DMA engine's maximum DMA size, or the packet could not be accepted for other reasons.
A fatal error has occurred in the HBA.
The tran_start() function can be called from user or interupt context. This requirement comes from scsi_transport().
attach(9E), tran_init_pkt(9E), scsi_hba_attach(9F), scsi_transport(9F), scsi_address(9S), scsi_arq_status(9S), scsi_hba_tran(9S), scsi_pkt(9S) | http://docs.oracle.com/cd/E19963-01/html/821-1476/tran-start-9e.html | CC-MAIN-2014-35 | refinedweb | 973 | 51.28 |
1. Install Real-time Java VM
There is a bunch of RT VMs that you can donwload and use but perhaps the one that is the easiest to install and to play with is Oracle's Java RTS. The current version is Java RTS 2.2. After filling the download form, you should be able to download it to your desktop. The name of the donwloaded file will be something like : java_rts-2_2-fcs-bin-b19-linux-i586-eval_academic.zip
1.0 Requirements
- RT Linux - if you want to really run with real-time priorities. However, for starting and learning how to work with RT VMs, a regular linux should do - try eg. Ubuntu or Fedora OS.
untar downloaded distributable into /opt/jrts2.2 directory. Let's call it RTJAVA_HOME.
$ export RTJAVA_HOME=/opt/jrts2.2/
For more details, see SUN Java RTS Technical Documentation. Java RTS is distributed under restricted academic license that expires after 365 days but don't worry, you can just dowload a new distribution and re-install it.
1.2. Verify the Installation
Type:
You should see:
$ $RTJAVA_HOME/bin/java -version
java version "1.5.0_20" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_20_Java-RTS-2.2_fcs-b19_RTSJ-1.0.2) Java Real-Time System HotSpot(TM) 64-Bit Client VM (build 1.5.0_20-b19, mixed mode)
In case you are not running in a real-time environment or your linux does not have the rt-kernel extensions, you will also see the following warning:
You can safely ignore this one for testing RTSJ.
Java Real-Time System HotSpot(TM) 64-Bit Client VM warning: Unable to lock pages into memory: insufficient privileges Java Real-Time System HotSpot(TM) 64-Bit Client VM warning: Cannot use the real-time scheduling class.
1.3. A missing libcap.so problem
However, a problem can occur when running the "./bin/java" on some systems:
This happened to me both on Ubuntu and Fedora OS. There is a detailed description of this problem here (as it appears, I was the first person to identify this issue).
$RTJAVA_HOME/bin/java -version
dl failure on line 824Error: failed /opt/sunrts-2.2/jre/lib/i386/server/libjvm.so, because libcap.so.1: cannot open shared object file: No such file or directory
Solution to the missing libcap.so.1 lib is to locate a libcap.so.2 and rename it as libcap.so.1
$ locate libcap.so.2
$ sudo cp /lib/libcap.so.2 /lib/libcap.so.1
2. Runnig a Real-time HelloWorld program
Now we can finally run some real-time Java code. A classical real-time Java hello world example is below:
import javax.realtime.RealtimeThread; public class HelloRealtimeWorld extends RealtimeThread { String message; public void run(){ message = "Hello Realtime World"; } public static void main(String args[]){ HelloRealtimeWorld thread = new HelloRealtimeWorld(); thread.start(); try{ thread.join(); } catch(InterruptedException ie){ System.err.println("got interrupted"); return; } System.out.println(thread.message); } }
To compile the Real-Time HelloWorld class:
$ $RTJAVA_HOME/bin/javac -classpath $RTJAVA_HOME/jre/lib/rt2.jar
-d build/ HelloRealtimeWorld.java
And, to run:
$ $RTJAVA_HOME/bin/java -cp build/ HelloRealtimeWorld
Hello Realtime World!
And we are done!
Further resources on RT Java:
- Concurrent and Real-time Java Programming book,
- try our CDx - Real-Time Java Benchmark,
- Oracle's RTSJ Introduction
- Embedded and Real-time Computing class taught by Prof. Vitek (check out the slides for selected topics)
Further blog-post on the same topic:
-
This was a great post. It solved the problems I kept running into. Saved my life. Thank you!
I ran into the problem
" failure on line 824Error: failed /usr/lib/jrts-2.2_fcs/jre/lib/amd64/server/libjvm.so, because libcap.so.1: cannot open shared object file: No such file or directory "
on Ubuntu 10.04 LTS with rt-linux
your blog entry helped me fix the problem.
Cheers
As you mentioned you are running ubuntu 10.04 with rt-kernel. Can you help me in patching rt-kernel on ubuntu 13.10.
you saved my life :D
Thank you very very much
I cannot download java_rts-2_2-fcs-bin-b19-linux-i586-eval_academic.zip
could any one put link to it in 4shared or any sharing site
I cannot download too.. does anyone know the status, and when it would be available?
There some copies of the file on some servers... search for the exact filename =)
BUT ... it's Java 1.5 Update 20... lots of things will npt run (You can run Eclipse with OpenJDK and define project specifiv the RTS as JRE))
Better try IBM WebSphere RealTime or the JamaicaVM! | http://rtjava.blogspot.com/2010/11/real-time-java-helloworld.html | CC-MAIN-2017-26 | refinedweb | 771 | 51.55 |
We are using the new kafka consumer with the following config (as logged by kafka)
metric.reporters = []
metadata.max.age.ms = 300000
value.deserializer = class org.apache.kafka.common.serialization.ByteArrayDeserializer
group.id = myGroup.id
partition.assignment.strategy = [org.apache.kafka.clients.consumer.RangeAssignor]
reconnect.backoff.ms = 50
sasl.kerberos.ticket.renew.window.factor = 0.8
max.partition.fetch.bytes = 2097152
bootstrap.servers = [myBrokerList]
retry.backoff.ms = 100
sasl.kerberos.kinit.cmd = /usr/bin/kinit
sasl.kerberos.service.name = null
sasl.kerberos.ticket.renew.jitter = 0.05
ssl.keystore.type = JKS
ssl.trustmanager.algorithm = PKIX
enable.auto.commit = false
ssl.key.password = null
fetch.max.wait.ms = 1000
sasl.kerberos.min.time.before.relogin = 60000
connections.max.idle.ms = 540000
ssl.truststore.password = null
session.timeout.ms = 30000
metrics.num.samples = 2
client.id =
ssl.endpoint.identification.algorithm = null
key.deserializer = class sf.kafka.VoidDeserializer
ssl.protocol = TLS
check.crcs = true
request.timeout.ms = 40000
ssl.provider = null
ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
ssl.keystore.location = null
heartbeat.interval.ms = 3000
auto.commit.interval.ms = 5000
receive.buffer.bytes = 32768
ssl.cipher.suites = null
ssl.truststore.type = JKS
security.protocol = PLAINTEXT
ssl.truststore.location = null
ssl.keystore.password = null
ssl.keymanager.algorithm = SunX509
metrics.sample.window.ms = 30000
fetch.min.bytes = 512
send.buffer.bytes = 131072
auto.offset.reset = earliest
We use the consumer.assign() feature to assign a list of partitions and call poll in a loop. We have the following setup:
1. The messages have no key and we use the byte array deserializer to get byte arrays from the config.
2. The messages themselves are on an average about 75 bytes. We get this number by dividing the Kafka broker bytes-in metric by the messages-in metric.
3. Each consumer is assigned about 64 partitions of the same topic spread across three brokers.
4. We get very few messages per second maybe around 1-2 messages across all partitions on a client right now.
5. We have no compression on the topic.
Our run loop looks something like this
while (isRunning()) {
ConsumerRecords<Void, byte[]> records = null;
try
catch (Exception e){ // This never hits for us logger.error("Exception polling Kafka ", e); records = null; }
if (records != null) {
for (ConsumerRecord<Void, byte[]> record : records)
}
}
With this setup our performance has taken a horrendous hit as soon as we started this one thread that just polls Kafka in a loop.
I profiled the application using Java Mission Control and have a few insights.
1. There doesn't seem to be a single hotspot. The consumer just ends up using a lot of CPU for handing such a low number of messages. Our process was using 16% CPU before we added a single consumer and it went to 25% and above after. That's an increase of over 50% from a single consumer getting a single digit number of small messages per second. Here is an attachment of the cpu usage breakdown in the consumer (the namespace is different because we shade the kafka jar before using it) - So 20.54% of our entire process CPU is used on polling these 64 partitions (across 3 brokers) with single digit number of 70-80 byte odd messages. We've used bigger timeouts (100 seconds odd) and that doesn't seem to make much of a difference either.
2. It also seems like Kafka throws a ton of EOFExceptions. I am not sure whether this is expected but this seems like it would completely kill performance. Here is the exception tab of Java mission control. That is 1.8 mn exceptions over a period of 3 minutes which is about 10 thousand exceptions per second! The exception stack trace shows that it originates from the poll call. I don't understand how it can throw so many exceptions given I call poll it with a timeout of 10 seconds and get a single digit number of messages per second. The exception seems to be thrown from here:
3. The single thread seems to allocate a lot too. The single thread is responsible for 17.87% of our entire JVM allocation rate. During other runs it has gone up to 20% of our entire JVM allocation rate. Most of what it allocates seems to be those same EOFExceptions. Here is a chart showing the single thread's allocation proportion: Here is a chart that shows a breakdown of the allocations: About 20% of the allocations are for the EOFExceptions. But given that the 20% of the allocations (exceptions) is around 10k/second, the thread itself is allocating about 50k objects/second which seems excessive given how we are getting very few messages.
As a comparison, we also run a wrapper over the old SimpleConsumer that gets a lot more data (30 thousand 70 byte messages/sec on a different topic) and it is able to handle that load without much trouble. At this moment we are completely puzzled by this performance. At least some part of that seems to be due to the crazy volumes of exceptions but the CPU profiling breakdown seems to suggest that there are plenty of other causes including the Fetcher.initFetches() call and the ConsumerNetworkClient.poll() call. Note: Our messages seem to all be making through. We haven't measured the end to end latency. The exceptions are caught by Kafka's stack and never bubble up to us.
Attachments
- links to
- | https://issues.apache.org/jira/browse/KAFKA-3159 | CC-MAIN-2020-10 | refinedweb | 907 | 62.04 |
Hi, the reading is not needed to make it happen. main = writeFile "output" blackhole where blackhole = blackhole In fact, writing is not needed either. main = bracket (openFile "output" WriteMode) hClose (\hdl -> blackhole `seq` return ()) blackhole = blackhole Note that writeFile is indeed like this, so this seems to be the same problem. Sebastian Fischer wrote: > Of course, the cause is the black hole. But why is it not reported? I guess the following happens: When the blackhole is detected in the third argument of bracket, the second argument is executed. But for some reason, the handle is already finalized at this point, so hClose raises an exception itself. But bracket reraises the exception from its third argument only if its second argument does not raise an exception itself. So in this case, the "handle is finalized" exception seems to eat the "blackhole" exception. So the question remains: Why is the handle finalized? (And what is "finalizing an handle"?) Tillmann | http://www.haskell.org/pipermail/haskell-cafe/2010-August/081876.html | CC-MAIN-2014-42 | refinedweb | 158 | 65.32 |
#include <sched.h>
sched_rr_get_interval()
writes into the timespec
structure pointed to by
tp the round-robin time quantum
for the process identified by
pid. The specified process
should be running under the
SCHED_RR scheduling policy.
The timespec structure has the following form:
If
pid is zero,
the time quantum for the calling process is written into
*
tp.
On success,
sched_rr_get_interval() returns 0. On
error, −1 is returned, and
errno is set appropriately.
Problem with copying information to user space.
Invalid pid.
The system call is not yet implemented (only on rather old kernels).
Could not find a process with the ID
pid... | http://manpages.courier-mta.org/htmlman2/sched_rr_get_interval.2.html | CC-MAIN-2017-17 | refinedweb | 102 | 67.25 |
Shortcut or menu path to "Rotate to right/left"
I use the “Customize Toolbar” plugin to add favorite commands to the toolbar. One button I’ve added is to split my windows. The way the plugin works, I define the N++ menu path to the command in the Customize Toolbar config file, along with a 16x16 icon to show on the toolbar i.e. “View,Move/Clone Current Document,Move to Other View,split.bmp”.
I now want to add a button to rotate the view between horizontal and vertical. Unfortunately, those commands (“Rotate to right” and “Rotate to left”) are on the window splitter/grabber, not in the main menu structure. Is there a menu path or keyboard shortcut to those two rotate commands that I’ve missed somewhere?
I’m obviously looking for a single-click rotate, instead of a right-click on the grabber followed by a left click on the rotate command.
Unfortunately, looking at the source code, it appears that the splitter-container hardcode-generates those commands, and I don’t think even the plugins communication system has any messages which talk directly with the SplitterContainer’s object. I couldn’t find any menu command ID’s which affect that either (though the move and clone to other view are there).
Without a command ID or main menu position, you cannot record it in a macro. Without a published message ID, you’re not supposed to access those internal messages to manipulate it via a plugin.
However, a clever PythonScript programmer could probably search through the child-windows of the main Notepad++ GUI window, until they found the SplitterContainer object’s HWND, and then SendMessage to that HWND to send a
WM_COMMANDmessage to the SplitterContainer, with the lword as the left and right constants. Not that I would recommend someone do that 😉, since sending unpublished messages to internal hwnd objects is not guaranteed to stay consistently working from one version to the next (which is a risk you take by going beyond the published API).
Very much appreciated. It’s obviously not a major issue, but I wanted to make sure I wasn’t missing something obvious.
- Ekopalypse last edited by Ekopalypse
A python script might look like this
import ctypes ROTATION_A_LEFT = 2000 ROTATION_A_RIGHT = 2001 WM_COMMAND = 0x111 def isSingleView(): npp_hwnd = ctypes.windll.user32.FindWindowW(u'Notepad++', None) splitter_hwnd = ctypes.windll.user32.FindWindowExW(npp_hwnd, None, u'splitterContainer', None) return (not bool(ctypes.windll.user32.IsWindowVisible(splitter_hwnd)), splitter_hwnd) def LOWORD(value): return value & 0xFFFF single_view, hwnd = isSingleView() if not single_view: ctypes.windll.user32.SendMessageW(hwnd, WM_COMMAND, LOWORD(ROTATION_A_LEFT), 0)
@PeterJones - thx - explanation was perfect - I did not even had to check the source :-)
Thank you! I’ve not done Python before, but with such clear code, I figured I’d give it a shot. :) Your code worked perfectly.
Unfortunately, while I can run the script from the menu, when I try to assign it to “Customize Toolbar”, nothing happens when I press the new toolbar button. In case anyone sees something wrong with my last config line below, or knows something about a step I’m missing, I thought I’d post. All of the other commands below work as expected, it’s just that Rotate does nothing when the button is pressed.
Edit,Line Operations,Sort Lines Lexicographically Ascending,sort.bmp
Edit,Line Operations,Remove Consecutive Duplicate Lines,dedup.bmp
Plugins,XML Tools,Pretty print (XML only),xml.bmp
Plugins,JSON Viewer,Format JSON,json.bmp
View,Move/Clone Current Document,Move to Other View,split.bmp
Plugins,Python Script,Scripts,Rotate,rotate.bmp
Thank you again.
I don’t use Customize Toolbar. However, something does jump out at me: the first 5 rows of your config have 3 levels of menu (main menu, submenu, command) followed by the icon/bmp; the last has 4 levels of menu (main, submenu, submenu, command) before the icon/bmp. It may be that Customize Toolbar cannot go that deep (I don’t know).
PythonScript plugin has Plugins > Python Script > Configuration…, which allows you to add a script into the Menu Items list on the left – this is a prerequisite to configuring a Settings > Shortcut Mapper keyboard shortcut to a script, and it might also be necessary for the script to work with Customize Toolbar as well – because if the Rotate script were in the left-hand list, it would show up in Plugins > Python Script > Rotate – which could be accessed using:
Plugins,Python Script,Rotate,rotate.bmp
… which then has the same number of levels as your other commands.
Aside from that, there’s also the right-hand pane in the same Configuration… dialog, which allows you do add a PythonScript script directly into the toolbar (complete with icon) without needing the Customize Toolbar plugin at all.
I don’t know how to explain what happened, but I restarted N++ one more time, and now the button works as expected.
Very odd, as I’d done that a couple of times already. Thanks to everyone for the assistance!
And regarding the same number of levels comment, it appears that tool we’re using to talk decides that back-to-back commas should be displayed as a single comma. In all but the last config line above, there are 2 commas before the .bmp. The second comma just didn’t render in my post.
@VTGroupGitHub said in Shortcut or menu path to "Rotate to right/left":
tool we’re using to talk decides
Yes, it uses markdown format – though I’ve never seen it eat commas before; I guess it depends on what other markdown you’re using.
If you ever want text to come through literally, the best is to highlight the literal then press the
</>toolbar button at the top:
Edit,Line Operations,Sort Lines Lexicographically Ascending,,sort.bmp
- Ekopalypse last edited by
What I think the problem was is that a newly created script hasn’t been assigned
an ID known to npp. This is normally done during plugin initialization where npp
asks for functions to register, hence the restart of npp solved it. | https://community.notepad-plus-plus.org/topic/18615/shortcut-or-menu-path-to-rotate-to-right-left/1?lang=en-US | CC-MAIN-2020-45 | refinedweb | 1,017 | 60.95 |
So I have a tic-tac-toe
board
class Board
attr_accessor :grid
def initialize(grid = Array.new(3, Array.new(3, nil)))
@grid = grid
end
def place_mark(position, symbol)
@grid[position[0]][position[1]] = symbol
end
end
place_mark
board = Board.new
board.place_mark([0,0], :x)
[[:X, nil, nil],
[:X, nil, nil],
[:X, nil, nil]]
[[:X , nil, nil],
[nil, nil, nil],
[nil, nil, nil]]
initialize
def initialize(grid = [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]])
@grid = grid
end
place_mark
The issue is that
Array.new(3, Array.new(3, nil)) gives you an array with the same array in it three times.
It's like doing this:
x = Array.new(3, nil) grid = Array.new(3, x)
So you have an array containing
x three times. You really want three separate arrays that can each have their own values.
Per:
Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.
To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:
Array.new(4) { Hash.new } #=> [{}, {}, {}, {}]
This is also a quick way to build up multi-dimensional arrays:
empty_table = Array.new(3) { Array.new(3) } #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
That last example is exactly what you're looking for. | https://codedump.io/share/0qc8uSsDL2iw/1/ruby-2d-array-assignment | CC-MAIN-2016-50 | refinedweb | 252 | 64.2 |
sqlakeyset: offset-free paging for sqlalchemysqlakeyset: offset-free paging for sqlalchemy
Notice: In accordance with Python 2's rapidly-approaching end-of-life date, we've stopped supporting Python 2. If you really need it, the latest version to support Python 2 is 0.1.1559103842, but you'll miss out on all the latest features and bugfixes from the latest version. You should be upgrading anyway!
This library implements keyset-based paging for SQLAlchemy (both ORM and core).
This library has been tested with PostgreSQL and MariaDB/MySQL. It should work with other SQLAlchemy-supported databases too provided they support
row( syntax (see below).
BackgroundBackground
A lot of people use SQL's
OFFSET syntax to implement paging of query results. The trouble with that is, the more pages you get through, the slower your query gets. Also, if the results you're paging through change frequently, it's possible to skip over or repeat results between pages. Keyset paging avoids these problems: Selecting even the millionth page is as fast as selecting the first.
Getting StartedGetting Started
Here's how it works with a typical ORM query:
from sqlakeyset import get_page from sqlbag import S from models import Book with S('postgresql:///books') as s: # create a session q = s.query(Book).order_by(Book.author, Book.title, Book.id) # # gets the first page page1 = get_page(q, per_page=20) # gets the key for the next page next_page = page1.paging.next # gets the second page page2 = get_page(q, per_page=20, page=next_page) # returning to the first page, getting the key previous_page = page2.paging.previous # the first page again, backwards from the previous page page1 = get_page(q, per_page=20, page=previous_page) # what if new items were added at the start? if page1.paging.has_previous: # go back even further previous_page = page1.paging.previous page1 = get_page(q, per_page=20, page=previous_page)
Under the HoodUnder the Hood
sqlakeyset does the following to your query in order to get the paged contents:
- adds a where clause, to get only rows after the specified row key.
- if getting the previous page, reverses the
order bydirection in order the get the rows before the specified bookmark.
- adds a limit clause, to fetch only enough items to fill the page, plus one additional (this additional row is used only to test for the existence of further pages after the current one, and is discarded from the results).
- returns the page contents as an ordinary list that has an attached
.pagingattribute with the paging information for this and related pages.
Page objectsPage objects
Paged items/rows are returned in a Page object, which is a vanilla python list, except with an attached
Paging object with the paging information.
Properties such as next and previous return a 2-tuple containing the ordering key for the row, and a boolean to specify if the direction is forwards or backwards.
In our above example, the 2-tuple specifying the second page might look like:
('Joseph Heller', 'Catch 22', 123), False
The False means the query will fetch the page after the row containing Catch 22. This tuple contains two elements, title and id, to match the order by clause of the query.
The page before this row would be specified as:
('Joseph Heller', 'Catch 22', 123), True
The first and last pages are fetched with None instead of a tuple, so for the first page (this is also the default if the page parameter is not specified):
None, False
And the last page:
None, True
Keyset SerializationKeyset Serialization
You will probably want to turn these keysets/bookmarks into strings for passing around.
sqlakeyset includes code to do this. To get a serialized bookmark, just add
bookmark_ to the name of the property that holds the keyset you want.
Most commonly you'll want
next and
previous, so:
>>> page.paging.bookmark_previous <i:1~i:2015~s:Bad Blood~i:34 >>> page.paging.bookmark_next >i:1~i:2014~s:Shake It Off~i:31
sqlakeyset uses the python csv row serializer to serialize the bookmark values (using
~ instead of a
, as the separator). Direction is indicated by
> (forwards/next), or
< (backwards/previous) at the start of the string.
LimitationsLimitations
- Golden Rule: Always ensure your keysets are unique per row. If you violate this condition you risk skipped rows and other nasty problems. The simplest way to do this is to always include your primary key column(s) at the end of your ordering columns.
- Any rows containing null values in their keysets will be omitted from the results, so your ordering columns should be
NOT NULL. (This is a consequence of the fact that comparisons against
NULLare always false in SQL.) This may change in the future if we work out an alternative implementation; but for now we recommend using
coalesceas a workaround:
from sqlakeyset import get_page from sqlalchemy import func from sqlbag import S from models import Book with S('postgresql:///books') as s: # If Book.cost can be NULL: q = s.query(Book).order_by(func.coalesce(Book.cost, 0), Book.id) # page1 will start with books where cost is null: page1 = get_page(q, per_page=20)
- If you're using the in-built keyset serialization, this only handles basic data/column types so far (strings, ints, floats, datetimes, dates, booleans, and a few others). The serialization can be extended to serialize more advanced types as necessary (documentation on this is forthcoming).
DocumentationDocumentation
sqlakeyset is in early alpha and documentation other than this README is scarce so far. We are working on remedying this. Watch this space.
InstallationInstallation
Assuming you have pip installed, all you need to do is install as follows:
$ pip install sqlakeyset
This will install sqlakeyset and also sqlalchemy if not already installed. Obviously you'll need the necessary database driver for your chosen database to be installed also. | https://reposhub.com/python/orm/djrobstep-sqlakeyset.html | CC-MAIN-2021-39 | refinedweb | 967 | 52.49 |
[
]
Brian Foster commented on OODT-296:
-----------------------------------
>
>
> Internally at JPL, we built a Workflow 2 GUI (thanks [~bfoster]!) :-) I'm working on
preparing a patch to port it from the old internal JPL workflow manager (wengine) code to
Apache OODT. I'll use this patch to track the progress. I need to migrate:
> * namespaces from g.j.n.oodt to o.a.oodt
> * use of jgraph library to
> * some old deps on wengine-branch internal to JPL
> I'll attach a screenshot to show what it looks like (and will look like) shortly.
--
This message is automatically generated by JIRA.
For more information on JIRA, see: | http://mail-archives.apache.org/mod_mbox/oodt-commits/201107.mbox/%3C1264240658.3960.1310416740120.JavaMail.tomcat@hel.zones.apache.org%3E | CC-MAIN-2020-10 | refinedweb | 105 | 76.32 |
The call to SendResponseString will simply write the value of out (S1, S2, etc...) to the outbound or response mailbox numbered 11. Response mailboxes have numbers equal to the specified mailbox number plus 10. You actually have to pass the response mailbox number (i.e., 10..19) rather than the "regular" mailbox number (0..9), unless Mindsquals is doing something weird and adding 10 to the number you pass in (which it should not do).On the NXT side I stuck with the code I mentioned in my previous post (page 43 of Daniele Benedettelli's tutorial at bricxcc site):
//SLAVE #define BT_CONN 1 #define INBOX 5 #define OUTBOX 1 task main(){ string in, out, iStr; int i = 0; while(true){ iStr = NumToStr(i); out = StrCat("S",iStr); ReceiveRemoteString(INBOX, true, in); SendResponseString(OUTBOX,out); TextOut(10,LCD_LINE3,in); TextOut(10,LCD_LINE5,out); Wait(100); i++; } }
On the PC side I wrote something really simple (please note that I am using this code only as a rough example, it is by no means 100% functional, large sections were left out):
using NKH.MindSqualls; namespace BTMasterMessage { public partial class Form1 : Form { ............................ private void GetMessage() { byte comPort = byte.Parse(this.txtComPort.Text); NxtCommunicationProtocol comm = new NxtBluetoothConnection(comPort); comm.Connect(); string msg = comm.MessageRead(NxtMailbox2.Box1, NxtMailbox.Box0, true); this.Text = msg; } } }
Well, nothing worked, there was no message displayed PC side. Then I read more closely what John mentioned in his answer and I decided to change the first argument of MessageRead from Box1 to Box11:
string msg = comm.MessageRead(NxtMailbox2.Box11, NxtMailbox.Box0, true);
It was a magical moment when I ran the program and I got an "S173" or something like it on my screen. It was so awesome!
The conclusion: MindSqualls rocks and the helpful and friendly people in the NXTasy forum do as well! Big thanks to both teams! | http://mynxting.blogspot.com/2010/04/ | CC-MAIN-2018-22 | refinedweb | 311 | 64.41 |
I have a program that randomly flips a quarter 100 times. The results gives me a list of heads and tails. I need the results to look like this:
100 Flips resulted in 49 heads and 51 tails. With varing numbers for heads and tails.
Thank you for any help given.
I have two sets of Classes the first is FlipResult and the second is Driver. Here they are:
//FlipResult Class import java.awt.BufferCapabilities.FlipContents; public class FlipResult { Quarter quarter; public FlipResult(){ quarter = new Quarter(); } public void run(){ for(int j = 0; j < 100; j++){ quarter.flip(); System.out.println(quarter.isHeads()? "heads" : "tails"); } } } //Driver Class public class Driver { public static void main(String[] args) { System.out.println("100 flips resulted in" ); FlipResult tf = new FlipResult(); tf.run(); } } | https://www.daniweb.com/programming/software-development/threads/352971/java-help-request | CC-MAIN-2017-30 | refinedweb | 129 | 68.26 |
Gravity Forms is hands down the best contact form plugin for WordPress. Gravity Forms WordPress Plugin allows you to quickly build and design your WordPress forms using the form editor. You just need to select your fields, configure your options, and easily embed forms on your WordPress powered site using the built in tools.
Although Gravity Forms have tons of features but it lacks one basic thing and that is the client side validation. It does not provide JavaScript validation from the admin panel options. It does provide server side validation which is good but in this day and age of jQuery, you do want to warn users up front and ask them to fill the form properly. Not just that it does not provide the js validation, Gravity Forms plugin also does not allow you to place any js code at form level designing.
Worse, they don’t have anything on their website community, and mind you it’s not easy to access that info anyway. Only members and those who have provided their licensed key can get access and read those important bits which should be easily available to all IMO. Eveen after providng all that info, I still could not find solution and then i was forced to do soemthign on my own.
here;s what I did and could manage to do Gravity Forms client side validation using jQuery.
First of all, include jQuery library to your head like this:
After you have created and placed your Gravity Form on your blog, get it’s id and it;s submit button id. If it’s your first form, chances are that it’s id is “gform_1” and submit button id is “gform_submit_button_1”. Place following code inside your WordPress blog head tag, although you can add it anywhere in the page:
The above code will call the form validator function where you can put all your logic. Here’s a sample function that will allow you to check different fields, add this into your page anywhere:
With this client side validation using jQuery, you can now control everything and easily create forms in WordPress. There’s no better forum Plugin available for WordPress than Gravity Forms.
Hope that helps.
Cheers!
4 Comments
Works for me with —
1) made the function name match
2) used ‘jQuery(document).ready(function($) {‘ rather than ‘$(document).ready(function($) {‘
3) added the ‘if’ in for Form.input_1 check
jQuery(document).ready(function($) {
$(“#gform_submit_button_4”).click(function() {
return FormContact_Validator(gform_4);
});
});
function FormContact_Validator(Form){
if (Form.input_1.value == “”){
alert(“Please enter your First Name”);
Form.input_1.focus();
return (false);
}
if (Form.input_2.value == “”){
alert(“Please enter your Last Name”);
Form.input_2.focus();
return (false);
}
if (Form.input_3.value == “”){
alert(“Please enter your Message.”);
Form.input_3.focus();
return (false);
}
}
After reading this post I’m thinking you may help me. Hope so!
I’ve been using Visual Form Builder Pro for a long time now but I have a different need. I need to have a field where the user should insert an associate number. That number is property of an external client. So, the webservice has to validate with the external client if that number is valid on their system. When pressing the “submit” button, it has to call that webservice. Depending on the response of the webservice (validating or not the associate number) the form will be submited or not. I asked the plugins’ developer for help and the answer was “my requirements are outside the scoop of what Visual Form Builder Pro can provide”.
SO, can you help me with this plugin or do you have an idea of how can I build forms in another way / with another plugin/ etc so I can use a webservice with it??? And how??
Thank you!
Hi Joana,
Firs of all, that was a very bad response from the plugin developer for number of reasons, 1) they could add this feature in their plugin 2) they could charge you for the feature.
Yes I can help.. You need a new plugin, that plugin will call the third party API and respond to your form and validate the number based on the response received form the API. Form will call the plugin via AJAX and this is show it will be done. but anyway..
It depends how much work is this, but let me know and I will check the details and respond with a quote.
Hi,
thank for this code, and this what I want, but what about captcha validation, yes we can check blank captcha field validation but what about if the user enter wrong captcha.
any help for this.
thanks. | https://www.parorrey.com/blog/front-end-development/wordpress-gravity-forms-validation-on-client-side-using-jquery/ | CC-MAIN-2019-26 | refinedweb | 775 | 71.04 |
Trying to simply compile a java program843810 Sep 16, 2009 11:43 PM
Downloaded JDK 6 Update 16 with Java EE ( java_ee_sdk-5_07-jdk-6u16-windows.exe) the entire 161 megs. Does this have the javac.exe? I don't believe it does. If not then which download?
Thanks
Thanks
This content has been marked as final. Show 13 replies
1. Re: Trying to simply compile a java program843810 Sep 16, 2009 11:50 PM (in response to 843810)Oh I forgot to mention, here's the message I keep getting, I also am running under vista if that makes any difference.
--------------------Configuration: Program0201 - <Default> - <Default>--------------------
Error : Invalid path, \bin\javac.exe -source 1.5 -classpath "C:\Program Files\Xinox Software\JCreatorV4\MyProjects\Program0201" -d C:\Program" Files\Xinox "Software\JCreatorV4\MyProjects\Program0201 @src_program0201.txt"
Process completed.
2. Re: Trying to simply compile a java programEJP Sep 17, 2009 12:02 AM (in response to 843810)
Downloaded JDK 6 Update 16 with Java EE ( java_ee_sdk-5_07-jdk-6u16-windows.exe) the entire 161 megs. Does this have the javac.exe?All JDKs have the java compiler.
I don't believe it does.The bizarre error message you posted doesn't suggest that. It suggests you are running a bizarre command line somehow.
3. Re: Trying to simply compile a java program843810 Sep 17, 2009 12:48 AM (in response to EJP)If so then where is javac.exe? Also I am using JCreator to compile. I installed JCreator from a cd that was supplied with the book I purchased, Java for Dummies. I apoligize if I have solicited in the wrong forum but I tried the java for beginners forum and tried every suggestion and failed.
Thanks
4. Re: Trying to simply compile a java programEJP Sep 17, 2009 1:57 AM (in response to 843810)javac.exe is in $JDK_HOME/bin where JDK_HOME is where the installer put the JDK.
I can't comment on JCreator or where it expects to find things or how it constructs command lines but that one is completely wrong.
5. Re: Trying to simply compile a java program843810 Sep 17, 2009 5:34 AM (in response to EJP)The installation put JDK_HOME in C:\Sun\SDK. But there is no javac.exe in C:\Sun\SDK\bin.
This is quite a mystery.
6. Re: Trying to simply compile a java program843810 Sep 17, 2009 10:20 AM (in response to 843810)
kendem wrote:Installation? What installation? The Sun JDK or JCreator?
The installation put JDK_HOME in C:\Sun\SDK.
If you are talking about the JCreator installation, try the JCreator forum.
7. Re: Trying to simply compile a java program796447 Sep 17, 2009 1:39 PM (in response to 843810)NOTE: This was crossposted so people are wasting their time on this guy.
8. Re: Trying to simply compile a java program843810 Sep 17, 2009 3:13 PM (in response to 796447)warnerja;
I didn't know I was supposted to keep to one forum for help, I didn't see that rule anywhere. Is this forum for advanced users of Java? If so then should I not post here anymore? Otherwise I have another different question on compiling or should I post a new message for that? The question is why is access denied in the following message? I set access permissions on all files/directories but still get the Access is denied.
Thanks
--------------------Configuration: Program0201 - JDK version <Default> - <Default>--------------------
C:\Program Files\Xinox Software\JCreatorV4LE\MyProjects\Program0201\MortgageText.java:4: error while writing MortgageText: C:\Program Files\Xinox Software\JCreatorV4LE\MyProjects\Program0201\MortgageText.class (Access is denied)
public class MortgageText {
^
1 error
9. Re: Trying to simply compile a java program796447 Sep 17, 2009 4:06 PM (in response to 843810)The point was to alert other people who may be answering, that they should check the other place(s) to see if they are about to waste their time duplicating what has already been said. Too late though, the time wasting already happened!
And that it is rude for you to crosspost, at least without providing link(s) to the other conversation(s), for the reason mentioned above. That should just be obvious.
10. Re: Trying to simply compile a java program843810 Sep 17, 2009 4:52 PM (in response to 796447)Hey warnerja,
Just trying to learn Java and brand new to these forums. Unforgiving bunch here. Good bye.
11. Re: Trying to simply compile a java program796447 Sep 17, 2009 8:42 PM (in response to 843810)Am I supposed to grieve your loss?
If you come to a place looking for help, and someone corrects your abuse of netiquette and you run away in a huff, believe me nobody in the forum loses anything. Only you do.
Stay, go - no skin off my nose.
12. Re: Trying to simply compile a java program830056 Jan 11, 2011 2:48 AM (in response to 796447)Hello all,
I have just read this forum and l hope l am not doing the wrong thing but l am having the same issue.
I am just working through Java for Dummies....don't laugh..working with window 7 and the jcreator provided and l am getting a very simlar issue as metioned above. can somebody please help or point me to a form that would be able to gide me.
Cheers.
Error message is when l try to compile:
error while writing MortgageText: C:\Program Files (x86)\Xinox Software\JCreatorV4LE\MyProjects\Program0201\MortgageText.class (Access is denied)
13. Re: Trying to simply compile a java programdarrylburke Jan 11, 2011 7:54 AM (in response to 830056)Moderator advice: Please don't post to threads which are long dead, and don't hijack another poster's thread. When you have a question, start your own thread. Feel free to post a link to a related thread.
Moderator action: Locking this thread.
db | https://community.oracle.com/message/6362071 | CC-MAIN-2016-40 | refinedweb | 989 | 65.93 |
Robert A. Wlodarczyk's Blog (MSFT)adventures with the Windows Imaging Component Evolution Platform Developer Build (Build: 5.6.50428.7875)2006-10-27T14:36:00ZNew blog home!<p>Since Windows 7 shipped, I am no longer working on the team delivering the Windows Imaging Component. I'm working on some different areas within Windows. Also, I have started my own blog, <a title="SimplicityGuy" href="">SimplicityGuy</a>, where I plan to cover projects that I work in outside of work.</p> <p>This will be the last post to the blog here. All future posts will be at <a title="SimplicityGuy" href="">SimplicityGuy</a>.</p><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk few updates and links<P>Some folks have been inquiring about the sampel code that I had on my blog. Since my web host was changed and the content was lost, I've moved the code to CodePlex. I've pruned the samples, and <A href="" mce_href="">made them availabled here</A>. What's included:</P> <UL> <LI>Converting WPF BitmapSource <-> GDI+ Bitmap</LI> <LI>Metadata Walker</LI> <LI>Using WPF InPlaceBitmapMetadataWriter</LI></UL> <P>Also, the code for WICExplorer and WICCop are available from MSDN. <A href="" mce_href="">They are available here</A>. What's included:</P> <UL> <LI>WICExplorer: Base bones metadata and image viewer built using WIC</LI> <LI>WICCop: Tool used to verify that the WIC CODEC Guidelines have been properly implemented. Also includes C# COM Interop interface definitions for WIC.</LI></UL><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk to other blogs...<P>Just last week, the <A href="" mce_href="">DirectX blog</A> has gone live!</P> <P>From now on, any posts about WIC will be placed on the DirectX blog. Questions about WIC will continue to be answered in the <A href="" mce_href="">WIC Forums</A> on MSDN.</P> <P.</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Working Group 1.01 Spec Published<P>Just today the <A href="" mce_href="">Metadata Working Group posted the version 1.01 of their guidance</A>. There are a few changes:</P> <UL> <LI>clarification around location</LI> <LI>removal of Exif UserComment from the "Description" guidance</LI> <LI>clarification around "Date/Time"</LI> <LI>addition of "Implementation Notes" section</LI></UL> <P mce_keep="true"> </P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk in Windows 7 Pre-Beta<p></p> <p:</p> <ul> <li>Enhanced metadata support</li> <ul> <li>GIF: </li> <ul> <li>Metadata handlers exposed, enabling developers to gain access to the animation information. These include Logical Screen Descriptor (LSD), Image Descriptor (IMD), Graphic Control Extensions (GCE), Application Extensions (APE), Comment.</li> </ul> <li>PNG: </li> <ul> <li>New metadata handlers added, including iTXT, gAMA, bKGD, cHRM, iCCP, sRGB, tIME.</li> </ul> <li>JPEG: </li> <ul> <li>New metadata handlers added, including Comments, Chrominance, Luminance.</li> <li>Ability to read spanned APP13 blocks.</li> </ul> <li>Existing metadata handlers:</li> <ul> <li>Many bug fixes!</li> </ul> </ul> <li>Enhanced TIFF support</li> <ul> <li>Support for tiled, planar, and JPEG compressed TIFFs</li> </ul> <li>Cross-apartment and MTA support.</li> <li>IWICPixelFormatInfo2</li> <ul> <li>Adds information about transparency and numeric representation of the pixel format.</li> </ul> <li>IWICProgressiveLevelControl</li> <ul> <li>This allows developers to gain access to an image's progressive levels.</li> <li>Supports on GIF, PNG, and JPEG.</li> </ul> <li>Additional Pixel Formats, including ones for high color</li> </ul> <p>If you have any questions about WIC on Windows 7, please feel free to either <a href="mailto:codecs@microsoft.com">email us</a> or <a href="">visit the forums</a>.</p><img src="" width="1" height="1">Robert A. Wlodarczyk Working Group<p <a href="">endorsed the efforts from the Metadata Working Group</a>.</p> <p>The specification produced by the Metadata Working Group is available from <a href="">the website</a>. It outlines the goals as well as details how each of the fields should be used in order to ensure maximum compatibility among applications that adhere to this specification. </p> <p>For more details on the Metadata Working Group, <a href="">check out the website</a>.</p><img src="" width="1" height="1">Robert A. Wlodarczyk Tools now available!<P>The following WIC Tools are now available from the Microsoft Download Center... with source code!</P> <UL> <LI>WICGrinder (updated!)</LI> <LI>WICExplorer</LI> <LI>Sample CODEC, metadata handler, pixel formats</LI></UL> <P><A title="WIC Tools" href="" mce_href="">Click here to download the code!</A> <A href="" mce_href="">Also here.</A></P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Forum, it's finally happened... we've created a <A class="" href="" mce_href="">WIC Forum</A> on the MSDN Forums page. So, if you have any questions about WIC, please <A class="" href="" mce_href="">post them there</A>. Enjoy!<div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk WPF's InPlaceBitmapMetadataWriter<P>Many.</P> <P>If you've struggled with the InPlaceBitmapMetadataWriter and want to get the sample... <A title="Using InPlaceBitmapMetadataWriter" href="" mce_href="">grab it from here</A>.</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Pro Photo Summit 2007<P mce_keep="true">Last week was the Microsoft Pro Photo Summit. Below are links to some coverage from the event:</P> <BLOCKQUOTE> <P>PopPhoto <A class="" href="" mce_href="">(1)</A>, <A class="" href="" mce_href="">(2)</A></P> <P><A class="" href="" mce_href="">Blurberati</A></P> <P><A class="" href="" mce_href="">Photo Business Forum</A></P> <P>Dispatches <A class="" href="" mce_href="">(1)</A>, <A class="" href="" mce_href="">(2)</A>, <A class="" href="" mce_href="">(3)</A>, <A class="" href="" mce_href="">(4)</A></P></BLOCKQUOTE><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Conference the recent <A class="" href="" mce_href="">Photo Metadata Conference</A>, Josh Weisberg from Microsoft represented WIC there. <A class="" href="" mce_href="">Here's some coverage...</A> and <A class="" href="" mce_href="">some more...</A><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk now knows about WIC<P>It's great to see that now <A class="" title=WikipediaWikipedia knows something about WIC</A>. :)</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Photo Beta Plugin for Adobe Photoshop you been eye-ing the new HD Photo format? Are you an avid user of Adobe's Photoshop? Well, now you can give HD Photo a whirl in Photoshop CS2 (or the CS3 beta). <A class="" title="HD Photo Plugin for Adobe Photoshop" href="" mce_href="">Download the HD Photo Plugin for Adobe Photoshop</A>.<div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk from MSR<P>Just announced at <A class="" title="Techfest 2007" href="" mce_href="">MSR Techfest</A> yesterday... Ever wonder how you view gigapixel images? Or how do you even go about creating gigapixel images using somewhat commodity equipment? MSR just released a tool that's built on the WIC APIs and uses HD Photo as its backing store. <A class="" title="HD View" href="" mce_href="">Check out their website</A>.</P> <UL> <LI> <DIV mce_keep="true"><A class="" title="HD View - How Done?" href="" mce_href="">Equipment and methodologies used</A></DIV></LI> <LI> <DIV mce_keep="true"><A class="" title="HD View - Make Your Own" href="" mce_href="">Make your own HD photos</A></DIV></LI></UL> <P mce_keep="true">Enjoy!</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Color Profile Posted those of you using CMYK images in your workflow using WIC, you'll want to download the <A class="" title=CMYKCMYK profile that was posted a few days ago</A>. Enjoy.<div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Tiësto & Windows Vista<P>Some of you who know me better know that I'm a huge DJ Tiësto fan... even before he was vote #1 DJ in the world. Having been a bad fan lately and not checking out the <A class="" title="DJ Tiësto" href="" mce_href="">fan website</A>, <A class="" title="DJ Tiësto & Windows Vista" href="" mce_href="">here's the direct link</A>.</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk FAQ<P>Today the FAQ about PhotoInfo was posted. <A class="" title="PhotoInfo FAQ" href="" mce_href="">Check it out here.</A> Of interest it talks about how to read the Maker Note data once a file was edited using WIC.</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk PhotoInfo Released you're looking to add IPTC and other pieces of metadata from Windows Explorer, Microsoft PhotoInfo is the tool for you! <A class="" title=PhotoInfoCheck it out</A>.<div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk BitmapSource and GDI+ Bitmap Interop<P>Many folks in the forums (<A href="" mce_href="">most recent post</A>).</P> <P>I've put the <A title="BitmapSource <-> Bitmap Sample" href="" mce_href="">code here</A>. Enjoy!</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk 1.0 is released!<P>The WIC package installer is now available on MSDN:</P> <P>x86: <A href=""></A></P> <P>x64: <A href=""></A></P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk to give PhotoSynth a try?'s a tech preview of PhotoSynth available! <A class="" href="" mce_href="">Go check it out!</A><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Updated<P>After the <A class="" href="" mce_href="">initial release of WICGrinder</A> almost 2 weeks ago, we have added metadata tests in. Also, we addressed some bugs within the pre-existing tests.</P> <P>Please pick up an update copy of WICGrinder here: <A class="" href="" mce_href="">WICGrinder (x86)</A>; <A class="" href="" mce_href="">WICGrinder (x64)</A></P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Fx 3.0 RTM is out!<P>.NET Framework 3.0 RTM'd! Go <A class="" href="" mce_href="">download it</A>! If you want the SDK, <A class="" href="" mce_href="">here it is</A>.</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk Verifier & WICGrinder<P>In the <A class="" title=WICGrinderprevious post about WICGrinder</A>,. </P> <P><A class="" title="AppVerifier Download Link" href="" mce_href="">Download AppVerifier now</A>.</P> <P>Have fun!</P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk you wrote a WIC enabled CODEC... Does it work?<P>After reading this blog, <A class="" href="" target=_blankPeggi's whitepaper</A>, and the <A class="" href="" target=_blankMSDN Documentation</A>, you decided to write a CODEC for an image file type. The CODEC was even tested in <A class="" href="" target=_blankWICExplorer</A>.?</P> <P>My team has given some serious thought to this. In order to help facilitate in this task, we've come up with a tool called WICGrinder. To use the tool, you:</P> <OL> <LI>create a new script</LI> <LI>enter in your CODEC's GUIDs for the container format, decoder, and encoder (if supported)</LI> <LI>provide sample images for your CODEC</LI></OL> <P>After this you run the script and a verbose output of your CODEC's capabilities is outputted. Tests that are included are those that specifically check for items pointed out in <A class="" href="" mce_href="">Peggi's whitepaper</A>. If WICGrinder crashes, you may run it under a debugger with a debug build of your CODEC to determine what caused it to crash. A complete readme is included in the zip download.</P> <P>In order to run this, you should have the latest Windows Vista build installed (RC1 or greater). If you have any questions about the tool, please email <A href="mailto:wictools@microsoft.com">wictools@microsoft.com</A>. Also, if you have any questions about WIC in general, please email <A href="mailto:wiccodec@microsoft.com">wiccodec@microsoft.com</A>. </P> <P>Download it today: WICGrinder [Update 2006.11.10... please use the updated version: <A class="" href="" mce_href="">WICGrinder (x86)</A>; <A class="" href="" mce_href="">WICGrinder (x64)</A>]</P> <P><SPAN style="FONT-SIZE: 8pt; FONT-FAMILY: 'Arial','sans-serif'">.)<?xml:namespace prefix = o<o:p></o:p></SPAN></P><div style="clear:both;"></div><img src="" width="1" height="1">Robert A. Wlodarczyk | http://blogs.msdn.com/b/rwlodarc/atom.aspx | CC-MAIN-2014-42 | refinedweb | 2,142 | 59.3 |
28 June 2012 14:19 [Source: ICIS news]
LONDON (ICIS)--UBS has lowered its target share price for UK-based specialty chemicals firm Yule Catto to £1.77 (€2.21, $2.77) from £2.60, following the company’s bleak trading outlook, the investment bank said on Thursday.
On Wednesday, Yule Catto released a trading update which said it is expecting a £5m drop in operating profits due to falling demand and continued economic uncertainty.
“The challenging trading conditions outlined at the time of the group's May interim management statement have continued through the remainder of the first half of the year,” said Yule Catto.
The company added that in its Europe and ?xml:namespace>
“Demand is currently a little weaker than the first few months of the year, with business in the construction-related sector continuing to be the weakest area of activity,” the company said.
UBS said that trading in nitrile butadiene rubber (NBR) in
In its trading statement, Yule Catto said weakness in end-market demand for NBR is continuing.
“This, combined with the effect of recent capacity additions has led to increasingly aggressive competitor pricing and a further weakening of profitability in nitrile. Additional competitive capacity is also due on stream during the course of the summer,” the company said.
At 12:40 GMT, Yule Catto’s shares were trading at £1.36 on the London Stock Exchange, down 1.45% on the previous close.
(€1 = £0.80, $1 = £ | http://www.icis.com/Articles/2012/06/28/9573678/ubs-lowers-its-target-share-price-for-uks-yule-catto.html | CC-MAIN-2015-18 | refinedweb | 244 | 53.71 |
How to Run an API Test within a Web Test
In some cases you may need to combine a Test Studio web test with an API test. For example, if your application under test interacts with a service (e.g. creates a user in a web interface that gets stored in a database) and you want to verify directly against that interface that your new user is correctly created.
Tip
Test Studio gives the option for running API tests as steps from a web test out-of-the-box.
To achieve that with Test Studio you will need to create a Test Studio for APIs project and create a test that performs the necessary requests and verifications.
The next step is to create a coded step in the web test that will start a system process. The following code will run the Telerik.ApiTesting.Runner.exe with the
test command and the following arguments:
- the path to the API test project (
-p C:\ApiTests\DemoTests)
- the test inside this project that needs to be executed (
-t "".\Get User Id By Its Username"")
You can read more about running API tests with Test Studio for APIs command line from here
The code will wait for the end of the API test execution. After the process ends - the exit code is placed in assert statement to check if this step passed or failed depending on the API test status.
Hint: in a default installation, the path to the executable Telerik.ApiTesting.Runner.exe is: "C:\Program Files (x86)\Progress\Test Studio\Bin\ApiTesting\runnerconsole\Telerik.ApiTesting.Runner.exe"
// Have to include the references: using System.Diagnostics; [CodedStep(@"Run Api Test")] public void Run_Api_Test_CodedStep() { // initialize new system process Process runApiTest = new Process(); // define the process name to be started runApiTest.StartInfo.FileName = @"[PathToExecutable]\Telerik.ApiTesting.Runner.exe"; // set the arguments runApiTest.StartInfo.Arguments = @"test -p [PathToTheTestProject]\DemoTests -t "".\Get User Id By Its Username"""; // run the process runApiTest.Start(); // wait until the test return an exit code runApiTest.WaitForExit(); // get the exit code from the executed process int exitCode = runApiTest.ExitCode; // check if this test step pass or fail. If return 0 - process complete normally, else - process fould. Assert.AreEqual(exitCode, 0); }
Imports System.Diagnostics <CodedStep("Run Api Test")> _ Public Sub Run_Api_Test_CodedStep() Dim runApiTest As New Process() runApiTest.StartInfo.FileName = "[PathToExecutable]\Telerik.ApiTesting.Runner.exe" runApiTest.StartInfo.Arguments = "test -p [PathToTheTestProject]\DemoTests -t "".\Get User Id By Its Username""" runApiTest.Start() runApiTest.WaitForExit() Dim exitCode As Integer = runApiTest.ExitCode Assert.AreEqual(exitCode, 0) End Sub
Advanced: Passing a Variable from an API Test to a Web Test
Sometimes you may need to get a variable that is acquired by your API test and use it into your web test. (For example if you want to create a user first via a REST service and than use his user ID to perform an action in your web test.)
Tip
Test Studio gives the option for passing variables from the web test to the embedded API test and vice versa out-of-the-box.
Test Studio for APIs stores runtime variables in a ".variables" directory inside the root of the test project being executed. The files in that folder are usually consumed only by the user interface of Test Studio for APIs. This is why by default, if you run your tests via command line, the ".variables" folder will not be generated. In order to generate it when running tests, you need to add an additional parameter to your execution command:
--save-contexts. For example, to run a single test in a test project and generate .variables, you can use a command like:
C:\>"C:\Program Files (x86)\Progress\Test Studio for APIs\Bin\ApiTesting\runnerconsole\Telerik.ApiTesting.Runner.exe" test -p "C:\ApiTests\DemoTests" -t ".\CRUD Tests\Get All Users" --save-contexts
Inside the ".variables" folder, Test Studio for APIs generates a separate file for each executed test (with a file name like:
my-test-name.variables) and an additional "root" file for project-level variables, called ".global.variables".
Every time you use a Set Variable step in an API test, its value gets stored in the .variables file for the respective test.
The easiest way to transfer any value from an API test to a web test is to store it with a Set Variable step in Test Studio for APIs and extract it from the .variables file later in a coded step in your web test.
To achieve that you can:
- Create a web test in Test Studio.
Use the coded step described above to run your API test, but add
--save-contextsto your arguments - e.g.:
runApiTest.StartInfo.Arguments = "test -p [PathToTheTestProject]\DemoTests -t "".\Get User Id By Its Username""" --save-contexts
Add another coded step after that, that will read the .variables file for your test and extract the desired variable:
// Have to include the references: using System.IO; using Newtonsoft.Json.Linq; [CodedStep(@"Get Variable from Api Test")] public void Get_Variable_from_Api_Test_CodedStep() { string path = @"[PathToTheTestProject]\TestStudioTest\.variables\Test Case.variables"; string json = string.Empty; using (StreamReader reader = new StreamReader(path)) { json = reader.ReadToEnd(); } var result = JToken.Parse(json); // Select the desired value from the json. // In this example ".\\Test Case" is the path to the test case // and "user-email" is the name of the variable stored by the API test string email = result["scopes"][".\\Test Case"]["variables"]["user-email"].ToString(); // Store the email to an extracted variable which can be used in a UI step or another coded step SetExtractedValue("extractedEmail", email); }
Imports System.IO Imports Newtonsoft.Json.Linq <CodedStep("Get Variable from Api Test")> _ Public Sub Get_Variable_from_Api_Test_CodedStep() Dim path As String = "C:\tmp\TestStudioTest\.variables\Test Case.variables" Dim json As String = String.Empty Using reader As New StreamReader(path) json = reader.ReadToEnd() End Using Dim result = JToken.Parse(json) Dim email As String = result("scopes")(".\Test Case")("variables")("user-email").ToString() SetExtractedValue("extractedEmail", email) End Sub
Note: .variables files contain text in json format. An easy way to extract a particular value from them is if you parse the file using Json.NET. Test Studio already uses Json.NET so its .dll file (Newtonsoft.Json.dll) is available in the Bin folder of the Test Studio installation folder. In order to add
using Newtonsoft.Json.Linq; to your coded step, you need to add an assembly reference to Newtonsoft.Json.dll as described here
The code snippet saves the extracted value to a variable in the web test. See here for more information.
Once extracted, the variable can be used as described here | https://docs.telerik.com/teststudio/knowledge-base/test-execution-kb/run-api-test-in-web-test | CC-MAIN-2022-40 | refinedweb | 1,098 | 58.79 |
I want your help with an exercise in C. Well, it gives us the piece of code(i've posted it below) and it telling us :
Watch the output for input 4,4. Do the same with 3, 4. Explain if the behavior of your program seems logic or if you observe something strange. And what is that. Also, explain how you can fix the problem that is presented, so that it has right output.
In this part of the code :
res = (--i == 3) || (j++ == 7);i know that if the first condition is true, then res is set to true and it doesn't check the second condition. But i can't figure out what i have to do. Can you help me?
#include <stdio.h> int main( void ) { int i, j; int res; scanf("%d", &i); scanf("%d", &j); res = (--i == 3) || (j++ == 7); printf("%d\n", i); printf("%d\n", j); printf("%d\n", res); } | https://www.dreamincode.net/forums/topic/256438-help-with-an-exercise-in-c/ | CC-MAIN-2018-51 | refinedweb | 158 | 90.8 |
T_FREE(3N) T_FREE(3N)
NAME
t_free - free a library structure
SYNOPSIS
#include <<tiuser.h>>
int t_free(ptr, struct_type)
char *ptr;
int struct_type;
DESCRIPTION
t_free() frees memory previously allocated by t_alloc(3N). This func-
tion will free memory for the specified structure, and will also free
memory for buffers referenced by the structure.
ptr points to one of the six structure types described for t_alloc(3N),
and struct_type identifies the type of that structure which can is used as an argument to one or more
transport functions.
t_free() checks the addr, opt, and udata fields of the given structure
(as appropriate), and frees the buffers pointed to by the buf field of
the netbuf (see intro(3)) structure. The maxlen, len, and buf members
of the netbuf structure are described in t_accept(3N). If buf is NULL,
t_free() will not attempt to free memory. After all buffers are freed,
t_free() will free the memory associated with the structure pointed to
by ptr.
Undefined results will occur if ptr or any of the buf pointers points
to a block of memory that was not previously allocated by t_alloc(3N).
RETURN VALUES
t_free() returns:
0 on success.
-1 on failure and sets t_errno to indicate the error.
ERRORS
TSYSERR The function failed due to a system error and set errno
to indicate the error.
SEE ALSO
intro(3), t_alloc(3N)
21 January 1990 T_FREE(3N) | http://modman.unixdev.net/?sektion=3&page=t_free&manpath=SunOS-4.1.3 | CC-MAIN-2017-30 | refinedweb | 232 | 62.78 |
Uber Go Style Guide
Table of Contents
- Introduction
- Guidelines
- Performance
- Style
- Group Similar Declarations
- Import Group Ordering
- Package Names
- Function Names
- Import Aliasing
- Function Grouping and Ordering
- Reduce Nesting
- Unnecessary Else
- Top-level Variable Declarations
- Prefix Unexported Globals with _
- Embedding in Structs
- Use Field Names to initialize Structs
- Local Variable Declarations
- nil is a valid slice
- Reduce Scope of Variables
- Avoid Naked Parameters
- Use Raw String Literals to Avoid Escaping
- Initializing Struct References
- Format Strings outside Printf
- Naming Printf-style Functions
- Patterns
Introduction
Styles are the conventions that govern our code. The term style is a bit of a
misnomer, since these conventions cover far more than just source file
formatting—gofmt handles that for us.
The goal of this guide is to manage this complexity by describing in detail the
Dos and Don’ts of writing Go code at Uber. These rules exist to keep the code
base manageable while still allowing engineers to use Go language features
productively.
This guide was originally created by Prashant Varanasi and Simon Newton as
a way to bring some colleagues up to speed with using Go. Over the years it has
been amended based on feedback from others.
This documents idiomatic conventions in Go code that we follow at Uber. A lot
of these are general guidelines for Go, while others extend upon external
resources:
All code should be error-free when run through
golint and
go vet. We
recommend setting up your editor to:
- Run
goimportson save
- Run
golintand
go vetto check for errors
You can find information in editor support for Go tools here:
Guidelines
Pointers to Interfaces
You almost never need a pointer to an interface. You should be passing
interfaces as values—the underlying data can still be a pointer.
An interface is two fields:
- A pointer to some type-specific information. You can think of this as
“type.”
- Data pointer. If the data stored is a pointer, it’s stored directly. If
the data stored is a value, then a pointer to the value is stored.
If you want interface methods to modify the underlying data, you must use a
pointer.
Receivers and Interfaces
Methods with value receivers can be called on pointers as well as values.
For example,
type S struct { data string } func (s S) Read() string { return s.data } func (s *S) Write(str string) { s.data = str } sVals := map[int]S{1: {"A"}} // You can only call Read using a value sVals[1].Read() // This will not compile: // sVals[1].Write("test") sPtrs := map[int]*S{1: {"A"}} // You can call both Read and Write using a pointer sPtrs[1].Read() sPtrs[1].Write("test")
Similarly, an interface can be satisfied by a pointer, even if the method has a
value receiver.
type F interface { f() } type S1 struct{} func (s S1) f() {} type S2 struct{} func (s *S2) f() {} s1Val := S1{} s1Ptr := &S1{} s2Val := S2{} s2Ptr := &S2{} var i F i = s1Val i = s1Ptr i = s2Ptr // The following doesn't compile, since s2Val is a value, and there is no value receiver for f. // i = s2Val
Effective Go has a good write up on Pointers vs. Values.
Zero-value Mutexes are Valid
The zero-value of
sync.Mutex and
sync.RWMutex is valid, so you almost
never need a pointer to a mutex.
If you use a struct by pointer, then the mutex can be a non-pointer field.
Unexported structs that use a mutex to protect fields of the struct may embed
the mutex.
Copy Slices and Maps at Boundaries
Slices and maps contain pointers to the underlying data so be wary of scenarios
when they need to be copied.
Receiving Slices and Maps
Keep in mind that users can modify a map or slice you received as an argument
if you store a reference to it.
Returning Slices and Maps
Similarly, be wary of user modifications to maps or slices exposing internal
state.
Defer to Clean Up
Use defer to clean up resources such as files and locks.
Defer has an extremely small overhead and should be avoided only if you can
prove that your function execution time is in the order of nanoseconds. The
readability win of using defers is worth the miniscule cost of using them. This
is especially true for larger methods that have more than simple memory
accesses, where the other computations are more significant than the
defer.
Channel Size is One or None
Channels should usually have a size of one or be unbuffered. By default,
channels are unbuffered and have a size of zero. Any other size
must be subject to a high level of scrutiny. Consider how the size is
determined, what prevents the channel from filling up under load and blocking
writers, and what happens when this occurs.
Start Enums at One
The standard way of introducing enumerations in Go is to declare a custom type
and a
const group with
iota. Since variables have a 0 default value, you
should usually start your enums on a non-zero value.
There are cases where using the zero value makes sense, for example when the
zero value case is the desirable default behavior.
type LogOutput int const ( LogToStdout LogOutput = iota LogToFile LogToRemote ) // LogToStdout=0, LogToFile=1, LogToRemote=2
Error Types
There are various options for declaring errors:
- [
errors.New] for errors with simple static strings
- [
fmt.Errorf] for formatted error strings
- Custom types that implement an
Error()method
- Wrapped errors using [
"pkg/errors".Wrap]
When returning errors, consider the following to determine the best choice:
- Is this a simple error that needs no extra information? If so, [
errors.New]
should suffice.
- Do the clients need to detect and handle this error? If so, you should use a
custom type, and implement the
Error()method.
- Are you propagating an error returned by a downstream function? If so, check
the section on error wrapping.
- Otherwise, [
fmt.Errorf] is okay.
If the client needs to detect the error, and you have created a simple error
using [
errors.New], use a var for the error.
If you have an error that clients may need to detect, and you would like to add
more information to it (e.g., it is not a static string), then you should use a
custom type.
Be careful with exporting custom error types directly since they become part of
the public API of the package. It is preferable to expose matcher functions to
check the error instead.
// package foo type errNotFound struct { file string } func (e errNotFound) Error() string { return fmt.Sprintf("file %q not found", e.file) } func IsNotFoundError(err error) bool { _, ok := err.(errNotFound) return ok } func Open(file string) error { return errNotFound{file: file} } // package bar if err := foo.Open("foo"); err != nil { if foo.IsNotFoundError(err) { // handle } else { panic("unknown error") } }
Error Wrapping
There are three main options for propagating errors if a call fails:
- Return the original error if there is no additional context to add and you
want to maintain the original error type.
- Add context using [
"pkg/errors".Wrap] so that the error message provides
more context and [
"pkg/errors".Cause] can be used to extract the original
error.
- Use [
fmt.Errorf] if the callers do not need to detect or handle that
specific error case.
It is recommended to add context where possible so that instead of a vague
error such as “connection refused”, you get more useful errors such as
“call service foo: connection refused”.
When adding context to returned errors, keep the context succinct by avoiding
phrases like “failed to”, which state the obvious and pile up as the error
percolates up through the stack:
However once the error is sent to another system, it should be clear the
message is an error (e.g. an
err tag or “Failed” prefix in logs).
See also Don’t just check errors, handle them gracefully.
Handle Type Assertion Failures
The single return value form of a type assertion will panic on an incorrect
type. Therefore, always use the “comma ok” idiom.
Don’t Panic
Code running in production must avoid panics. Panics are a major source of
cascading failures. If an error occurs, the function must return an error and
allow the caller to decide how to handle it.
Panic/recover is not an error handling strategy. A program must panic only when
something irrecoverable happens such as a nil dereference. An exception to this is
program initialization: bad things at program startup that should abort the
program may cause panic.
var _statusTemplate = template.Must(template.New("name").Parse("_statusHTML"))
Even in tests, prefer
t.Fatal or
t.FailNow over panics to ensure that the
test is marked as failed.
Use go.uber.org/atomic
Atomic operations with the sync/atomic package operate on the raw types
(
int32,
int64, etc.) so it is easy to forget to use the atomic operation to
read or modify the variables.
go.uber.org/atomic adds type safety to these operations by hiding the
underlying type. Additionally, it includes a convenient
atomic.Bool type.
Performance
Performance-specific guidelines apply only to the hot path.
Prefer strconv over fmt
When converting primitives to/from strings,
strconv is faster than
fmt.
Avoid string-to-byte conversion
Do not create byte slices from a fixed string repeatedly. Instead, perform the
conversion once and capture the result.
Style
Group Similar Declarations
Go supports grouping similar declarations.
This also applies to constants, variables, and type declarations.
Only group related declarations. Do not group declarations that are unrelated.
Groups are not limited in where they can be used. For example, you can use them
inside of functions.
Import Group Ordering
There should be two import groups:
- Standard library
- Everything else
This is the grouping applied by goimports by default.
Package Names
When naming packages, choose a name that is:
- All lower-case. No capitals or underscores.
- Does not need to be renamed using named imports at most call sites.
- Short and succinct. Remember that the name is identified in full at every call
site.
- Not plural. For example,
net/url, not
net/urls.
- Not “common”, “util”, “shared”, or “lib”. These are bad, uninformative names.
See also Package Names and Style guideline for Go packages.
Function Names
We follow the Go community’s convention of using MixedCaps for function
names. An exception is made for test functions, which may contain underscores
for the purpose of grouping related test cases, e.g.,
TestMyFunction_WhatIsBeingTested.
Import Aliasing
Import aliasing must be used if the package name does not match the last
element of the import path.
import ( "net/http" client "example.com/client-go" trace "example.com/trace/v2" )
In all other scenarios, import aliases should be avoided unless there is a
direct conflict between imports.
Function Grouping and Ordering
- Functions should be sorted in rough call order.
- Functions in a file should be grouped by receiver.
Therefore, exported functions should appear first in a file, after
struct,
const,
var definitions.
A
newXYZ()/
NewXYZ() may appear after the type is defined, but before the
rest of the methods on the receiver.
Since functions are grouped by receiver, plain utility functions should appear
towards the end of the file.
Reduce Nesting
Code should reduce nesting where possible by handling error cases/special
conditions first and returning early or continuing the loop. Reduce the amount
of code that is nested multiple levels.
Unnecessary Else
If a variable is set in both branches of an if, it can be replaced with a
single if.
Top-level Variable Declarations
At the top level, use the standard
var keyword. Do not specify the type,
unless it is not the same type as the expression.
Specify the type if the type of the expression does not match the desired type
exactly.
type myError struct{} func (myError) Error() string { return "error" } func F() myError { return myError{} } var _e error = F() // F returns an object of type myError but we want error.
Prefix Unexported Globals with _
Prefix unexported top-level
vars and
consts with
_ to make it clear when
they are used that they are global symbols.
Exception: Unexported error values, which should be prefixed with
err.
Rationale: Top-level variables and constants have a package scope. Using a
generic name makes it easy to accidentally use the wrong value in a different
file.
Embedding in Structs
Embedded types (such as mutexes) should be at the top of the field list of a
struct, and there must be an empty line separating embedded fields from regular
fields.
Use Field Names to initialize Structs
You should almost always specify field names when initializing structs. This is
now enforced by [
go vet].
Exception: Field names may be omitted in test tables when there are 3 or
fewer fields.
tests := []struct{ op Operation want string }{ {Add, "add"}, {Subtract, "subtract"}, }
Local Variable Declarations
Short variable declarations (
:=) should be used if a variable is being set to
some value explicitly.
However, there are cases where the default value is clearer when the
var
keyword is use. Declaring Empty Slices, for example.
nil is a valid slice
nil is a valid slice of length 0. This means that,
- You should not return a slice of length zero explicitly. Return
nil
instead.
- To check if a slice is empty, always use
len(s) == 0. Do not check for
nil.
- The zero value (a slice declared with
var) is usable immediately without
make().
Reduce Scope of Variables
Where possible, reduce scope of variables. Do not reduce the scope if it
conflicts with Reduce Nesting.
If you need a result of a function call outside of the if, then you should not
try to reduce the scope.
Avoid Naked Parameters
Naked parameters in function calls can hurt readability. Add C-style comments
(
/* ... */) for parameter names when their meaning is not obvious.
Better yet, replace naked
bool types with custom types for more readable and
type-safe code. This allows more than just two states (true/false) for that
parameter in the future.
type Region int const ( UnknownRegion Region = iota Local ) type Status int const ( StatusReady = iota + 1 StatusDone // Maybe we will have a StatusInProgress in the future. ) func printInfo(name string, region Region, status Status)
Use Raw String Literals to Avoid Escaping
Go supports raw string literals,
which can span multiple lines and include quotes. Use these to avoid
hand-escaped strings which are much harder to read.
See also, | https://xiequan.info/uber-go-style-guide/ | CC-MAIN-2020-16 | refinedweb | 2,399 | 65.01 |
5. File formats and conventions eg /etc/passwd
xfsSection: File Formats (5)
Index | Return to Main Contents
NAMExfs - layout, mount options, and supported file attributes for the XFS filesystem
DESCRIPTIONSome functionality specific to the XFS filesystem is accessible to applications through the xfsctl(3) and by-handle (see open_by_handle(3)) interfaces.
MOUNT OPTIONST
- The options enable/disable an "opportunistic" improvement to be made in the way inline extended attributes are stored on-disk. When the new form is used for the first time when attr2 is selected (either when setting or removing extended attributes) the on-disk superblock feature bit field will be updated to reflect this format being in use.
The.
Barriers are enabled by default.
- discard|nodiscard
- Enable/disable the issuing of commands to let the block device reclaim space freed by the filesystem. This is useful for SSD devices, thinly provisioned LUNs and virtual machine images, but may have a performance impact.
Note: It is currently recommended that you use the fstrim application to discard unused blocks rather than the discard mount option because the performance impact of this option is quite severe. For this reason, nodiscard is the default.
- grpid|bsdgroups|nogrpid|sysvgroups
- These options define what group ID a newly created file gets. When grpid is set, it takes the group ID of the directory in which it is created; otherwise it takes the fsgid of the current process, unless the directory has the setgid bit set, in which case it takes the gid from the parent directory, and also gets the setgid bit set if it is a directory itself.
- filestreams
- Make the data allocator use the filestreams allocation mode across the entire filesystem rather than just on directories configured to use it.
- of the page cache.
If "largeio" specified, a filesystem that was created with a "swidth" specified will return the "swidth" value (in bytes) in st_blksize. If the filesystem does not have a "swidth" specified but does specify an "allocsize" then "allocsize" (in bytes) will be returned instead. Otherwise the).
-.
- noalign
- Data allocations will not be aligned at stripe unit boundaries. This is only relevant to filesystems created with non-zero data alignment parameters (sunit, swidth) by mkfs.
-, and often used in combination with "norecovery" for mounting read-only snapshots.
- noquota
- Forcibly turns off all quota accounting and enforcement within the filesystem.
- uquota/usrquota/quota/uqnoenforce/qnoenforce
-. These options are only relevant to filesystems that were created with non-zero data alignment parameters.
The sunit and swidth parameters specified must be compatible with the existing filesystem alignment characteristics. In general, that means the only valid changes to sunit are increasing it by a power-of-2 multiple. Valid swidth values are any integer multiple of a valid sunit value.
Typically the only time these mount options are necessary if after an underlying RAID device has had it's geometry modified, such as adding a new disk to a RAID5 lun and reshaping it.
- swalloc
- Data allocations will be rounded up to stripe width boundaries when the current end of file is being extended and the file size is larger than the stripe width size.
- wsync
- When specified, all filesystem namespace operations are executed synchronously. This ensures that when the namespace operation (create, unlink, etc) completes, the change to the namespace is on stable storage. This is useful in HA setups where failover must not result in clients seeing inconsistent namespace presentation during or after a failover event.
FILE ATTRIBUTESTchattr(1), xfsctl(3), mount(8), mkfs.xfs(8), xfs_info(8), xfs_admin(8), xfsdump(8), xfsrestore(8).
Index
Return to Main Contents | https://eandata.com/linux/?chap=5&cmd=xfs | CC-MAIN-2020-10 | refinedweb | 598 | 52.29 |
As I was jogging this morning, I went pass a vegetable warehouse, because it was really early in the morning, I saw the veg distributor were biding for tons and tons of vegetables, they were yelling and shouting. Love the atmosphere, and I saw a monitor that shows all kinds of information about the goods they delivered. So I begin to wonder, can I do this with Camel?
OK, so here is the case, when ever a truck comes in with loads of goods, when the driver signs the goods over, a cvs file contains the product information will be feed into our system via wireless transmission. Because we need to work with these data, our first step is then to covert the individual items in csv file into Java Objects. Since there are multiple items in one csv file, so it's a perfect timing for us to use the splitter pattern in Camel.
After we split each product, we can use the built-in Bindy Data format to convert the single line csv item into a Pojo. For Bindy, it is used for converting non-structured data to/from Java Bean. The sources of converting could be as follows,
- CSV records
- Fixed-length records
- FIX messages
- or almost any other non-structured data
Before you start coding, make sure you have the right dependency by adding the camel-bindy dependency in.
org.apache.camel camel-bindy 2.12.0.redhat-611412
First specify where you will collect the csv file, with a file endpoint, with our example, we listen from a csv file and delete the file after done
And then start splitting it using the pattern, uses new line as the separator,
And then convert it into Pojo by unmarshalling the csv file with bindy. As you can see we refer it to a Java Object named product.
Inside the object,there are few things needs to be pre-configured like the annotation that defines binding mappings. First, need to set the separator between each column, and then set which position it is in the csv file.
package org.blogdemo.websocketdemo; import org.apache.camel.dataformat.bindy.annotation.CsvRecord; import org.apache.camel.dataformat.bindy.annotation.DataField; @CsvRecord(separator = "\\,") public class Product { @DataField(pos = 1, required = true) String productId; @DataField(pos = 2, required = true) String productName; @DataField(pos = 3, required = true) String farmerName; @DataField(pos = 4, required = true) String quantity; @DataField(pos = 5, required = true) String harvestDate; //........ @Override public String toString() { //...... } }
Here is the video taking you how to do it step by step.
After we receive the data, we are going to display the information on the monitor through Websocket and also store the data somewhere in the system too in Part Two.
I tried to use bindy to parse UTF-8 fixed length file I get errors. It seems that characters that need multiple bytes to encode confuse the parser/scanner.
How to deal with multiple bytes characters with bindy?
or we need to use something else?
Thanks in advance
Then total bytes of each line may exceed 600 bytes.
Indy check total bytes (not character) then it error.
I managed to workaround this by write my own Processor with java.
Thanks!
Your sample is helpful. I am able to create a route that handle a fixed length file no problem. Now I am looking for a sample to read a fixed length with first row as header, then rest are detail rows. I have been trying to annotate "hasHeader" in the primary model and "isHeader" in the header model but no luck, would you kindly provide me some directions?
Thanks | http://wei-meilin.blogspot.com/2015/03/jboss-fuse-parsing-csv-file-playing.html | CC-MAIN-2019-30 | refinedweb | 606 | 69.82 |
Scrapy SDK Customisation Options
Once, you have integrated the ScrapeOps SDK with your Scrapy spiders using the Scrapy Integration Guide, the SDK will automatically log all your scraping stats and display them on your dashboard.
However, there is more functionality within the Scrapy SDK that enables you to customise how it logs your Scrapy spiders.
Setting a Job Name
With ScrapeOps you can give your jobs unique Job Names so that their stats can be grouped together on the dashboard and have health checks applied to them.
There are two ways of doing this:
- ScrapeOps Server Management - If you are using ScrapeOps to schedule/run jobs on your VM/Scrapyd servers you can give each job a unique name in the dashboard when you schedule it.
- In Your Spider - You can define the job name in your spider using the spider arguement
sops_job_name.
The following is an example of how to give a job an unique Job Name within your spider.
class DemoSpider(scrapy.Spider):
name = 'demo_spider'
sops_job_name = "MY_JOB_NAME" ## add job name here
def start_requests(self):
urls = [
'',
'',
]
for url in urls:
yield scrapy.Request(url | https://scrapeops.io/docs/monitoring/python-scrapy/scrapy-sdk-customisation/ | CC-MAIN-2022-40 | refinedweb | 185 | 62.61 |
Visual Studio provides powerful databinding features which allow you, the developer, to attach controls to fields in a database table and have those fields update automatically when the current record in the table is changed. What makes it so powerful is that you can do this with little or no code. With common data types like strings or numbers, databinding is very simple, but it gets slightly more complicated when the data to be bound to is a custom type. This article addresses that special case and discusses how to bind a control to ink stored in a database. Note that the ink I'm referring to is the ink from the Microsoft Tablet PC SDK.
This article is a companion article to Using .NET Databinding to Display Ink from a Database which discussed how to bind a read-only InkPicture control to a database. If you have not read that article, you should probably take a moment to do so now. This article will go a step further and discuss how to create a read-write binding of the ink to the database using a control that is derived from the InkPicture control and it assumes that you are familiar with all the content in the previous article. Due to threading issues it is not possible to create a read/write binding to the InkPicture control directly, hence the need for us to create our own derived control.
InkPicture
This article assumes that you have knowledge of or experience using bound controls in Microsoft Visual Studio and are able to use the IDE to manipulate Connections, DataAdapters, and DataSets. Basic understanding of the development of user controls is also helpful, but not necessary.
In order to use the code in this article you will need to have the Microsoft Tablet PC SDK installed on your development machine. The Tablet PC SDK can be downloaded from. It is not necessary to have a Tablet PC in order to use the SDK.
Because of a threading issue with the InkPicture control that ships with the Tablet PC SDK it is necessary to crate our own InkPicture control to use in our databinding. We don't want to reinvent the wheel so we use inheritance and derive our new control from the InkPicture control. The code below shows what the declaration of our new control should look like.
public class InkDataPicture : Microsoft.Ink.InkPicture
{
}
The inherited control takes on all the properties and methods of the control it inherits from so we only need to implement the properties or methods that we would like to change. If you've done development with Ink serialization and the InkPicture box then you know that the InkEnabled property of the control needs to be false if you are going to manipulate the ink in code. We bind to the Ink property of the control using formatting events and those events do not provide us access to the source control; they only provide us access to the data. Because we don't have access to the control we cannot ensure that the InkEnabled property is false. Because of this issue, attempts to bind to an editable InkPicture box will fail.
To work around the editing limitation of the InkPicture control we will implement a new Ink property on our inherited control. In our property we will force the InkEnabled property to be false whenever the Ink property is written to. The code below shows this new property.
InkEnabled
Ink
public new Ink Ink
{
get {return base.Ink;}
set
{
bool EnabledCache = base.InkEnabled;
base.InkEnabled = false;
base.Ink = value;
base.InkEnabled = EnabledCache;
}
}
In the previous article which described binding read-only ink to the control. The process is very similar for the read/write binding. The only difference is the addition of an event handler for the Parse event. The Format event fired when the data in the database (a byte array) needed to be converted to Ink. The Parse event is the exact opposite and fires when the Ink needs to be converted back to bytes for storage in the database. The code below demonstrates how to bind the control to the database and implement the event handlers.
Parse
Format
private void Form1_Load(object sender, System.EventArgs e)
{
Binding binding = inkDataPicture1.DataBindings.Add(
"Ink",myDS1,"MyTable.InkField");
binding.Format += new ConvertEventHandler(binding_Format);
binding.Parse += new ConvertEventHandler(binding_Parse);
odbDA.Fill(myDS1);
}
private void binding_Format(object sender, ConvertEventArgs e)
{
Ink ink = new Ink();
if (e.DesiredType.Equals(typeof(Ink)))
{
if (e.Value.GetType().Equals(typeof(byte[])))
{
byte[] bytes = (byte[])e.Value;
if (bytes.Length>0)
{
ink.Load(bytes);
}
}
e.Value = ink;
}
}
private void binding_Parse(object sender, ConvertEventArgs e)
{
if (e.DesiredType.Equals(typeof(byte[])) &&
e.Value.GetType().Equals(typeof(Ink)))
{
Ink ink = (Ink)e.Value;
e.Value = ink.Save(PersistenceFormat.InkSerializedFormat);
}
}
The code above allows you to make changes to the ink in your new control but the changes won't be saved to the database until you instruct it to. This is done in our sample application by the use of the Update method on the DataAdapter.
Update
DataAdapter
odbDA.Update(myDS1);
That's all there is too it. It's not quite as simple as standard databinding but once you have it working you could forget about it and never touch the code again.
For other easy to use, and free, ink-enabled controls visit our Web site. | http://www.codeproject.com/Articles/8044/Using-NET-Databinding-to-Bind-an-Editable-InkPictu?PageFlow=FixedWidth | CC-MAIN-2014-49 | refinedweb | 902 | 64 |
This is a useful trick. When you have setup an dataset on your page maybe you want to change the filter in that dataset depending on different conditions. I made two buttons and four images. The images are all connected to a dataset called pageElements and consists of fields pageName, puffImage1, puffImage2, puffImage3 and puffImage4 which is the four images.
Now I connect the buttons to their onClick method in code below and change the filter in the dataset and the images will then change depending on which button is clicked. This can be used through url filter, user filter, connected to another dataset or in any other way. I think it is awesome to change filters during runtime this way.
Then just take the same code and add that to the second button and you are good to go.
Added the code for quick copy and paste.
import wiXData from 'wix-data'; export function puffButton1_onClick(event) { // Change puffImage filter on dataset and fade in new images console.log("change images to hotel"); wixData.query("pageElements").eq("pageName", "hotel").find().then((results) => { let items = results.items; let firstItem = items[0]; $w("#puffImage1").src = firstItem.puffImage1; $w("#puffImage2").src = firstItem.puffImage2; $w("#puffImage3").src = firstItem.puffImage3; $w("#puffImage4").src = firstItem.puffImage4; });
This is cool. URL to your site you're building?
it is not published yet
How would you go about filtering a dataset on click for a table?
If you would like to filter a dataset and reconnect that filtered data onto a table on your page you can do it like the below code.
Your dataset is called: myDataset
Your table is called: myTable
The above code will check if fieldToFilterOn is equal to valueToFilterBy and then it take the results and get the items in that result and push those items into the rows property on the table named myTable.
This is not tested but it should work ;)
HI Andreas, I would have messaged you directly but couldn't figure out how. I am trying to build something specific and thought you could help. I want to build a dynamic one page website that uses forms instead of a traditional menu to navigate. Options selected by the visitor will then custom build the page based off selections. unchecking an option would remove it from the page. in the end, the information remaining would be collected as a sales lead. Think you could help? I tried watching your video on workflows but the quality was very low and I couldn't really see it.
Write to me at hello@wixshow.com
Hey Andreas,
I have given the above codes a go on my website but haven't quite perfected them to achieve what I am after.
Like many shopping sites, I want to be able to click the filters which are at the top of my page (img attached) and the gallery will be filtered as I click any of the buttons in any order.
Is there a way to highlight the buttons once clicked so the user can see their selection?
Alternatively, I could use a check box but unsure how to code this also.
So far, I have the following code which works for the "Sort" buttons
import wixData from 'wix-data';
$w.onReady( function() {
$w("#button23").onClick( (event, $w) => {
$w("#dataset1").setSort( wixData.sort()
.descending("price") );
} );
$w("#button22").onClick( (event, $w) => {
$w("#dataset1").setSort( wixData.sort()
.ascending("price") );
} );
} );
This page is
Any help will be much appreciated! Many thanks.
Helen | https://www.wix.com/velo/forum/coding-with-velo/changing-filter-in-a-dataset-onclick | CC-MAIN-2021-21 | refinedweb | 584 | 73.17 |
In this tutorial, you’ll learn to use Python 3 for creating an IRC bot. IRC is an acronym for Internet Relay Chat which is a popular form of communication to send text messages over the network.
How to Use Python to Build an IRC Bot?
What is an IRC Bot?
A bot is a virtual assistant that emulates a real user to provide instant responses. IRC bot is a type of network client that could be a script or a program that can relay messages using the IRC protocol.
When any active user receives a text from the IRC bot, it appears to him as another real user.
What can a Bot do?
The bots mimic a real user and communicate with other active clients. However, they can perform a variety of tasks:
- Archive chat messages
- Can parse Twitter feeds
- Crawl the web for a keyword
- Run any command if needed.
How to Implement IRC in Python?
For this, we’ll need a Python program that creates a client socket to connect to the IRC server. The IRC server performs a simple verification and connects without much hassle.
The script uses Python socket library to allow network communication. Check the below sample code.
import socket ircbot = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
The IRC protocol is just a layer above the IP protocol and works over the TCP/IP stack.
We’ll need our program to exchange the following set of commands.
** Authetication **** USER botname botname botname: text NICK botname NICKSERV IDENTIFY botnickpass botpass ** Join Channel **** JOIN
Bot Source Code
Class File:
First, you need to create an IRC bot class. Copy the below code and paste in a file and save it as the irc_class.py.
import socket import sys import time class IRC: irc = socket.socket() def __init__(self): # Define the socket self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def send(self, channel, msg): # Transfer data self.irc.send(bytes("PRIVMSG " + channel + " " + msg + "n", "UTF-8")) def connect(self, server, port, channel, botnick, botpass, botnickpass): # Connect to the server print("Connecting to: " + server) self.irc.connect((server, port)) # Perform user authentication self.irc.send(bytes("USER " + botnick + " " + botnick +" " + botnick + " :pythonn", "UTF-8")) self.irc.send(bytes("NICK " + botnick + "n", "UTF-8")) self.irc.send(bytes("NICKSERV IDENTIFY " + botnickpass + " " + botpass + "n", "UTF-8")) time.sleep(5) # join the channel self.irc.send(bytes("JOIN " + channel + "n", "UTF-8")) def get_response(self): time.sleep(1) # Get the response resp = self.irc.recv(2040).decode("UTF-8") if resp.find('PING') != -1: self.irc.send(bytes('PONG ' + resp.split().decode("UTF-8") [1] + 'rn', "UTF-8")) return resp
After creating the network communication class, we’ll import t in our client and use its instance. We are designing a demo client so that you can understand it easily.
Our bot will send the “Hello!” message while responding to a “Hello” message on the channel.
Client Script:
Below the Python IRC Bot program to start the client communication. Create a new file, copy the code, paste it, and save as irc_bot.py.
IRC server usually runs on ports like 6667 or 6697 (IRC with SSL). So, we’ll be using “6667” in our sample. Also, you will need to provide a valid IRC Server IP address or hostname to make this program run correctly.
from irc_class import * import os import random ## IRC Config server = "10.x.x.10" # Provide a valid server IP/Hostname port = 6697 channel = "#python" botnick = "techbeamers" botnickpass = "guido" botpass = "<%= @guido_password %>" irc = IRC() irc.connect(server, port, channel, botnick, botpass, botnickpass) while True: text = irc.get_response() print(text) if "PRIVMSG" in text and channel in text and "hello" in text: irc.send(channel, "Hello!")
Please note that you can run the above program using the following command:
python irc_bot.py
Hope, the above tutorial could help you build a more complex IRC bot with more features and usage.
If you wish to learn Python programming from scratch, then read this Python Tutorial.
>. | https://linksoftvn.com/python-irc-bot-a-hands-on-tutorial-with-example/ | CC-MAIN-2019-18 | refinedweb | 665 | 59.19 |
I have a script to import pointclouds. To select the files to import I use code like this:
from rhinoscriptsyntax import OpenFileNames filtr = 'Text Files (*.txt)|*.txt| XYZ Color files (*.xyz)|*.xyz|pts Files (.pts)|*.pts||' strPaths = OpenFileNames('XYZRGB file to import', filtr)
Download from here:
XYZRGB_Import_File_Names_Crashes_Rhino.py (195 Bytes)
If you run this short script, a file selection window will pop up. If you cancel this window, then Rhino crashes after a few seconds.
Is this a bug or should I be doing this another way? The crash does not occur when selecting only a single file and cancelling the file selection window using this code:
from rhinoscriptsyntax import OpenFileName filtr = 'Text Files (*.txt)|*.txt| XYZ Color files (*.xyz)|*.xyz|pts Files (.pts)|*.pts||' strPath = OpenFileName('XYZRGB file to import', filtr)
The crash happens in both Rhino 7 and 6.
Regards,
Terry. | https://discourse.mcneel.com/t/cancelling-file-selection-window-crashes-rhino-7-6/117512 | CC-MAIN-2022-27 | refinedweb | 143 | 66.54 |
I was asked if I’d be keen to go to Kiwi Pycon (a Python conference in Dunedin, New Zealand). I decided it would be an interesting experience even though my Python knowledge is a bit lacking
A few weeks ago I was asked if I’d be keen to go to Kiwi Pycon (a Python conference in Dunedin, New Zealand). I decided it would be an interesting experience even though my Python knowledge is a bit lacking. So as an after-work project my colleague Yosan and I decided to put together a small game to help us learn the language. This article covers our initial experiences putting everything together.
As with other languages I’ve learned I typically like to develop an application which involves a handful of functions such as reading files, networking, user input and visuals. This forces me to become familiar with libraries and language functions which gets me up to speed in a way that re-implementing algorithms and completing tutorial projects would not. It also forces me to understand a bit about Python’s environment with regards to installing dependencies and creating releases.
We looked up a few libraries related to game creation and networking and decided to use pygame as that seemed to provide a functionality that would remove a lot of the tedium from development. It also looked like Python had a range of libraries for networking so we decided to figure it out when we got to it.
Python itself was relatively easy to install. We just took the auto installer from the website and had the runtime ready within a minute.
Pygame proved to be a bit frustrating to install. It took several attempts before we managed to download the script and install it in the correct way. We had to find the correct version of the library (that matched the version of Python we had installed) on a list of dependencies that wasn’t easily found, then extract that with the Python package install utility pip3.exe. This seemed harder than it should have been, especially due to the number of different versions of the library and the slight differences in what we would have to do if we had a different version of Python installed.
Eventually we got things set up and looked for a tutorial on getting the basics of a game up and running.
The first thing to do when getting started with anything graphical is just to get something (or anything) rendered to the screen. We found a whole bunch of tutorials of varying complexity on this and based on their examples came up with a basic render loop:
import pygame, sys from pygame.locals import *
WIDTH = 400 HEIGHT = 400
screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Hello World!')
clock = pygame.time.Clock()
thing = pygame.image.load('images/TrashPanda/TrashPanda_front.png')
x = 0 y = 0
while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
clock.tick(30) screen.fill((0,0,0)) screen.blit(thing, (x, y)) pygame.display.flip()
This code produced this:
After that, we focused on capturing user input to move the character. We also created a class for the player character to internalize some of its logic:
class Minion: def init(self, x, y): self.x = x self.y = y self.vx = 0 self.vy = 0 def update(self): self.x += self.vx self.y += self.vy #this keeps the player character within the bounds of the screen if self.x > WIDTH - 50: self.x = WIDTH - 50 if self.x < 0: self.x = 0 if self.y > HEIGHT - 50: self.y = HEIGHT - 50 if self.y < 0: self.y = 0
def render(self): screen.blit(thing, (self.x, self.y))
User input was captured within the game loop:
for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_LEFT: cc.vx = -10 if event.key == K_RIGHT: cc.vx = 10 if event.key == K_UP: cc.vy = -10 if event.key == K_DOWN: cc.vy = 10 if event.type == KEYUP: if event.key == K_LEFT and cc.vx == -10: cc.vx = 0 if event.key == K_RIGHT and cc.vx == 10: cc.vx = 0 if event.key == K_UP and cc.vy == -10: cc.vy = 0 if event.key == K_DOWN and cc.vy == 10: cc.vy = 0
And the character’s position was updated and rendered (also in the gameloop):
cc.update() cc.render()
Now that we had basic character movement working, we wanted to start building some simple multiplayer functionality.
We decided on a very simple data transfer model:
We decided to use TCP sockets as they handle things like connects and disconnects easier than UDP. Also this isn’t exactly a performance critical application.
We managed to find a good article covering writing async servers in Python here.
The basic server code started as this:
import socket import asyncore import random import pickle import time
BUFFERSIZE = 512
outgoing = []
#additional logic here...
class MainServer(asyncore.dispatcher): def init(self, port): asyncore.dispatcher.init(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind(('', port)) self.listen(10)
def handle_accept(self): conn, addr = self.accept() print ('Connection address:' + addr[0] + " " + str(addr[1])) outgoing.append(conn) playerid = random.randint(1000, 1000000) playerminion = Minion(playerid) minionmap[playerid] = playerminion conn.send(pickle.dumps(['id update', playerid])) SecondaryServer(conn)
class SecondaryServer(asyncore.dispatcher_with_send): def handle_read(self): recievedData = self.recv(BUFFERSIZE) if recievedData: updateWorld(recievedData) else: self.close()
MainServer(4321) asyncore.loop()
This defines a MainServer responsible for accepting new TCP connections which it then creates a SecondaryServer for. The secondary servers handles all incoming data from each client. When an incoming packet is received, the data is passed to updateWorld. This is defined below:
class Minion: def init(self, ownerid): self.x = 50 self.y = 50 self.ownerid = ownerid
minionmap = {}
def updateWorld(message): arr = pickle.loads(message) playerid = arr[1] x = arr[2] y = arr[3]
if playerid == 0: return
minionmap[playerid].x = x minionmap[playerid].y = y
remove = []
for i in outgoing: update = ['player locations']
for key, value in minionmap.items(): update.append([value.ownerid, value.x, value.y]) try: i.send(pickle.dumps(update)) except Exception: remove.append(i) continue
for r in remove: outgoing.remove(r)
updateWorld is simply responsible for updating the dictionary containing the location of each player’s character. It then broadcasts the positions to each player by serializing their positions as an array of arrays.
Now that the client was built we could implement the logic in the client to send and receive updates. When the game is started we added some logic to start a simple socket and connect to a server address. This optionally takes an IP address specified by the command line but otherwise connects to localhost:
serverAddr = '127.0.0.1' if len(sys.argv) == 2: serverAddr = sys.argv[1] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((serverAddr, 4321))
We then added some logic to the start of the game loop to read from the socket. We utilized the ‘select’ package to read incoming packages from the socket only when they had data. If we had used ‘socket.recv’ the gameloop would halt if the socket didn’t have any packets to read. Using ‘select’ allows the gameloop to continue executing even if there isn’t anything to read:
ins, outs, ex = select.select([s], [], [], 0) for inm in ins: gameEvent = pickle.loads(inm.recv(BUFFERSIZE)) if gameEvent[0] == 'id update': playerid = gameEvent[1] print(playerid) if gameEvent[0] == 'player locations': gameEvent.pop(0) minions = [] for minion in gameEvent: if minion[0] != playerid: minions.append(Minion(minion[1], minion[2], minion[0]))
The above code handled two of the serialized payloads the server could possibly produce.
1. The initial packet containing the players server assigned identifier
This is used by the client to identify itself to the server on all position updates. It also used to ignore its own player data that server broadcasts so there isn’t a shadowed version of the player character.
2. The player location payload
This contains a set of arrays containing player identifiers and character positions. When this is retrieved the existing Minion objects are cleared and new Minion objects are created for each of the transmitted ones.
The other Minions are then rendered in the game loop:
for m in minions: m.render()
The last thing we had to do was to add some code to the client to tell the server the position of the player. This was done by adding a broadcast at the end of the gameloop to serialize the current players position using ‘pickle‘, then sending this bytestream to the server:
ge = ['position update', playerid, cc.x, cc.y] s.send(pickle.dumps(ge))
Once this was complete players connected to the same server could see the other players moving around.
Some additional updates such as displaying different avatars based on the playerid were implemented.
When finished, the current iteration with two players looked like this:
The full code for both client and server is available here.
Of course there’s always of room for development and improvement. If you found this article interesting, let us know in the comments below. Guide from a Python project to an open source package
☞ Top Popular Python open-source projects on GitHub...
After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...
Rummy Game Software Development- Mobiweb Technologies is India's leading Rummy Game Software provider company having expertise in providing Rummy website and app development solutions.
Mobiweb Technologies is a leading [ludo game app developmen]( "ludo game app developmen")t company that provides multiple types of ludo games in a single application. Ludo is one of the... | https://morioh.com/p/72dbbad1d23d | CC-MAIN-2020-40 | refinedweb | 1,654 | 60.21 |
Creating an online multiple-choice questionnaire with Python
It takes less than an hour…
There are many calculators online that are used to estimate the chance of medical harm due to disease such as risk calculators for thrombosis or mortality calculators for pneumonia. Most of them are made in Javascript and/or HTML. To see if and how Dash and Python can be used for making a medical calculator back and frontend I transformed the OPS assessment into an interactive form with multiple choice radio buttons. The code can be found on my GitHub and this is the link to the working version on Heroku.
In my example, I have used the OPS score. The OPS score is used to assess driving ability in the elderly. OPS stands for Orientation and memory, Practical skills and Social and personal functioning. It has been developed and published in 2000 by Frederiec Withaar from the University of Groningen in the article “Divided Attention and Driving, the effects of ageing and brain injury”. After the publication of her PhD thesis, the governmental organisation for medical drivers license checks in the Netherlands(CBR) started to ask for OPS scores of every applicant above the age of 75. There is currently no website that offers a quick calculation of the OPS score.
Steps
Creating a form adjusted to your needs will take you less than 60 minutes. You can use my code as a template. The main thing is to create a row with the dbc.Row function from Dash that contains a sentence and a row of labels with the answers displayed above radio buttons with the dcc.RadioItems function of Dash. The questions became a repeating pattern of the following:
dbc.Row(children=[
html.H5("Does the candidate overestimates her or his self concerning driving ability?",
style={"display": "inline-block", 'textAlign': 'center', "width": "50%", }),
dcc.RadioItems(
options=[
{'label': 'Yes', 'value': '1'},
{'label': 'Not sure', 'value': '2'},
{'label': 'No', 'value': '3'}
],
id='9',
value='',
# labelStyle={'display': 'inline-block', 'text-align': 'center','width': '100%'},
style={'display': 'inline-block', 'text-align': 'center', 'display': 'flex',
'justify-content': 'space-evenly', 'width': '30%'},
),
], ),
After a battery of rows the callback for the 9 questions looks as follows in its uncondensed form:
@app.callback(
Output('output-OPS-total', 'children'),
Output('output-O', 'children'),
Output('output-P', 'children'),
Output('output-S', 'children'),
[Input('1', 'value'),
Input('2', 'value'),
Input('3', 'value'),
Input('4', 'value'),
Input('5', 'value'),
Input('6', 'value'),
Input('7', 'value'),
Input('8', 'value'),
Input('9', 'value')])
def calc(Q1,Q2,Q3,Q4,Q5,Q6,Q7,Q8,Q9):
l = [Q1,Q2,Q3,Q4,Q5,Q6,Q7,Q8,Q9]
l_total, l_o, l_p, l_s = [], [], [], []
for i in l:
if i:
l_total.append(int(i))
for i in l[0:3]:
if i:
l_o.append(int(i))
for i in l[3:6]:
if i:
l_p.append(int(i))
for i in l[6:9]:
if i:
l_s.append(int(i))
return sum(l_total),sum(l_o),sum(l_p),sum(l_s)
After that created a Procfile with the following:
web: gunicorn OPS_calculator:server
and uploaded to Heroku:
git add .
git commit -m "update"
git push heroku master
The result looks something like this: | https://k-h-kramp.medium.com/ops-calculator-in-dash-with-python-d236f478f764?source=post_internal_links---------3---------------------------- | CC-MAIN-2022-21 | refinedweb | 529 | 53.41 |
mohitkumar gupta wrote: int x ;;
the above code complied fine.
are there anymore coding tricks that may come in the scjp exam
Shanky Sohar wrote:
mohitkumar gupta wrote: int x ;;
the above code complied fine.
are there anymore coding tricks that may come in the scjp exam
but if you try to do this
System.out.println(x);
then it will throw runtime exception
0
No it does not:
public class Test {
int x;;
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.x);
}
}
Result:
0
(Built in Eclipse, ran with Java 1.6.0_20).
Shanky Sohar wrote:
this is correct for instance or class and static variable.but not for local varaiables
for example..this will not work
also by mistake i say runtime error above but it will be compile time error
Sven Mathijssen wrote:
You are completely right, but the compile time error is not due to the extra semicolon at the end. If you omit the semicolon, it will still not compile.
Prasad Kharkar wrote:the compiler in that case will be because the int x variable will be locla variable and that should be initialized before using it
Pedro Kowalski wrote:One thing I bumped into recently is that
if (false) {
System.out.println("false if");
}
compiles and runs fine but shows warnings about 'dead code', while this
while (false) {
System.out.println("false while");
}
doesn't even compile because of unreachable code. | http://www.coderanch.com/t/508381/java-programmer-SCJP/certification/Coding-Tricks | CC-MAIN-2015-06 | refinedweb | 243 | 69.62 |
NAME
EXECUTE SCRIPT - Execute SQL/DDL script
SYNOPSIS
EXECUTE SCRIPT (options);
DESCRIPTION
Executes a script containing arbitrary SQL statements on all nodes that are subscribed to a set at a common controlled point within the repli‐ cation transaction stream. The specified event origin must be the origin of the set. The script file must not contain any START or COMMIT TRANSACTION calls. (This changes somewhat in PostgreSQL 8.0 once nested transactions, aka save‐ points, (Optional) The ID of the current origin of the set. Default val‐ ue is 1. EXECUTE ONLY ON = ival (Optional) The ID of the only node to actually execute the script. This option causes the script to be executed, by slonik(1), only on the one node specified. The default is to ex‐ ecute the script on all nodes that are subscribed to the set. See also the warnings in “Database Schema Changes (DDL)” [not available as a man page]. Note that this is a locking [“Locking Issues” [not available as a man page]] operation, which means that it can get stuck behind other database activity. At the start of this event, all replicated tables are unlocked via the function alterTableRestore(tab_id). After the SQL script has run, they are returned to ‘replicating state’ using alterTableForReplica tion(tab_id). This means that all of these tables are locked by this slon(1) process for the duration of the SQL script execution. If a table’s columns are modified, it is very important that the trig‐ gers be regenerated, otherwise they may be inappropriate for the new form of the table schema. Note that if you need to make reference to the cluster name, you can use the token @CLUSTERNAME@; if you need to make reference to the Slony-I namespace, you can use the token @NAMESPACE@; both will be ex‐ panded into the appropriate replacement tokens. This uses “schemadocddlscript_complete( integer, text, integer )” [not available as a man page].
EXAMPLE
EXECUTE SCRIPT ( SET ID = 1, FILENAME = ’/tmp/changes_2004-05-01.sql’, EVENT NODE = 1 ); Each replicated table receives an exclusive lock, on the origin node, in order to remove the replication triggers; after the DDL script com‐ pletes, those locks will be cleared. After the DDL script has run on the origin node, it will then run on subscriber nodes, where replicated tables will be similarly altered to remove replication triggers, therefore requiring that exclusive locks be taken out on each node, in turn. can‐ not speci‐ fied replication set. As of 1.1, all replicated tables are locked (e.g. - triggers are removed at the start, and restored at the end). This deals with the risk that one might request DDL changes on tables in multiple replication sets. 17 November 2008 EXECUTE SCRIPT(7) | http://manpages.ubuntu.com/manpages/karmic/man7/EXECUTE_SCRIPT.7.html | CC-MAIN-2014-15 | refinedweb | 458 | 62.68 |
>>(); } } }
<Window x: <Window.Resources> <local:ErrorsToMessageConverter x: </Window.Resources> <StackPanel Margin="5"> <TextBlock Margin="2">Enter An IPv4 Address:</TextBlock> <TextBox x: <TextBox.Text> <Binding ElementName="This" Path="IPAddress" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:IPv4ValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> <TextBlock Margin="2" Foreground="Red" FontWeight="Bold" Text="{Binding ElementName=AddressBox, Path=(Validation.Errors), Converter={StaticResource eToMConverter}}" /> </StackPanel> </Window>
In terms of the C# code, there really isn't much to look at - we just
have a dependency property for the IP address. It is the XAML that we
are really interested in here. First thing you probably noticed is that
we are declaring the binding for the
TextBox using the full binding
tags and syntax. This is because once you start adding things like
validation rules, we can't use the markup extension anymore.
Inside the
<Binding.ValidationRules> tags, we can list out all the
rules that we want to run against this binding. In our case, we only
have the one rule, but you can potentially have as many as you want. If
you have more than one rule, all the rules get run (it doesn't short
circuit after the first failure), so you get the accumulation of all the
rule errors.
The rules get run every time the binding propagates changes from the
target (in this case the
TextBox) to the source (in this case the
backing dependency property). Rules do not get run in the other
direction - so if something invalid was pushed directly into the source,
the target would show the value without running any rules. Because of
this, validation rules only make sense if the BindingMode of the
binding is
OneWayToSource or
TwoWay (the default).
By default, a
TextBox binding only commits changes when it loses
focus, but that is not nearly as interesting for this example. To get
the validation rules to run as the user types in the
TextBox, we set
the
UpdateSourceTrigger binding property to
PropertyChanged.
This means that the binding will be updated (and the rules will
therefore be run) every time the target property is changed.
Looking at the XAML, you are probably wondering where the red outline
comes from on the
TextBox when there is an error. Well, it turns out
that most of the built in WPF controls have a built in
ErrorTemplate.
This template defines what happens to the control in the case of a
validation rule failure. I actually think the default error template is
pretty good, but if you need to change it, you can treat it like any
other control template, and set it in a style.
That about covers the
TextBox, but now we need to take a look at how
we are displaying the error message. Validation rule errors are held in
an attached property called
Validation.Errors.
This is a collection of all the errors accumulated from all the rules
(remember, we can have more than one), so we need a converter to convert
that collection into a nice string to display:
using System; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Windows.Controls; using System.Windows.Data; namespace SOTCBindingValidation { public class ErrorsToMessageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var sb = new StringBuilder(); var errors = value as ReadOnlyCollection<ValidationError>; if (errors != null) { foreach(var e in errors.Where(e => e.ErrorContent != null)) { sb.AppendLine(e.ErrorContent.ToString()); } } return sb.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
A pretty simple converter - takes the error collection, and for each error that has an error message, append it to the accumulating string and then return the string. In the case were there are no errors, we will just get an empty string back.
The only trick to actually binding to the error collection is that it is
an attached property, and so you need to use the attached property path
syntax to reference it. That is why the
Validation.Errors has
parenthesis around it when it is set as the path of the binding. It is
essentially saying to take the
Errors attached property from the
Validation class and find the value on the
TextBox. Oh, the wonders
and confusion of dependency properties!
Well, that is it for this introduction to adding validation rules to your bindings! You can grab a zip of the source code for the example we built here below.
Source Files: | http://tech.pro/tutorial/948/wpf-tutorial-binding-validation-rules | CC-MAIN-2015-18 | refinedweb | 746 | 56.15 |
Java program to check if all the digits of a number are in increasing order :
In this tutorial, we will learn how to check if all the digits of a number are in increasing order or not using Java. For example, for the number 12345 , all the digits are in increasing order. But for the number 54321, they are not in increasing order.
The user will first enter one number and our program will start scanning its digits from right to left. It will compare the rightmost element to the element left to it. For example, 1234, we will first compare 4 with 3. Then we will change the number to 123. Again compare the digit 3 to 2. If we found any rightmost number less than the left one, it will exit from the loop and print one failure message.
Let’s take a look at the Java program to check how to solve this problem :
Java Program :
import java.util.Scanner; class Main { public static void main(String args[]) { //1 int num; boolean flag = false; //2 Scanner scanner = new Scanner(System.in); //3 System.out.println("Enter a number : "); num = scanner.nextInt(); //4 int currentDigit = num % 10; num = num/10; //5 while(num>0){ //6 if(currentDigit <= num % 10){ flag = true; break; } currentDigit = num % 10; num = num/10; } //7 if(flag){ System.out.println("Digits are not in increasing order."); }else{ System.out.println("Digits are in increasing order."); } } }
Explanation :
- Create one integer variable num to store the user input number and one boolean flag to indicate if the numbers are in increasing or decreasing order.
- Create one Scanner object to read the user input values.
- Ask the user to enter a number. Read it and store it in num variable.
- Create one integer currentDigit. It will hold the rightmost digit of the number. Convert the num to num/10.
- Run one while loop to check for all digits of num.
- If any right digit is less than the left digit, mark flag as true and break from the loop. Else, change the rightmost digit to the next left digit and change the number to number / 10.
- Check the value of flag and print one message to the user. If flag is true, digits are not in increasing order, else they are in increasing order.
Sample Output :
Enter a number : 123456 Digits are in increasing order. Enter a number : 1234586 Digits are not in increasing order. Enter a number : 1368 Digits are in increasing order.
Similar tutorials :
- Java program to check if a Matrix is Sparse Matrix or Dense Matrix
- Java Program to check if a number is Neon or not
- Java program to check if a number is perfect or not
- Java program to check if a number is Pronic or Heteromecic
- Java program to check if a matrix is upper triangular matrix or not
- Java program to check if a number is a buzz number or not | https://www.codevscolor.com/java-check-all-digits-number-increasing-order | CC-MAIN-2020-50 | refinedweb | 491 | 65.12 |
Straighten up, why?
You need to recover data from previously scanned document. Obviously you immediately think of using an OCR ( see this article which shows how to use Tesseract )… but there you are, if your document is of good quality, it is not aligned correctly. he is askew! and your OCR cannot interpret its content.
This is quite normal, in fact you must first straighten the document so that it looks straight, ready for the application of this OCR. We will see in this article how to use Python and the deskew library.
The Python deskew library
What’s great about the Python universe is that there is a library for everything. After some quick research on your search engine you will certainly find quite a few begging to be tried.
I’ll show you one of the simplest: the deskew library which you can find here .
Installation is quick and easy (the underlying code is also quick, if you have time to look at it). For information, this library uses another much better known scikit-image library , which is also very useful for managing image data.
pip install deskew
Goal
The goal is rather simple, we need to retrieve the textual information from the following image:
Just to check what I told you in the introduction, let’s try to use Tesseract directly on this image:
try: from PIL import Image except ImportError: import Image import pytesseract image1 = Image.open('img_35h.jpg') pytesseract.image_to_string(image1, lang='fra')
''
Indeed, Tesseract sees absolutely nothing!
Straighten the image with deskew
First of all, let’s import the necessary libraries:
import numpy as np from skimage import io from skimage.transform import rotate from skimage.color import rgb2gray from deskew import determine_skew from matplotlib import pyplot as plt
Then create a small function that will allow us to straighten the image:
def deskew(_img): image = io.imread(_img) grayscale = rgb2gray(image) angle = determine_skew(grayscale) rotated = rotate(image, angle, resize=True) * 255 return rotated.astype(np.uint8)
This function is quite simple. The deskew library indeed encapsulates all the calls necessary for recovery … except perhaps the conversion to gray levels which is an essential step to detect tilt angles.
Then let’s create a small function to test and see the result (with matplotlib ) of our adjustments:
def display_avant_apres(_original): plt.subplot(1, 2, 1) plt.imshow(io.imread(_original)) plt.subplot(1, 2, 2) plt.imshow(deskew(_original))
The result
I took a few tilted images to test the result. A first test with a tilt of 35 degrees clockwise:
display_avant_apres('img_35h.jpg')
Then with an inclination of 15 degrees counterclockwise:
display_avant_apres('img_15ah.jpg')
The result seems rather conclusive, doesn’t it? let’s try to use Tesseract now on this image:
io.imsave('output.png', deskew('img_35h.jpg')) image1 = Image.open('output.png') pytesseract.image_to_string(image1, lang='fra')
'Bonjour'
And There you go ! the result is the expected one.
You want to automate this type of task with the RPA Blue Prism … take a look at this article.
The video below shows the solution in action: | http://aishelf.org/deskew/ | CC-MAIN-2021-31 | refinedweb | 514 | 57.27 |
Experience your
30 day trial
now!
Today we welcome our guest blogger CRM MVP Darren Liu from the Crowe Horwath company.
Have you ever been asked by someone to get a list of contacts having birthdays during a certain time period from CRM? If so what have you done to perform this task? Within the application, birthdays are tracked on Contact records as a single date (including year). This causes problems when searching for birthdays in a certain time period as the birth date is evaluated including the year. To illustrate, consider the following example:
· John Dole, 10/1/1980 · Adam Smith, 9/1/1970 · Mark Francis, 10/10/1960
· John Dole, 10/1/1980
· Adam Smith, 9/1/1970
· Mark Francis, 10/10/1960
Within CRM, searching for date is done by range. There is no easy way to identify from the above contacts all those having birthday in October as any range you choose will include the year. Wildcard functions on date fields are not a workable solution.
There are several solutions to this problem including JavaScript to parse birthday on the onChange event, a custom report or a plug-in. The desired functionality is to be able to search by birth month, birth day, and/or birth year, allowing the user to quickly identify all birthdays in a certain time period.
In this blog, I will show you how to use a pre plug-in to parse the birthday field into day, month and year. This way, the users will able to perform searches using Advanced Find. I have chosen the plug-in approach because it will help me parse the birthday field not only when the users update the birthday on the contact form but also when updating the birthday through the CRM web service for data imports and data integration.
Implement the pre plug-in
1. Create New Attributes
Create three new attribute on the Contact entity form in CRM. After creating the new attributes, publish the Contact customization.
Display Name
Schema Name
Type
Searchable
Values
Birth Month
new_birthmonth
Picklist
Yes
Jan = 1, Feb = 2, Mar = 3, Apr = 4, May = 5, Jun = 6, Jul = 7, Aug = 8, Sept = 9, Oct = 10, Nov = 11, Dec = 12
Birth Day
new_birthday
Int
Min Value = 1
Max Value = 31
Birth Year
new_birthyear
Min Value = 1900
Max Value = 9999
2. Create pre plug-in using Visual Studio
Create a plug-in project name Crm.Plugin, copy and paste the following code to your Plug-in project.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
namespace Crm.Plugin
{
public class MonthDayYearContactPlugin : IPlugin
{
public void Execute(IPluginExecutionContext context)
{
DynamicEntity entity = null;
if (context.InputParameters.Properties.Contains(ParameterName.Target) &&
context.InputParameters.Properties[ParameterName.Target] is DynamicEntity)
entity = (DynamicEntity)context.InputParameters[ParameterName.Target];
if (entity.Name != EntityName.contact.ToString()) { return; }
}
else
return;
try
if (entity.Properties.Contains("birthdate"))
{
CrmDateTime _birthdate = (CrmDateTime)entity["birthdate"];
if (_birthdate.IsNull)
{
entity["new_birthday"] = CrmNumber.Null;
entity["new_birthmonth"] = Picklist.Null;
entity["new_birthyear"] = CrmNumber.Null;
}
else
DateTime birthdayValue = _birthdate.UserTime;
entity["new_birthday"] = new CrmNumber(birthdayValue.Day);
entity["new_birthmonth"] = new Picklist(birthdayValue.Month);
entity["new_birthyear"] = new CrmNumber(birthdayValue.Year);
}
catch (Exception ex)
throw new InvalidPluginExecutionException("An error occurred in the Month, Day, Year Plug-in for Contact.", ex);
}
}
3. Register the plug-in The last step is to register the plug-in. To register the plug-in, you may use the Plug-in Registration tool from the MSDN Code Gallery. After the assembly is uploaded, you need to associate the following steps to the plug-in:
Message: Create
Primary Entity: contact
Filtering Attributes: birthdate
Eventing Pipeline Stage of Execution: Pre Stage
Execution Mode: Synchronous
Triggering Pipeline: Parent Pipeline
Message: Update
Primary Entity: contact
Filtering Attribute: birthdate
Eventing Pipeline Stage of Execution: Pre Stage
Execution Mode: Synchronous
Triggering Pipeline: Child Pipeline
Summary
That’s all there is to it! The users will now be able to use Advanced Find to quickly identify their contacts birthday in a certain time period from now on. For the existing contacts previously stored in CRM, you will need to write a one-time SQL script to update the birthday fields in the MSCRM database in order for CRM to return the correct data back to the users. Hopefully this will help you on your next CRM project.
Cheers,
Darren Liu
thanks,I have Created my List,good job.
We luv to hear about success. Thanks for sharing! :o)
Hi there! My interest is in the birth date 10/10/60. That is my birthday and I noticed that in your example, Mark Francis has the same. Is he a real person or just an example, because I have been searching for nearly a year for other people that turn 50 on 10/10/10 because I think it would be interesting to create a party somewhere. I am not in the market for software, but just was interested to know if Mark was a real person and if that is really his birthday. If so, he would be a candidate for the party. I know this is a little off the wall, but if you can be of any help it would be greatly appreciated. Thank you for your time and I hope you are having a great day!
Brenda Mende
Bluskeyesonly1@yahoo.com
Hi Brenda,
Sorry to tell you that Mark in this example is not a real person.
Hoho, it works, thank u so much.
Thank you for sharing.
Just wondering why you need to create plugin for both parent and child pipeline? | http://blogs.msdn.com/b/crm/archive/2009/02/27/creating-a-birthday-contact-list.aspx | CC-MAIN-2013-48 | refinedweb | 927 | 57.27 |
Given the code below public class ThreadDemo extends Thread[ public void run(){ System.out.println("Thread started"); try{ Thread.sleep(20000); //20 seconds sleep System.out.println("I am Back from my sleep"); } catch(InterruptedException e){ System.out.println("I got Interrupted"); } } } Which of the following statements are true? ( ANY ONE ) A.Exactly 20 seconds after the start method is called "I am Back from my sleep" be printed. B.We can be sure that atleast after 20 seconds elapsed, "I am Back from sleep" will be printed. C.The delay between output "Thread started" and "I am Back from sleep" is less or more than 20 seconds. D.None of the above. | http://www.coderanch.com/t/219411/java-programmer-SCJP/certification/Reg-Threads-Valiveru-exam | CC-MAIN-2015-48 | refinedweb | 113 | 70.09 |
I'm reviewing Bugzilla bugs in preparation of the Tomcat 3.2.2 release.
Bugzilla 160 has been open since Tomcat 3.1 and it looks like its real and
that it violates the Servlet 2.2 spec.
I want to make sure I am correctly interpretting the spec before I dig too
deep. I'll send a similar message to the servlet api mailing list.
1) HttpServletRequest.getRequestedSessionId() should return the session
that arrived with the request. This might not match the session id returned
by HttpServletRequest.getSession()because the session might have been
invalidated or timed out, etc. So far so good. What isn't clear (at least
from reading the code) is should calling HttpServletRequest.getSession()
modify the requested session id. I think that it shouldn't but the code in
RequestImpl.java updates the requested session id. A quick look at the
Tomcat 3.3 version appears to work as I expected it to.
2) A related question, HttpServletRequest.isRequestedSessionIdValid() is
implemented as follows:
HttpSession session = (HttpSession)request.getSession(false);
return (session != null);
If this method is called *before* the invoking servlet calls
getSession(true) then it will correctly determine if the *requested* session
id was valid. After that it will always return true. This seems wrong
because specification clearly states this method determines if the requested
session id was valid. Tomcat 3.3 appears to suffer from this problem. | http://mail-archives.apache.org/mod_mbox/tomcat-dev/200103.mbox/%3CJFEMIAGAMJPJFLEODNEEGEOEDDAA.marc.saegesser@apropos.com%3E | CC-MAIN-2014-41 | refinedweb | 234 | 61.63 |
A question about the FileTimeToLocalFileTime function turned out to be something else
Raymond
A customer reported that their program was running into problems with the
FileTimeToLocalFileTime function. Specifically, they found that the values reported by the function varied wildly for different time zones. Even though the two time zones were only a few hours apart, the results were hundreds of centuries apart.
The customer did a very good job of reducing the problem, providing a very simple program that illustrated the problem. I cleaned it up a bit.
#include <windows.h> #include <stdio.h> int main(int argc, char **argv) { FILETIME ftUTC = { 0, 0 }; FILETIME ftLocal; SYSTEMTIME stLocal; double vLocal = 0; BOOL result = 0; printf("ftUTC = {%d,%d}\n", ftUTC.dwHighDateTime, ftUTC.dwLowDateTime); result = FileTimeToLocalFileTime(&ftUTC, &ftLocal); printf("FT2LFT returns %d\n", result); printf("ftLocal = {%d,%d}\n", ftLocal.dwHighDateTime, ftLocal.dwLowDateTime); FileTimeToSystemTime(&ftLocal, &stLocal); printf("stLocal = %d.%d.%d %02d:%02d:%02d\n", stLocal.wYear, stLocal.wMonth, stLocal.wDay, stLocal.wHour, stLocal.wMinute, stLocal.wSecond); SystemTimeToVariantTime(&stLocal, &vLocal); printf("vLocal = %f\n", vLocal); return 0; }
According to the customer, “When we run the program with the current time zone set to UTC-8, we get the correct values, but if we run it with the time zone set to UTC+8, we get the wrong values. We expect that a zero starting file time should result in a zero variant time.” They also provided two screen shots, which I converted to a table.
Okay, first of all, let’s see which is actually correct and which is incorrect.
The
FileTimeToLocalFileTime function subtracts or adds eight hours. Since the starting time was zero, the result in the case of UTC-8 is an integer underflow, which prints as negative numbers if you use the
%d format. (Note to language lawyers: Don’t get all worked up about stuff like “passing an unsigned integer to the
%d format results in undefined behavior.” I’m talking about Win32 here, and I’m trying to explain observed behavior, not justify theoretical behavior.)
The value
{67,237191168} corresponds to
0x00000043`0e234000, which has the signed decimal value
288000000000 which is exactly equal to
8 * 10000 * 1000 * 3600, or eight hours after zero. On the other hand, the value
{-68,-237191168} corresponds to
0xffffffbc`f1dcc000 which has the signed decimal value
-288000000000 which is exactly equal to
-8 * 10000 * 1000 * 3600, or eight hours before zero.
So far, the numbers match what we expect. Although we do have an issue that in the UTC-8 case, the value underflowed to a very large positive number.
Next, we convert
ftLocal to
stLocal. The easy case is UTC+8, where the timestamp of eight hours after zero is converted to January 1, 1601 at 8am, because the zero time for
FILETIME is January 1, 1601 at midnight. This is spelled out in the very first sentence of the documentation for the
FILETIME structure.
Okay, now the hard case of UTC-8. The timestamp
0xffffffbc`f1dcc000, if interpreted as an unsigned number, corresponds to May 27, 58456 (at around 9:30pm), but if interpreted as a signed number, corresponds to 4pm December 31, 1600. The
FileTimeToSystemTime function rejects negative timestamps, return
FALSE and
ERROR_INVALID_PARAMETER. Since the call failed, the value in
stLocal is undefined, and here, it just contains uninitialized garbage. (Because “uninitialized garbage” is a valid value for “undefined”.)
The next thing we do is convert the
stLocal to a variant time. As noted in the documentation, the zero time for variant time is December 30, 1899. (Required reading: Eric’s Complete Guide to VT_DATE, wherein the insanities of variant time are investigated.) Again, the case of UTC+8 is easy: January 1, 1601 is many many days before December 30, 1899, apparently −109205 days. I’m going to take this for granted and not check the math, because the goal is not to double-check the results but rather to explain why the results are what they are. On the other hand, the (garbage) date of the zeroth day of the 15281th month of the year 34453 is not valid, and the
SystemTimeToVariantTime fails because the parameter is invalid. In this case, the output variable
vLocal is left unchanged, and it continues to have the value zero, the value it was initialized with.
Therefore, the fact that in the so-called “correct” case the value of
vLocal is zero has nothing to do with the functioning of the API, but rather has everything to do with the line
double vLocal = 0;
at the start of the program. Change the line to
double vLocal = 3.14159;
and the result in the “correct” case will be 3.14159.
The conclusion here is that the so-called “incorrect” result is actually correct, and the so-called “correct” result is just an accident. The customer is under the mistaken impression that a zero
FILETIME matches a zero variant time, but they do not. The zero points for the two time formats are quite different. The problem was exacerbated by the fact that the test program didn’t check the return values of
FileTimeToSystemTime or
SystemTimeToVariantTime, so what it thought were the values set by those two functions were actually just the uninitialized values passed into the respective functions. | https://devblogs.microsoft.com/oldnewthing/20150306-00/?p=44523 | CC-MAIN-2019-43 | refinedweb | 878 | 52.6 |
Provide control over an open file
#include <sys/types.h> #include <unistd.h> #include <fcntl.h> int fcntl( int fildes, int cmd, ... );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.:
The file status flags (see open() for more detailed information) are:
The file access modes are:.
The only defined file descriptor flag is:
If a lock can't be set, fcntl() returns immediately.
The flock structure contains at least the following members:.
The following functions ignore locks:
-1 if an error occurred (errno is set). The successful return value(s) depend on the request type specified by arg, as shown in the following table:
/* *; } | http://www.qnx.com/developers/docs/qnxcar2/topic/com.qnx.doc.neutrino.lib_ref/topic/f/fcntl.html | CC-MAIN-2022-27 | refinedweb | 115 | 61.43 |
Reference counting is something of a lost art. I, for one, hope it stays that way. If there was a way to mess up counting, I was more than up to the task of finding it. That's only a slight exaggeration.
So I very much appreciate garbage collected languages like Dart. Of course, garbage collection can only do so much—I promise you that it is still possible to build web applications that consume insane amounts of memory. In that vein, tonight I investigate sharing implementors in the bridge pattern.
The Gang of Four book describes Handle Body idiom for tackling this in C++. But that's for my old nemesis reference counting. In Dart, I have to think factory constructor singletons would be an easy way to tackle this. For example, consider the wildly memory intensive
DrawingApi1class:
class DrawingApi1 implements DrawingApi { void drawCircle(double x, double y, double radius) { print( "[DrawingApi1] " "circle at ($x, $y) with " "radius ${radius.toStringAsFixed(3)}" ); } }Clearly, I do not want that class to instantiate new objects each time a
Circlerefined abstraction is created:
Even ifEven if
List<Shape> shapes = [ new Circle(1.0, 2.0, 3.0, new DrawingApi1()), new Circle(0.0, 6.0, 1.0, new DrawingApi1()), new Circle(2.0, 2.0, 1.5, new DrawingApi1()), new Circle(5.0, 7.0, 11.0, new DrawingApi2()), new Circle(1.0, 2.0, 3.0, new DrawingApi1()), new Circle(5.0, -7.0, 1.0, new DrawingApi2()), new Circle(-1.0, -2.0, 5.0, new DrawingApi1()) ];
DrawingApi2is significantly more lightweight than
DrawingApi1, enough of the latter will drag the browser / system to a halt. But a simple singleton factory constructor solves that neatly:
class DrawingApi1 implements DrawingApi { static final DrawingApi1 _drawingApi = new DrawingApi1._internal(); factory DrawingApi1()=> _drawingApi; DrawingApi1._internal(); void drawCircle(double x, double y, double radius) { /* ... */ } }The class variable
_drawingApiis constructed once from a private constructor. The regular
DrawingApi1()is a factory constructor that only returns that one
_drawingApireference. And the internal constructor is a simple, no-argument private constructor.
The only case that does not cover is when the number of references to a
DrawingApi1instance goes to zero. The start-at-zero case is handled automatically for me by Dart. The private
_drawingApiclass variable is not assigned until the constructor is invoked for the first time—that is just thanks to Dart's lazy instantiation. So no memory will be used unless and until the first
DrawingApi1shape is drawn.
If I really needed to reclaim memory, I might try a handle-body kind of thing. But I'd probably get it wrong. So instead I use mirrors (because mirrors are always easier than reference counting). If I switch to constructing shapes with the class name instead of an instance, the individual shapes might look like:
TheThe
List<Shape> shapes = [ new Circle(1.0, 2.0, 3.0, DrawingApi1), new Circle(0.0, 6.0, 1.0, DrawingApi1), new Circle(2.0, 2.0, 1.5, DrawingApi1), new Circle(5.0, 7.0, 11.0, DrawingApi2), new Circle(1.0, 2.0, 3.0, DrawingApi1), new Circle(5.0, -7.0, 1.0, DrawingApi2), new Circle(-1.0, -2.0, 5.0, DrawingApi1) ];
Circleconstructor still redirects the last parameter, which is now a
Type, to the abstraction superclass:
class Circle extends Shape { double _x, _y, _radius; Circle(this._x, this._y, this._radius, Type drawingApi) : super(drawingApi); // ... }Finally, the constructor in the
Shapeabstraction can
putIfAbsent()on the cache:
import 'dart:mirrors' show reflectClass; abstract class Shape { DrawingApi _drawingApi; static MapIf I want to clear that cache after all
_drawingApiCache = {}; Shape(Type drawingApi) { _drawingApi = _drawingApiCache.putIfAbsent( drawingApi, ()=> reflectClass(drawingApi).newInstance(new Symbol(''), []).reflectee ); } // ... }
Shapeinstances have been removed, I can use a simple
clear():
abstract class Shape { // ... void reset() { _drawingApiCache.clear(); } // ... }The rest remains unchanged from previous nights. The bridge between abstraction (shape) and implementor (a drawing API) is used in the
draw()method in the refined abstraction:
class Circle extends Shape { // ... void draw() { _drawingApi.drawCircle(_x, _y, _radius); } // ... }I draw two conclusions from this. First, I enjoy mirrors far more than is healthy. A handle-body class would have involved counting, but might have solved the last reference removal just as well (and possibly clearer). Second, singletons seem to solve the reference count for nearly all use-cases.
Play with the code on DartPad:.
Day #78 | https://japhr.blogspot.com/2016/01/sharing-implementors-is-easy-in-bridge.html | CC-MAIN-2017-43 | refinedweb | 726 | 68.06 |
I still believe that an immutable nsIString interface coupled with appropriate
implementations could be a huge win for us in terms of both space and time.
There would need to be at least 4 implementations to make this work:
- nsUnicharString for double-byte encoding,
- nsCString for single-byte encoding,
- nsSubString would manage a lengh and offset into another nsIString to avoid
copying,
- nsConcatenatedString would manage a sequence of nsIStrings, treating them as a
single concatenated string.
To determine whether my hypothesis is correct, I think we can instrument
nsString and nsCString to gather statistics that indicate how many copies of
strings we make in the process of running our app. Specifically:
- Count the number of times each nsString constructs a char/PRUnichar array.
This is often done when passing them to IDL-generated interfaces. (This number
could be completely eliminated with nsIString.) [ToNewString, ToNewCString,
ToNewUnicode, ToCString]
- Count the number of times we construct nsStrings from char/PRUnichar arrays.
This is often done when we want to manipulate strings that come in from
IDL-generated interfaces. (Some number of these could be eliminated with
nsIString.) (How can we break down first-time constructions from copies -
histogram?)
- Count the number of times we assign the character sequence in a string. Also
count the percentage of strings which are actually assigned. (This number would
indicate the number of additional nsIStrings which would need to be created due
to immutability.) [SetString, Assign, operator=]
- Count the number of substring operations done on nsStrings. (This number could
be replaced by an allocation of an nsSubString object.) [SetLength, Truncate,
Trim, Left, Mid, Right, Cut]
- Count the number of concatenation operations done on nsStrings. Also count the
percentage of strings which are concatenated. (This number could be replaced by
an allocation of an nsConcatenatedString object, saving space.) [operator+,
operator+=, Append, Insert]
- Count the number of mutation operations done on nsStrings. Also count the
percentage of strings which are mutated. (This number would indicate how often
an actual string buffer (e.g. the existing nsString implementation) would
continue to be needed.) [SetCharAt, ToLowerCase, ToUpperCase, StripChars,
StripWhitespace, ReplaceChar, ReplaceSubstring, CompressSet, CompressWhitespace]
Once we have these counts, we can see can do some analysis to determine what
sort of ramifications nsIString might have: Will we allocate far fewer strings
because they're shared more? Will we need to allocate far more substring objects
because they're mutated too often? What sort of space might we expect to save
due to more sharing. What sort of space might we expect to loose due to more
copies made as a result of mutation.
Right now we're in the dark.
Just counting constructors wont be good I think. We should factor in how many
are destroyed to get a figure of how many will exist. That will influence the
space issue.
n.b. that vidur & troy are exploring some kind of BSTR-like stuff to reduce
copies in layout. Not sure if their stuff would cross interface boundaries...
adding myself to cc.
I have wanted this for a long while. With this we could get rid of the
nsXPIDLCString. Adding myself to cc.
We could get rid of *some* uses of nsXPIDL(c)String -- those where the string
is immutable. If the caller is going to manipulate the string anyway then it
doesn't buy anything.
Another plan for getting rid of |nsXPIDL[C]String| is to roll its functionality
into |nsString|. See related bugs
<> -- alecf
<> -- scc
I'm tinkering with instrumenting nsStr with the stack walking code n' stuff to
see what intersting statistics I can produce.
Ok, made a first cut at gathering some stats. It's not everything that you asked
for, warren, but most of the ones that were really easy to pick up. The data is
below for simple startup & shutdown with as the homepage.
For each operation, I captured the number of times the operation occurred, the
total number of characters (one- or two-byte) that were involved in the
operation, and the mean and standard deviation of the number of characters per
operation (cuz I knew warren'd ask).
For ctors and Assign operations, I tried to deduce when copy-on-write (COW)
sharing would and would not occur; e.g., "nsString::nsString(const nsStr&) COW"
indicates that the incoming nsStr's buffer could be shared. "NOCOW" means that
the incoming nsStr's buffer was incompatible, and would need to be inflated to
two-byte.
ns[C]String::Append(const nsStr&) sometimes needs to inflate[deflate] the
inbound nsStr, so I factored out INFL[DEFL] appends from normal appends. (This
may be indicative of how useful a segmented buffer implementation would be.)
------ Characters ------
Operation Count Total Mean StdDev
nsCString::Append(char) 3081 3081 1 +/- 0
nsCString::Append(const char*) 33624 704152 21 +/- 85
nsCString::Append(const nsCString&) 1317 17939 14 +/- 11
nsCString::Append(const nsStr&) DEFL 1213 22236 18 +/- 17
nsCString::Assign(const PRUnichar*) 62 3553 57 +/- 19
nsCString::Assign(const char*) 2139 36108 17 +/- 22
nsCString::Assign(const nsStr&) COW 85 1720 20 +/- 4
nsCString::Assign(const nsStr&) NOCOW 7217 551108 76 +/- 48
nsCString::Cut() 570 5015 9 +/- 5
nsCString::ToNewCString 7494 357502 48 +/- 26
nsCString::ToNewUnicode 64 3559 56 +/- 21
nsCString::nsCString() 35033 0 0 +/- 0
nsCString::nsCString(const PRUnichar*) 62 3553 57 +/- 19
nsCString::nsCString(const char*) 105 5971 57 +/- 68
nsCString::nsCString(const nsCString&) COW 7655 364331 48 +/- 26
nsCString::nsCString(const nsStr&) NOCOW 6896 230701 33 +/- 36
nsString::Append(PRUnichar) 153883 153883 1 +/- 0
nsString::Append(char) 982 982 1 +/- 0
nsString::Append(const PRUnichar*) 31627 676237 21 +/- 202
nsString::Append(const char*) 32759 816672 25 +/- 409
nsString::Append(const nsStr&) 11694 71151 6 +/- 8
nsString::Append(const nsStr&) INFL 236 290 1 +/- 1
nsString::Append(const nsString&) 19554 292897 15 +/- 25
nsString::Cut() 4897 68723 14 +/- 228
nsString::Insert(PRUnichar) 1383 1383 1 +/- 0
nsString::Insert(const char*) 70 140 2 +/- 0
nsString::SetCharAt() 4591 4591 1 +/- 0
nsString::ToNewCString 2351 56711 24 +/- 23
nsString::ToNewUTF8String 4204 169205 40 +/- 41
nsString::ToNewUnicode 3674 56392 15 +/- 13
nsString::nsString() 133552 0 0 +/- 0
nsString::nsString(const PRUnichar*) 1055 14819 14 +/- 8
nsString::nsString(const char*) 1953 253280 130 +/- 1671
nsString::nsString(const nsStr&) NOCOW 230 6670 29 +/- 52
nsString::nsString(const nsString&) COW 10843 222664 21 +/- 526
Created attachment 5736 [details]
nsStringStats.h
Created attachment 5737 [details] [diff] [review]
diffs to xpcom/ds to implement string stats
Attached extra files and patches required to gather statistics.
Created attachment 5739 [details] [diff] [review]
better diffs.
Here's another run, with more functions accounted for, and visiting more sites:
------ Characters ------
Operation Count Total Mean StdDev
nsCString::Append(char) 8600 8600 1 +/- 0
nsCString::Append(const char*) 157749 2465740 16 +/- 51
nsCString::Append(const nsCString&) 2348 27977 12 +/- 10
nsCString::Append(const nsStr&) DEFL 3549 59550 17 +/- 17
nsCString::Assign(const PRUnichar*) 347 15652 45 +/- 14
nsCString::Assign(const char*) 5762 185482 32 +/- 43
nsCString::Assign(const nsStr&) COW 152 2978 20 +/- 3
nsCString::Assign(const nsStr&) NOCOW 33221 2086625 63 +/- 45
nsCString::Cut() 3306 26758 8 +/- 5
nsCString::SetCharAt() 196 196 1 +/- 0
nsCString::ToNewCString 35072 1739748 50 +/- 30
nsCString::ToNewUnicode 375 15521 41 +/- 18
nsCString::nsCString() 133167 0 0 +/- 0
nsCString::nsCString(const PRUnichar*) 347 15652 45 +/- 14
nsCString::nsCString(const char*) 496 57162 115 +/- 93
nsCString::nsCString(const nsCString&) COW 35300 1747820 50 +/- 30
nsCString::nsCString(const nsStr&) NOCOW 37316 1381001 37 +/- 42
nsString::Append(PRUnichar) 215192 215192 1 +/- 0
nsString::Append(char) 1996 1996 1 +/- 0
nsString::Append(const PRUnichar*) 146947 3483496 24 +/- 152
nsString::Append(const char*) 186147 3901793 21 +/- 195
nsString::Append(const nsStr&) 44255 318232 7 +/- 34
nsString::Append(const nsStr&) INFL 405 1578 4 +/- 4
nsString::Append(const nsString&) 100415 1785264 18 +/- 36
nsString::Assign(PRUnichar) 27116 27116 1 +/- 0
nsString::Assign(char) 322 322 1 +/- 0
nsString::Assign(const PRUnichar*) 28497 464960 16 +/- 52
nsString::Assign(const char*) 88503 3087143 35 +/- 281
nsString::Assign(const nsStr&) COW 133837 1256708 9 +/- 35
nsString::Assign(const nsStr&) NOCOW 11782 83533 7 +/- 16
nsString::Cut() 31814 578205 18 +/- 249
nsString::Insert(PRUnichar) 8674 8674 1 +/- 0
nsString::Insert(const char*) 1461 2932 2 +/- 0
nsString::SetCharAt() 41303 41303 1 +/- 0
nsString::ToNewCString 8461 224481 27 +/- 36
nsString::ToNewUTF8String 28337 1151229 41 +/- 43
nsString::ToNewUnicode 3177 53286 17 +/- 12
nsString::nsString() 705595 0 0 +/- 0
nsString::nsString(const PRUnichar*) 4675 83960 18 +/- 17
nsString::nsString(const char*) 16266 494636 30 +/- 651
nsString::nsString(const nsStr&) NOCOW 490 39884 81 +/- 114
nsString::nsString(const nsString&) COW 33812 515520 15 +/- 329
TOTAL 2326782 27657905
Here, 12.7% of the characters fall into the COW category. On a previous run for
just the mozilla.org page, I got 14.4%. Seems like we can safely assume
that we can save >10% by doing COW.
Three things to test:
(1) put a flag in |nsStr| to simulate COW semantics ... "this is a reference"
then charge subsequent mutators with the cost of an allocation/copy
this will help us better determine the value of adding COW
(2) count the number of times a string had mutators applied to it, this will
help us better determine the value of adding, e.g., an |nsIImutableString|
(3) put a time in the string, and whenever it changes size or when it gets
destroyed, add its duration to a bucket for that size. This will help
us better determine the value of adding, e.g., arena based allocation
for some capacities.
*** Bug 28842 has been marked as a duplicate of this bug. ***
*** Bug 26435 has been marked as a duplicate of this bug. ***
Interesting news! I implemented number (2) to determine how many strings are
mutated. Here are the results:
Allocated strings = 833582
Mutated strings = 551607
Unmutated strings = 281252
That's over 50%!! This was for a run visiting about 10-15 pages, including
tinderbox, a build log, cnn, yahoo, abcnews and others.
If you add my numbers up you'll see that there are 700+ strings unaccounted
for. This is because I only determine the number of mutated/unmutated strings
when they're destroyed, so the remining ones must be leaks.
Here's another longer run (60%):
Allocated strings = 1231811
Mutated strings = 777911
Unmutated strings = 467373
and here's one bringing up my mailbox (with 4000+ messages), and forwarding a
message with a lot of extra typing added to it (39%):
Allocated strings = 2170221
Mutated strings = 1594744
Unmutated strings = 621191
Immutable strings should be a huge win!
That's what I had informally determined as well, that immutable strings would
be a big win
And that's not even counting char* and PRUnichar* strings that are manually
alloc'd and are never in nsStrings. Right?
I instrumented |ns[C]String| to determine the amount of character copying and the
number of allocations that would be saved by implementing a Copy-On-Write [COW]
mechanism without necessarily changing the current interface. Here is a sample
run, typical of my results to date.
un-shared work: 15313192
COW work: 1183682
un-shared allocations: 416265
COW allocations: 460985 or about 10.74% more than un-shared
allocations
Yes, we save a lot on copying characters, but we actually end up doing _more_
allocations. The reason? One explanation is callers copying strings and making
small modifications in extant string variables explicitly for this purpose. So,
for example, I have a string variable into which I copy another string (the
allocation and copying are deferred), but now I modify it (and am charged for the
allocation, and some fraction of the copying, depending on the operation) and do
something with it, like compare. Then I copy another string into it (the current
value is released, but the allocation and copy are deferred again), and then, as
before, immediately make a change... now I'm charged for an allocation that I
wouldn't have been in the non-COW implementation.
Interesting results.
Created attachment 5842 [details] [diff] [review]
Here is a patch containing the changes I made to measure COW efficacy
Created attachment 5856 [details] [diff] [review]
diffs for mutated/unmutated accounting (in addition to Chris' diffs)
One comment about SCC's analysis: the 2nd copy would not necessarily require a
subsequent allocation. We can implement COW so that the underlying buffer is
retained until the string is deleted or resized. The original buffer could be
reused in the 2nd copy, so that the 2nd allocation (may not) be neccessary. Of
course a great deal depends on the size of the strings being operated upon.
With respect to the notion of a segmented string implementation: note that
|GetUnicode| is called in more than a thousand places. |GetBuffer| is called
less, but still quite a bit.
<>
<>
Both are obstacles to implementing a segmented string since callers expect the
resulting pointer to point to the entire buffer, and they do math with it or pass
it to things expecting an entire string.
I agree, Scott. It makes you wish we had iterators, doesn't it?
I did some more analysis... of how many strings have GetBuffer or GetUnicode
called for them. Here's the answer:
Allocated strings = 756941
Mutated strings = 521389 (68%)
Unmutated strings = 245669 (32%)
Contiguous buffers = 140836 (18%)
This was for visiting mozilla.org, cnn.com, abcnews.com, usatoday.com.
GetBuffer and GetUnicode were only called for 18% of the strings. So I think a
non-contiguous buffer implementation could still be a win. I didn't count how
many times GetBuffer/GetUnicode were called for the same string, but that would
be easy to add.
On another note... I must have been on crack when I reported the percentages
for unmutated strings. For the 3 runs I listed above, the percentages are
33.74%, 37.94% and 28.62% respectively. And for the above run, 32%. Still a
win, although not quite as spectacular as first reported.
P.S. My GetBuffer/GetUnicode analysis doesn't include places in the code that
use mStr directly, so it's an upper bound. If there's a critical place in the
code that uses mStr, then my numbers could be completely off.
I am posting the following set of recommendations to this bug to keep external
developers informed of the direction in which we are heading. The main players
in this impending change are already, as far as I know, all on the same page.
Rick Gessner <rickg@netscape.com> recently sent out his recommendations---which
I hope he will also post to this bug---which touch on the same themes. Rick's
recommendations paint a fairly good picture of the new world. I still think
the following evaluation is valuable, because it goes into detail as to what the
actual changes are/should-be, and _why_ those particular changes are important.
We want to move to a world where string clients can select from among a range of
implementations that embody different implementation strategies, e.g., a
general purpose string such as we have now, and specific-use implementations
like an immutable string that optimizes allocations, and a segmented string that
minimizes character copying over editing operations on very large datasets.
These new goals impose new requirements on our current string interfaces. Any
changes we make to the current interface must be source compatible with extant
clients, or we must be willing to pay the penalty of updating callers.
Note: our new goals fall out of our experiences using strings in our
application. They differ significantly from our original goals (which were all
about revealing the underlying implementation to clients for performance) and
so none of these recommendations can or should be taken as a criticism of the
current interface.
Specific recommendations fall into several categories (note: these are not the
the recommendations ... these are the categories). Very roughly in order of
importance with respect to this effort:
[A] removing from the interface any visible members that compromise the
abstraction allowing different underlying representations, else clients
won't be satisfied by alternate implementations
[B] removing from the interface any routines that aren't specifically about
manipulating the underlying representation, else alternate implementations
must re-implement identical functionality
[C] removing from the interface any i18n sensitive functionality, though
mostly instances of this recommendation will be covered by [B] above
[D] removing from the interface unused, unneeded, or unconventionally located
functionality, to reduce the burden on alternate implementations, and to
generally simplify
[E] adding to the interface any support machinery needed to enable changes
falling into one of the categories above, or simply to allow multiple
implementations at all, e.g., |virtual|
I believe rickg and I are already very much in agreement on these points. We
discussed them at length, and his recent message on redesign notes echoes these
sentiments. It is clear from his recent email messages that he has been
focused on these same key issues.
Here are my specific recommendations:
1 [A] Remove public inheritance from |nsStr|. Access to a specific
underlying buffer representation is prohibitive to alternate
implementations, e.g., a segmented string et al. It is also agreed that
having any public data members is a political impediment to crossing
XPCOM boundaries. According to rickg, visible inheritance from |nsStr|
is not exploited heavily, and should be easily removed. This is arguably
the most important thing we can do to enable further enhancements to our
string implementations and uses.
2 [A] |GetUnicode| and |GetBuffer| impose a prohibitive burden on
implementations in a multiple implementation world. As rickg points out,
this is another reason to add iterators. Unfortunately, these two
routines are very heavily used.
3 [E] Make the string interface abstract to allow multiple implementations.
We were already paying for a vtable, so no extra space requirements are
expected. The performance impact should be minimal.
4 [E] Split the abstract interface into layers encouraging read-only
implementations, e.g., an immutable string
5 [BCD] Make narrowing/widening an explicit operation done by constructors.
Do not allow implicit conversion in append and assign operations. Tests
show that we are not exploiting the `double interface' of string very
much, and this is good. Note that like |ToUpperCase| (et al)
functionality mentioned below, encoding conversions are properly in the
domain of i18n, and duplicating the functionality at the low-level in
string is suboptimal.
6 [BDE] Either remove operator overloading from the abstract interface, or
implement it conventionally, that is: non-virtual inlines using only the
abstract signatures for |Append| and |Assign|. Implement |operator+=()|
and |operator=()| as members; implement |operator+()| and relations as
non-members. Virtual assignment operators must be written carefully to
avoid slicing.
7 [BCDE] Remove |ToUpperCase|, |ToLowerCase|, |IsASCII|, |IsUnicode|,
|IsSpace|, and |IsAlpha| from the interface. Of these, only |ToLowerCase|
is heavily used, and i18n functionality like this must be pushed up into
the i18n layer, where, coincidentally, this functionality already happens
to exist.
8 [D] Remove (the little used) |ToNewString| from the interface. This
functionality is already available in the form of the copy-constructor.
In a multiple implementation world, the user will typically need to
select a specific implementation, in any case.
9 [BCD] Remove |IsOrdered| and |BinarySearch| from the interface. These are
not
general purpose routines, and can easily be implemented outside the
string class if they are deemed still needed.
10 [BCD] |EqualsIgnoreCase| and the |Compare| functions when the
|aIgnoreCase| parameter is true are problematic just as the other i18n
dependent routines are. Unfortunately, these routines are very heavily
used. Again, they are a burden in a multiple implementation world. They
should be implemented as non-members (based on extant i18n facilities)
that use iterators into the underlying string ... which also implies that
we will need string iterators.
11 [BCD] |ToFloat| and |ToInteger| should be removed from the interface.
Parsing should not be part of the required functionality for multiple
implementations. Given iterators, this functionality could be moved to
a non-member implementation, which, in any case, is again requires i18n
sensitivity. |ToFloat| is not heavily used. |ToInteger| is.
Similarly, the |Append|s that format a float or an integer are i18n
dependent. Some work may be required to provide similar functionality
that is factored into the i18n support.
12 [D] We probably don't need the power to say something like
myStr.Assign(yourStr).Append(herStr).Cut(20, 15);
It makes sense with operators, but we may want to simplify the client
interface with respect to named member functions. The |Assign|, |Append|,
|Insert|, |Cut|, and |SetString|, signatures should be changed to return
|void|.
13 [BCD] Turn the specialized modification and accessor functions |Trim|,
|CompressSet|, |StripChar|, |StripChars|, |StripWhitespace|,
|ReplaceChar|, |ReplaceSubstring|, and |CountChar| into non-member
`algorithms' that can be applied to any implementation.
14 [DE] Given the current copying signatures of |Left|, |Right|, and |Mid|,
they should probably be turned into non-member algorithms writing to an
iterator as well.
15 [E] Add iterators. Several of the points above are eased or solved by the
introduction of reasonable iterators.
16 [AD] Eliminate |nsSubsume[C]Str|. To much implementation knowledge is
currently required to reasonably utilize this in clients, and it presents
a burden to implementations to facilitate.
This is my primary focus at the moment.
fixing summary to better reflect our understanding
mass re-assigning to my new bugzilla account
Well, NEW_STRING_APIS is now switched on. The factoring is accomplished. And
some new implementation exist to solve some problems. We need a replacement for
XPIDL string; we need a COW implementation; we need to deploy the new
implementations. I'm re-summarizing this bug for the work of measuring and
deploying the new implementations.
Putting on nsbeta3 radar. warren say we really need to get this in for PR3, per
beta2 PDT reviews.
Simon, can you add your recent profiling work to this bug?
For everyone else, under discussion is the idea that `chunk' allocating strings
has turned out to be a bigger source of wasted space than it has been a
performance boon.
(oops, too many cc's, Bugzilla is making me remove one to add simon. Sorry dp)
Adding newsgroup postings on string usage:
<news:sfraser-F78927.13360202062000@secnews1.mcom.com>
It seems that nsString::SetCapacity() always buffers the string
size in 64-character chunks - this logic lives down in nsStr::Alloc.
So:
nsString foo;
foo.SetCapacity(1);
foo.Assign('a');
will eat up 128 bytes of heap space.
I have not found a way that I can set the capacity of an nsString
to exactly the length I know is needed. This of course has quite
an impact on bloat.
Seeing this leads me to question how often we actually need to
chunk changes in string length; what proportion of strings actually
change length during their lifetime? My guess is that it's < 50%,
which perhaps suggests that the normal behaviour should be to
not round up string sizes, and that we should have an API that
allows the caller to create a string with, or specify that an
existing string is likely to change length frequently from now
on.
<news:sfraser-0720CE.17500902062000@secnews1.mcom.com>
Some data on the bloat that results from string chunking (recall,
bloat = total memory every allocated, not a runtime high-water mark).
Numbers are K.
Test Allocated Used Waste % waste
--------------------------------------------------------------
Simple browser 2938.00 1548.98 1389.01 47.28%
Complex browser 5839.17 3214.73 2624.44 44.95%
Mail 6232.82 3369.89 2862.93 45.93%
So this chunking almost doubles the amount of memory that our
strings use.
<news:sfraser-D08810.16523102062000@secnews1.mcom.com>
In another post, waterson posed the question of how many strings with
identical contents are allocated, and whether we could use atoms for
these common strings. (He was, I think, talking about string usage in
a particular module/API, but the question can be generalized.)
So I put some debug code in nsStr::Destroy, that dumps out the contents
of strings just before they are deleted, if aDest.mOwnsBuffer == PR_TRUE
(which indicates that the buffer was heap-allocated). Some results are below.
These results can be used to find places is the code the might benefit from
shared strings, or cacheing of frequently used strings. Of course, I have
no data on call sites here.
The data look like this:
848 1 dummy:path
'848' is the count (# strings with these contents), '1' is the character width
(1 for char, 2 for PRUnichar), and the rest is the string itself.
Test 1:
Bring up browser, loading simple text-only HTML page, Quit.
<>
848 1 dummy:path
510 2 true
333 2
303 2 monospace
278 2 component://netscape/layout/element-factory?namespace=http://
277 1 component://netscape/layout/element-factory?namespace=http://
255 2 geneva
205 2 component://netscape/layout/element-factory?namespace=http://
200 1 component://netscape/layout/element-factory?namespace=http://
167 1
159 1
135 2 ISO-8859-1
123 2 UTF-8
117 2 serif
85 2 broadcaster
79 2 menuitem
78 2 menupopup
73 2 <string is a run of 28 spaces>
71 2 vertical
67 2 rdf:
Test 2:
Bring up browser, surf to mozilla.org, tinderbox, bugzilla, load a bug,
open prefs dialog.
<>
1797 2 monospace
1698 2 true
1007 2 serif
879 2 geneva
848 1 dummy:path
371 2 component://netscape/layout/element-factory?namespace=http://
370 1 component://netscape/layout/element-factory?namespace=http://
333 2
322 2 ISO-8859-1
315 1
266 2 vertical
248 2 component://netscape/layout/element-factory?namespace=http://
243 2 white
236 1 component://netscape/layout/element-factory?namespace=http://
176 2 \
167 1
159 2 UTF-8
128 1 css
125 2 never
121 2 black
Test 3:
Bring up browser, open mail-news, load 2 large IMAP folders
(including one of bugzilla mail)
<>
7084 2 UTF-8
4785 2 us-ascii
2809 1 mozilla.org
2808 1 bugzilla-daemon
1304 2 true
1034 2 component://netscape/intl/unicode/decoder?charset=x-imap4-modified-utf7
1032 2 x-imap4-modified-utf7
1029 2 never
987 1 netscape.com
957 2 geneva
948 1 %S Receiving: message headers %lu of %lu
947 1 sfraser
941 2 Bugzilla
894 2 monospace
848 1 dummy:path
500 2
488 2 autostretch
392 2 menuitem
358 2 component://netscape/layout/element-factory?namespace=http://
357 1 component://netscape/layout/element-factory?namespace=http://
Created attachment 12100 [details]
attaching data <dougt@netscape.com> generated...
Created attachment 12101 [details]
more <dougt@netscape.com> data...
Created attachment 12102 [details] [diff] [review]
Here's the patch Doug used to generate this data...
Doug, I attached your patch and data to this bug ... which seems like the
appropriate place. What conclusions can we draw from this data? There are
certain very common strings, true, but this is not enough to know if they are
candidates for being replaced with |nsShared[C]String|s, since we don't know how
they were generated. What do you think? The other bug filed on this is bug
#46738. I commented there as well. We should consider marking that bug either a
duplicate or a blocker for this bug.
marking dependencies, turning this [officially] into a tracking bug for
deploying new string implementations
giving up ancient string bugs to the new string owner. jag, you'll want to sort
through these and see which ones still apply and go with or against the
direction in which you intend strings evolve
This work is no longer relevant, strings have had a new implementation for a while now :-)
If the new strings code needs performance tuning, please file new bugs. | https://bugzilla.mozilla.org/show_bug.cgi?id=28221 | CC-MAIN-2016-30 | refinedweb | 4,584 | 52.9 |
Description editReally, the engine works by converting a template (which is a string, or a file) into a Tcl script, and then running it. Nearly each line of text encountered will be returned as is. The exception is text between <% ... %> which is treated as Tcl code (the eval happens in a safe interp, see Safe Interps). This makes it very flexible and it leaves you freedom of doing what you want, dealing with any data and putting how much code you want in the template (although the template should possibly hold minimum code - according to MVC, just the presentation logic, no code related to controller logic, state persistance, or data-retrieval logic).Also for convenience there is a <%= ... %> for spooling output (the proc _defaultSpool takes care of sending the text to the right place; you can change that: see Preprocessor Commands).
Usage editFirst, let's create a template file (templtest.tmpl):
<table><% for {set i 0} {$i < 4} {incr i} { %> <tr> <td><%= $i %></td> </tr><% } %> </table> <ul> <% foreach item $cityList { %><li><%= $item %> <% } %> </ul>The above template (in HTML language) generates a 4-row table, and an unordered list, taking values from a $cityList variable, that we're eventually going to define.First, let's load the code:
$ tclsh % source TemplaTclnow create a parser instance:
% TemplaTcl::create ttand parse our template:
% tt parseFile templtest.tmplset the variables used in our template:
% tt setVar cityList {Ragusa Ravenna Rieti Rimini Rome Rovigo}and render the template:
% puts [tt render]Here's the output that gets produced:
<table> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> </table> <ul> <li>Ragusa <li>Ravenna <li>Rieti <li>Rimini <li>Rome <li>Rovigo </ul>
Preprocessor commands editRunning in a safe interp, you cannot source your Tcl function library. There's a special markup command: <%@ ... %> that allows you to do special things, i.e., setting parser/interp options. That happens before the parser and before running the interpreter.To source a file you will do:
<%@ source = poo.tcl %>Instead, for including a template:
<%@ include = template.tmpl %>Also for changing the default spooler (mentioned above) do:
<%@ printCommand = puts -nonewline %>(that replaces the _defaultSpool spooler, which allows you to get the content as the return value of TemplaTcl::render).
#!/usr/bin/env tclsh package require Tcl 8.5 # 8.5 required cause the {*} in proc create and proc method package require struct # tcllib required namespace eval ::TemplaTcl { variable obj proc method {name args body} { proc $name [list self {*}$args] "variable obj ; $body" } method create {} { # create and setup a safe interpreter # for running template's tcl code catch {if [interp exists $obj($self:interp)] { interp delete $obj($self:interp)}} set obj($self:interp) [interp create -safe] interp share {} stdout $obj($self:interp) interp eval $obj($self:interp) { proc _defaultSpool {txt {cmd {}}} { global content if {$cmd == "clear"} {set content {}; return} if {$cmd == "get"} {return $content} append content $txt } } uplevel "proc $self {method args} {namespace eval ::TemplaTcl \[list \$method $self {*}\$args\]}" return $self } method parseFile {filename} { # read the template into $rawl - list of chars set fh [open $filename r] set raw [read $fh] close $fh return [$self parse $raw] } method parse {template} { $self _setMode raw #$self setOption printCommand "puts -nonewline" $self setOption printCommand "_defaultSpool" $self setVar * {} set q [::struct::queue] set rawl [split $template {}] foreach ch $rawl { # we work char-by-char :| $q put $ch # max block to compare (<%=) is 3 chars long: if {[$q size] >= 3} { set s3 [join [$q peek 3] {}] set s2 [join [$q peek 2] {}] switch $obj($self:mode) { raw { if {$s3 == "<%="} { # <%= is a shorthand for puts ... $q get 3; $self _setMode code; append obj($self:buf:$obj($self:mode)) "$obj($self:options:printCommand) " continue } elseif {$s3 == "<%@"} { # <%@ is for setting preprocessor options $q get 3; $self _setMode opt; continue } elseif {$s2 == "<%"} { # <% indicates begin of a code block $q get 2; $self _setMode code; continue } } code { if {$s2 == "%>"} { # and %> is the end of code block $q get 2; $self _setMode raw; continue } } opt { if {$s2 == "%>"} { # option parser $q get 2; $self _parseOptions $obj($self:buf:opt) set obj($self:buf:opt) {} $self _setMode raw; continue } } } append obj($self:buf:$obj($self:mode)) [$q get] } } # finish processing the queue: while {[$q size] > 0} { append obj($self:buf:$obj($self:mode)) [$q get] } $self _setMode flush # cleanup: foreach v {buf:code buf:opt buf:raw mode modeprev} {catch {unset obj($self:$v)}} } method render {} { # run the template script set tclBuf "" foreach l $obj($self:data) { set t [lindex $l 0] set d [lindex $l 1] switch $t { raw {append tclBuf "$obj($self:options:printCommand) [list $d]\n"} code {append tclBuf "$d\n"} } } foreach {var val} $obj($self:variables) {$obj($self:interp) eval [list set $var $val]} #puts $tclBuf;return if {$obj($self:options:printCommand) == "_defaultSpool"} { $obj($self:interp) eval {_defaultSpool {} clear} } $obj($self:interp) eval $tclBuf if {$obj($self:options:printCommand) == "_defaultSpool"} { set x [$obj($self:interp) eval {_defaultSpool {} get}] $obj($self:interp) eval {_defaultSpool {} clear} return $x } } method setOption {opt value} { switch $opt { printCommand {set obj($self:options:$opt) $value} include { set o inc$value create $o $o parseFile $value set prevMode [$self _setMode raw] append obj($self:buf:raw) [$o render] $self _setMode $prevMode } source {$obj($self:interp) invokehidden source $value} default {return -code error -errorinfo "Unknown option: $opt"} } } method setVar {var value} { if {$var == "*" && $value == ""} {set obj($self:variables) {}; return} lappend obj($self:variables) $var lappend obj($self:variables) $value } method _setMode {m} { set modenew {} switch $m {code - raw - opt {set modenew $m}} if {$modenew != {}} { if [catch {set obj($self:mode)}] {set obj($self:mode) $modenew} set obj($self:modeprev) $obj($self:mode) set obj($self:mode) $modenew set obj($self:buf:$obj($self:mode)) {} if {$obj($self:modeprev) == {}} { set obj($self:modeprev) $obj($self:mode) } } if {$m == "flush"} { set obj($self:modeprev) $obj($self:mode) set obj($self:mode) _ } if {$obj($self:mode) != $obj($self:modeprev)} { lappend obj($self:data) [list $obj($self:modeprev) $obj($self:buf:$obj($self:modeprev))] set obj($self:buf:$obj($self:modeprev)) {} return $obj($self:modeprev) } } method _parseOptions {o} { set optlist [split $o "\n;"] foreach opt $optlist { set pair [split $opt =] set opt_ [string trim [lindex $pair 0]] if {$opt_ == {}} continue $self setOption $opt_ [string trim [lindex $pair 1]] } }}
Discussion editescargo - I think it's a mistake to have parse read a file; it would be potentially more flexible to use if it just took a string to process as input, and let the caller determine where the string comes from. FF - good point! (changed)APW Just found textutil::expander[1] package in tcllib, which is included in ActiveTcl 8.4.14.0. Have the feeling it does something similar, maybe it's worth looking at it.FF but is not much versatile. Just tried this:
% package require textutil::expander % ::textutil::expander myexp % set a 64 % myexp expand {[if {$a > 50} {] put some text [} {] put some other text [}]} Error in macro: [if {$a > 50} {] put some text [} {] put some other text [}] --> missing close-bracketand I realized I feel well with TemplaTcl O:)APW I think if you look closer to the manual you will see that you have to set the left and right bracket command i.e. "<%" and "%>". Next the token directly following the left bracket is interpreted as the command for handling the contents, so if you have "<%= hello %>" you will need a proc with name "=" for handling the code inside the macro.
% package require textutil::expander % ::textutil::expander te % te lb "<%" % te rb "%> % proc = {args} { return $args } % te expand {this is a text which says <%= hello %> to you} this is a text which says hello to youAdditionally for constructs like a "if" clause it is possible to push and pop the context and at the end to evaluate the code in the macro, normally you will need some tokens for marking begin and end of macro, means a construct like:
<% code if { ...} { %> # some other code here <% /code %> proc code {args} { te cpush .... # some code here } proc /code {args} { set str [te cpop ...] # evaluate the code of the macro and set result return result }You can also define the number of passes to run for the same text to be able to do nested expansion if you use the expand.tcl directly from the author: William Duquette [2]
escargo - I think you want to give some thought into what scope the template code executes at. Right now it seems to be run in proc dump. Two likely alternatives are to run it in the caller's scope or at global scope.FF running in the caller scope might seem a convenient idea, but can potentially generate trouble, since the template is a tcl script that would run just between TemplaTcl::dump and the next command, potentially altering/damaging the caller's scope (if there are subsequent commands after the TemplaTcl::dump command); in order to make it more strict, I make it run in global scope (hoping that global is not polluted or has variable that can make the application unstable); but ideally it should run in a separate interp, copying the needed vars into that interpreter. Don't you think so?escargo - Running in a safe interp would be the right thing, but the question might be what data can the code executing as part of template processing access (or access easily). One could reasonable argue that it should only access values provided by a supplied data object. I could see wanting to supply maybe an environment data object as well (for access to info like date and time, host name, user name, and other info that would not be part of the data coming out of a table to be published).FF added safe interp, setVar command, and also a new markup command for special use (see above).escargo 1 Jun 2007 - See also subst. In some respects, subst is a better model than eval, since it assumes text with variable references and commands embedded in it, instead of valid programs with text embedded in the commands. The ability to intercept variable references and command executions that you don't know ahead of time would simplify some things that you want to do, but those aren't available yet. (Maybe what's needed is a subst that has been extended to take a -variables and/or -commands arguments, which are the names of commands to call when there are variable references or command references respectively.)FF 2007-06-02 - changed much things (almost all). I implemented a pseudo OO system. This allows running recursive/nested templates. If you were interested in this project, maybe you might be interested in re-reading this page from the beginning.CMcC 2Jun07 just doesn't get it - why create a language interpreter to substitute variables and function calls when tcl has a full-function command to do that, in subst? What does the new little language for templating buy you?APW Would that also work for the following example? I don't think so!
<%if {$a != $b} { %> <h3> abc </h3> <%if {$a != 1} {%> <li> <%= $var1 %> </li> <%} else {%> <li> <%= $var2 %> </li> <% } %> <% } else { %> <li> <% myobj getResult %> </li> <table> <tr> Hello there </tr> </table> <% } %>CMcC no, this would work better:
expr { $a != $b ? "[<h3> abc][<li> [expr {$a != 1 ? $var1: $var2}]]" : "[<li> [myobj getResult]] [<table> [<tr> "Hello there"]]" }This would also work:
if {$a != $b} { subst {<h3> abc </h3> [expr {$a != 1 ? "<li> $var1 </li>" : "<li> $var2 </li>"}] } } else { subst { <li> [myobj getResult] </li> <table> <tr> Hello there </tr> </table> } }(note: if returns a value!)But nothing would work as well as refactoring it so it wasn't quite as messy in the first place.APW from the discussion on ToW Tcl on WebFreeWay I have the feeling that people would like to have a template that looks like a HTML page (maybe also XML), so they could see what goes to the client and to have a little bit (or some more) code spread in to drive some output. That's also what Ruby on Rails (short RoR) does. So having Tcl code to produce HTML is not what is wanted in that case (my interpretation). Also for a Tcl programmer that might be more readable I agree. But I think the audience should be more people that do not know much about Tcl but are able tho enter some variables and simple constructs in Tcl to get input from a data source, for example a database.CMcC This is getting silly. Here's a fragment of the stuff that generates this very page you're reading - it's done using subst:
# page template for standard page decoration variable pageT {title: $name [div container { [div header {<h1 class='title'>$Title</h1>}] [div {wrapper content} {<p>$C</p>}] <hr noshade /> [div footer "<p>[join $menu { - }]</p> <p><form action='/_search' method='get'> <input name='S' type='text' value='Search'> </form></p>"] }] }If you really wanted to, you could replace the [div] calls with straight <div>...</div> text.If you feel that subst can't be used on text that resembles an HTML page, you really should have a careful look at what subst does.APW That works if you have defined a proc named div when using subst, but if you want to parse a XML template where you don't know all the tags and you only want to handle specially the part included in <% ... %> and handle all the rest as a text/string? Could you give me an example for that using subst?
<company> my company </mycompany> <% if {[string first $mycompany "DE"]} { %> <cname class="DE"> <%= [getmycompany DE] %> </cname> <department> my department </department> <% } else { %> <cname class="OTHERS"> <%= [getmycompany OTHERS] %> </cname> <% } %> </company>This is just a very simple example, which could be built differently to produce the same output, I know. How would the template file look like for being able to use subst? The output shall be again XML being that conversion the first pass of multiple passes, conversion to HTML being done in a later pass.CMcC Since you asked for subst usage:
[subst { <company> my company </company> [expr {[string first $mycompany "DE"] ? "<cname class='DE'>[getmycompany DE]</cname> <department> my department </department>" : "<cname class='OTHERS'>[getmycompany OTHERS]</cname>" }] }]But I think I'd do this instead in that case:
"<company> my company </company> [expr {[string first $mycompany "DE"] ? "<cname class='DE'>[getmycompany DE]</cname> <department> my department </department>" : "<cname class='OTHERS'>[getmycompany OTHERS]</cname>" }]"Or, by preference, a bit of refactoring:
set cclass [expr {[string first $mycompany "DE"]?DE:OTHERS}] "[<company> {my company}] [<cname> [list class $cclass] {[getmycompany $cclass]}] [if {$cclass eq "DE"} {<department> {my department}}]"APW that's ok, but it doesn't look like an XML page template any more, and that was what some people including me would like to have! The last example you have can also be coded using Tcl code without any subst (and then it might be even more readable :-)) ), but that was not the intention.CMcC Ok, so using subst-if:
[subst { <company> my company </company> [If {[string first $mycompany "DE"]} { <cname class='DE'>[getmycompany DE]</cname> <department> my department </department> } else { <cname class='OTHERS'>[getmycompany OTHERS]</cname> }] }]will now work. Does that look enough like an XML template for the purpose?APW Meanwhile jcw has suggested an interesting solution for what I would like to have see below.
escargo - subst does not have a notion of iteration to expand things inside the string being operated on, for one thing.CMcC Tcl has the concept of iteration, though. Use map, or it's easy to write a function that iterates (think foreach, which returns its iterated results). For example, the thing above to turn a list into an HTML list could be simply represented as <ul><li>[join $list </li><li>]</li></ul>, which is cleaner (I think) ... or even define a proc (such as is already in the tcllib html package) to perform the wrapping.The page HTML generator provides some light-weight facilities along those lines.FF the above mentioned systems sure are good for some things. But my target is a very specific case, where those systems maybe lack some things.TemplaTcl works with templates rich in static text, but also rich in interruptions due to code or putting variables (the typical case is generating markup for a web page). Dealing with that using other systems can possibly result being counter-productive (the TemplaTcl examples found in this page are too simple to demonstrate that).CMcC Do you mean that you can stop the template expansion midway? subst can also do that.FF Even if right now it does its job nicely - just now I added template inclusion (<[email protected] = ..%>), and Tcl source-ing (<[email protected] = ...%>) - I'll keep adding missing features to satisfy the case of code generation, with a particular regard to X(HT)ML page templating, so don't expect it to be just that tiny set of features.CMcC What I'm interested in is examples of some useful things TemplateTcl does better than Tcl, because that's a sign of something that could be improved in Tcl.FF What I mean is: your example is more Tcl code than markup, the markup is hidden and split across the Tcl commands. A template designer (or an X(HT)ML editor) shouldn't care about that. If you don't see advantages in that, maybe you don't need this engine. Note: I'm not stating Tcl has some lack; I'm simply doing an application in Tcl. It is NOT doing "something better than Tcl"! It's doing something "with Tcl" - that sounds more appropriate ;)CMcC I was hoping there was some lack, so it could be repaired.03jun07 jcw - While subst is indeed great for templating IMO, it is unfortunate that it is completely linear. When you use expr and self-defined [...] calls inside to control flow and repetition, you end up nesting things twice each time: first to embed the operation, and again to protect/return the body of that operation. Even Tcl has two modes for that because it becomes unwieldy: the command mode where each command starts on a newline (or after ";"), and embedded calls with [...].CMcC I agree with you, jcw. So I think I'd tend to define an if command that evaluated the test using expr, and then evaluated the consequent or else using subst instead of eval, thus:
[If {$fred} { <h1> header $fred</h1> <..> } else { <h1> header not $fred</h1> <more html> }]That would be an hour's work, would fit nicely alongside a modified foreach and sit inside a namespace. It was 20 minutes' work, and it's on the HTML generator page. Thanks, jcw, for cutting to the nub of the problem. Subst-foreach is next.What other facilities would be useful?APW What about Subst-while?CMcC Too easy :) It's right after Subst-if on the other page.
03jun07 jcw - But I don't see the point in embedding an escape layer using XML. Here's a visually simpler approach:Templates and substAPW 2007-06-07 - I have moved the suggestion from jcw to its own page, as there are some places where I would like to add a link to that page. Hope all agree on that.escargo 3 Jun 2007 - I think one of the reasons for templates is that you can do some of the work of layout in WYSIWYG HTML tools, and then decide what parts to replace with parameters and control structures to get a more generalized form. Certainly you would want to be using CSS wherever possible to separate structure from presentation, but for abstracting certain content details, having a templating system allows decomposition into something that is closer to the original source than replacing final HTML with calls to the tcllib html package or with hand-coded Tcl to generate the HTML.escargo 19 Jun 2007 - I've been looking at the tcllib package named html. It is the opposite of templating, that is a script of commands produces the HTML result. I think it's interesting that many of its commands return strings based on subst in the body.
- ::html::eval
- ::html::for
- ::html::foreach
- ::html::if
- ::html::while
Sly: I believe my implementation is much more minimal. And it works for most common cases.
proc parse {txt} { set code "set res {}\n" while {[set i [string first <% $txt]] != -1} { incr i -1 append code "append res [list [string range $txt 0 $i]]\n" set txt [string range $txt [expr {$i + 3}] end] if {[string index $txt 0] eq "="} { append code "append res " set txt [string range $txt 1 end] } if {[set i [string first %> $txt]] == -1} { error "No matching %>" } incr i -1 append code "[string range $txt 0 $i] \n" set txt [string range $txt [expr {$i + 3}] end] } if {$txt ne ""} { append code "append res [list $txt]\n" } return $code }Let's test it:
set code [parse { asdfgh <% for {set i 5} {$i < 10} {incr i} { %> ZZZZ <%=$i%> XXXXX <%=[expr {$i * 5}]%> <% } %> zxcvb } ] puts " THIS IS CODE:\n\n$code\n\n" eval $code puts " THIS IS RESULT:\n\n$res"Output:
THIS IS CODE: set res {} append res { asdfgh } for {set i 5} {$i < 10} {incr i} { append res { ZZZZ } append res $i append res { XXXXX } append res [expr {$i * 5}] append res { } } append res { zxcvb } THIS IS RESULT: asdfgh ZZZZ 5 XXXXX 25 ZZZZ 6 XXXXX 30 ZZZZ 7 XXXXX 35 ZZZZ 8 XXXXX 40 ZZZZ 9 XXXXX 45 zxcvb
CAU See also, THP it's currently driving some dashboard tools for my employer. I think it's very similar to what you want.AMG: Also, see the template system in Wibble. Look for "wibble::template" and "wibble::applytemplate".jbr : Subst template expansion helpers
[kRob] - 2013-09-09 21:30:37Hey Guys,I'm trying to run this script and keep getting an error for the following line of script:$obj($self:interp) eval $tclBufthis is line 117 in the render method in TemplaTcl and the error gives " invalid command name "}"I'm not familiar with TemplaTcl at all and cant' seem to figure it out.Anyone else getting this?
milarepa - 2014-07-13 21:10:15I got the same problem as kRob.
FireTcl - 2015-02-15 18:13This is my own version. It uses TclOO. It has no other dependency. Possibily to uses filters.
namespace eval ::TemplaTcl { namespace eval filters { proc trim {txt} { return [string trim $txt] } proc title {txt} { return [string totitle $txt] } proc lower {txt} { return [string tolower $txt] } proc upper {txt} { return [string toupper $txt] } } proc filter {filter_name text} { return [filters::$filter_name $text] } array set RE [list \ start_code {\A\n?[ \t]*<%\s*} \ finnish_code {\A\s*%>[ \t]*\n?} \ start_variable {\A<%=\s*} \ finnish_variable {\A\s*%>} \ start_options {\A\n?[ \t]*<%@\s*} \ finnish_options {\A\s*%>[ \t]*\n?}] oo::class create TemplaTcl { variable interp_name mode modeprev options parsed_template list_of_user_variables buffer_options buffer_raw buffer_code buffer_variable output RE constructor {{filename ""}} { set ns [namespace qualifiers [info object class [self]]] namespace eval [self namespace] "namespace upvar $ns RE RE" # create and setup a safe interpreter for running template's tcl code set interp_name [interp create -safe] interp alias $interp_name _filter {} ${ns}::filter interp alias $interp_name print {} puts interp eval $interp_name { set _output "" proc ::puts {args} { global _output set list_of_filters [list] set end_char "\n" set i 0 set args_length [llength $args] while {$i < $args_length} { set arg [lindex $args $i] if {$arg eq "-varname"} { incr i set varname [lindex $args $i] upvar $varname variable_value set msg $variable_value } elseif {$arg eq "-nonewline"} { set end_char "" } elseif {$arg eq "-filters"} { incr i set list_of_filters [lindex $args $i] } else { set msg $arg } incr i } set msg $msg$end_char foreach filter_name $list_of_filters { set msg [_filter $filter_name $msg] } append _output $msg } } array set options [list] set list_of_user_variables [list] set buffer_code "" set buffer_options "" set buffer_raw "" set buffer_variable "" if {$filename ne ""} { my set_template_from_file $filename } } method set_template_from_file {filename} { set fh [open $filename r] set template [read $fh] close $fh my set_template $template } method set_template {template} { my Initialize_mode set template_length [string length $template] set index 0 while {$index < $template_length} { switch $mode { raw { set found_mode 0 foreach possible_mode [list options variable code] { set startToken start_$possible_mode if {[regexp -indices -start $index -- $RE($startToken) $template matched_indices]} { my Set_mode $possible_mode set index [lindex $matched_indices 1] set found_mode 1 break } } if $found_mode continue } code - variable - options { if {[regexp -indices -start $index -- $RE(finnish_$mode) $template matched_indices]} { my Set_mode raw set index [lindex $matched_indices 1] continue } } } append buffer_$mode [string index $template $index] incr index } lappend parsed_template [list $mode [set buffer_$mode]] set buffer_$mode {} set template {} } method Initialize_mode {} { set mode raw set modeprev "" } method render {} { # run the template script set output "" set tclCode "" foreach parsed_item $parsed_template { lassign $parsed_item item_type item_content switch $item_type { raw { append tclCode "puts -nonewline [list $item_content]\n" } code { append tclCode "$item_content\n" } variable { append tclCode "puts -nonewline -varname $item_content\n" } options { my Parse_options $item_content tclCode } } } foreach {varname value} $list_of_user_variables { interp eval $interp_name [list set $varname $value] } interp eval $interp_name $tclCode set output [interp eval $interp_name {set _output}] interp eval $interp_name {set ::_output ""} return $output } method set_vars {args} { lappend list_of_user_variables {*}$args } method get_vars {} { return $list_of_user_variables } method delete_vars {} { set list_of_user_variables [list] } method Set_mode {m} { set modeprev $mode set mode $m if {$mode != $modeprev} { lappend parsed_template [list $modeprev [set buffer_$modeprev]] set buffer_$modeprev {} } } method Parse_options {o tclCode_var} { upvar $tclCode_var tclCode set optlist [split $o "\n;"] foreach opt $optlist { set pair [split $opt =] set opt_ [string trim [lindex $pair 0]] if {$opt_ == {}} continue my Set_option $opt_ [string trim [lindex $pair 1]] tclCode } } method Set_option {opt value tclCode_var} { upvar $tclCode_var tclCode switch $opt { include { set o [[info object class [self]] new $value] $o set_vars {*}[my get_vars] append tclCode [$o render] } source {interp invokehidden $interp_name source $value} default {return -code error -errorinfo "Unknown option: $opt"} } } } } # Example: set p [::TemplaTcl::TemplaTcl new] $p set_vars cityList [list {New york} Madrid London] $p set_template { <table> <% for {set i 0} {$i < 4} {incr i} { %> <tr><td><%= i %></td></tr> <% } %> </table> <ul> <% foreach item $cityList { %> <li><%= item %></li> <% } %> </ul>} puts [$p render] | http://wiki.tcl.tk/18175?redir=18174 | CC-MAIN-2017-34 | refinedweb | 4,332 | 52.63 |
Groovy, Web Services and OBIEE 12c. I first started writing Groovy when Oracle acquired Sunopis (now Oracle Data Integrator), as Groovy was and is the standard way to script the ODI SDK. I was hooked. If you ever read my work on that other blog, you know I once proposed Groovy as the definitive choice for interacting with JMX MBeans. By the way… it’s a shame their new blog format removed my embedded video of the Matrix Architect… which is the main reason I beefed up the Matrix imagery here.
UPDATE: Thanks Robin Moffatt for “refactoring” my old post and putting The Architect back in.
In OBIEE 12c, JMX Beans are gone, and in it’s place, we’ve inherited extended SOAP support in some cases, but gloriously… new RESTful services for most of the lifecycle management capabilities. Did this cause me to kick Groovy to the curb in favor of groovier languages like JavaScript or Python for OBIEE 12c scripting? Not a chance.
I’m specifically talking about scripting web services in this piece… which technically means, developing web service clients, and I’ll describe how to do that for both the legacy SOAP services that have been with us for a while, as well as the RESTful services that are new in OBIEE 12c. Although I’m serenading the Groovy language in this post, I need to make it clear that much of the simplicity in my code is due to the wonderful groovy-wslite project and the dead-simple syntax and convenience methods included therein. This project manifests everything good about DSL, implementing meaningful closures instead of overloaded APIs… thanks John Wagenleitner (twitter|github) and all of the contributors for a first-class piece of software.
The Matrix Reloaded
I love to hear the scoffs when I say “SOAP” aloud to other developers. It’s easy to forget that web services were invented with SOAP, and without this important link in the chain, we wouldn’t have RESTful APIs, microservices, or any of the new JavaScript-centric projects and platforms so common today. SOAP is an aging standard though, and certainly not the flavor of the month… but the good news for Groovy developers is that groovy-wslite supports SOAP in the same groovy way it supports REST. We’ll experience Groovy with SOAP with a new service in OBIEE 12c… one giving us the equivalent of “Reload Files and Metadata”.
All the SOAP stuff is documented and completely supported… at least as much as anything is with OBIEE. So lets take a peek at how Groovy makes all of this easier. The SOAP services in OBIEE require that we first get a session id, so we call a separate SOAP method to get the initial session id before we call the method we’re actually interested in. This is easy with groovy-wslite:
@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.3')
import wslite.soap.SOAPClient
import wslite.soap.SOAPClientException
def session = new SOAPClient(
''
).send(
SOAPAction: ''
) {
body {
logon('xmlns': 'urn://oracle.bi.webservices/v8') {
name('weblogic')
password('Admin123')
}
}
}.envelope
println session
Let’s walk through this. The Grab annotation is a built-in (or in-built for my British friends) way in Groovy to pull down JAR files from Maven repositories… by default using Maven Central. When compiling Groovy we would typically use a build tool such as Gradle to manage dependencies… but Grab is great when doing lightweight scripting jobs. The rest of the code is specific to the web service we are using. The SOAPAction URL specifies the particular web service we are using… obviously the host and port will vary depending on the OBIEE installation.
The body and envelope structure in SOAP is just a standard way to structure a payload for passing to a web service — with the body describing the method we want to call — in this case the logon method which returns the session id we are looking for. This gives us the following output… a simple print of the session id we captured:
iqaa0dofih4625lrsks9ja466q1ii7jhaid8taduha2ldram
So building from this, we need to call the actual reloadMetadata method in a similar way, referencing the session id we just returned using the variable session which I defined in the code above, so consider this code as a continuation of what’s above:
new SOAPClient(
''
).send(
SOAPAction: ''
) {
body {
reloadMetadata('xmlns': 'urn://oracle.bi.webservices/v8') {
sessionID(session)
}
}
}.envelope
This gives us the ability to call “Reload Files and Metadata” programatically… something that was typically hacked together with JavaScript in an ugly way in OBIEE 11g.
Getting Forensic All Up in Here
To use RESTful web services, we need to know the URL of the service we are interacting with, the different parameters to pass, the content type of those parameters, and the content type of the response payload. But the RESTful services we’ll be using in this post are undocumented in OBIEE 12c, and I would imagine unsupported. So how do we go about about determining all of this?
Now seems like a good time for the lawyers to get involved. Although the SOAP stuff is heavily documented, the RESTful stuff is purely caveat emptor. I’ll quote my good friend Robin Moffatt for this… it’s a fine denial of warranty:
None of these Web Services are documented, and they should therefore be assumed to be completely unsupported by Oracle. This article is purely for geek interest. Using undocumented APIs leaves you at risk of the API changing at any time.
But hey: with the simple patch upgrade from 12.2.1.0 to 12.2.1.1… Oracle changed the name of the supported API from data-model-cmd.sh to datamodel.sh, broke it, and now rely on an accidentally exposed functionality for a workaround. Meanwhile, all the RESTful methods I’m describing here were unchanged. So which one put you more at risk…I’m just saying…
There are a variety of web service “sniffing” approaches, including projects like Fiddler or Wireshark, or command-line utilities like sysdig. Generally, we would listen to traffic using one of these tools while making a call to the REST API… for instance, using datamodel.sh/datamodel.cmd in 12.2.1.1, and then watch the output from these sniffing tools. While this will certainly work… OBIEE 12c is already logging all REST API calls against bi-lcm, the RESTful web service for all lifecycle management functionality. In the <domain-home>/servers/bi_server1/logs directory, we see the bi-lcm-rest.log.0 file, which has all the calls to bi-lcm there. Let’s take a look at this in action.
The Matrix Uploaded
I’m going to upload a binary repository to OBIEE 12.2.1.1 using the following command:
[oracle@localhost]$ datamodel.sh uploadrpd -I current.rpd -W Admin123 -U weblogic -P Admin123 -SI ssi -S localhost -N 9502 -D
Service Instance: ssi
Operation successful.
RPD upload completed successfully.
[oracle@localhost repository]$
What do we see in the bi-lcm-rest.log.0 file? For one thing… the binary data from the RPD is written to the log file, which muddies the water a bit about what’s there… but we can make out the POST structure, which includes the URL, followed by the multi-part data elements. I’ve cleaned up the results a bit to make it clear:
200 > POST
200 > Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
200 > Authorization: Basic d2VibG9naWM6QWRtaW4xMjM=
200 > Connection: keep-alive
200 > Content-Length: 30228
200 > Content-Type: multipart/form-data;boundary=Boundary_1_1813187653_1472059721163
200 > Host: localhost:9502
200 > MIME-Version: 1.0
200 > User-Agent: Jersey/2.22.1 (HttpUrlConnection 1.8.0_101)
--Boundary_1_1813187653_1472059721163
Content-Type: text/plain
Content-Disposition: form-data; name="rpd-password"
Admin123
--Boundary_1_1813187653_1472059721163
Content-Type: application/vnd.oracle.rpd
Content-Disposition: form-data; filename="current.rpd"; modification-date="Wed, 24 Aug 2016 13:22:06 GMT"; size=29708; name="file"
This gives us all we need to construct code to call the API, which is simplistic and easy to follow using Groovy and groovy-wslite:
')
def response = client.post(path: '/bi-lcm/v1/si/ssi/rpd/uploadrpd') {
multipart 'file', new File('current.rpd').bytes,
"application/vnd.oracle.rpd"
multipart "rpd-password", "Admin123".bytes
}
println JsonOutput.prettyPrint(new String(response.data))
Let me walk through a few of the lines. We need to define our client object, providing the address of the OBIEE 12.2.1.1 server, and then use basic HTTP (username and password) authentication against it.
Following the construction and authorization of our client object… we get into the details of the POST method. Notice that, instead of a highly-overloaded API to handle all the different permutations of RESTful methods… we get convenience DSL methods specific to the different method types, in this case the POST. Also, notice we only pass a single explicit parameter to the POST method — the path of the service — while the balance of the parameters are expressed using a closure and DSL content. In the DSL we are able to expressively describe our content to the POST, and the closure structure means we don’t have to worry about API ordering, etc. In this example we need to describe two multi-part REST parameters. Multipart parameters are how we pass content like file data described with content “labels” and specific boundaries as a way to delineate the different parameters… sort of like how we handle attachments in email protocols. This is dead-simple in Groovy: we can pass the binary representation of any data (including that from Files or Strings) by simply using the bytes method as a core part of all Groovy objects, including File objects but also String objects.
Groovy-wslite does something especially nice with the response object… it automatically renders the data attribute — a single attribute in a complex object returned as the payload — as a byte[] datatype. If you see how a cURL call presents this data back… it dumps the binary data which is difficult to render in certain terminals and text editors (this binary data is also what is written to the bi-lcm-rest.log.0). For instance:
[oracle@localhost repository]$ curl -X "POST" "" \
> --data-urlencode "target-password=Admin123" --basic --user weblogic:Admin123
d��2016-08-26 08:21:55.560 >:HO۟G�1�is3��O�>�:XJ�.9�Gc�{n�0��q`o�+��-L&���?2o���OO��M.o���IY�X�*=��(�9B9|�%��6���X�����s
��}='^X،VT��]�����QƢ�ÚY�c�9�?��G���^Q��"��=��0O�
Kh��w��-��e�ʩz�2���*���O��|
�{L�[iCfv�)�v)��'����|�CM'yJ�<C/;�
��g6p��&�#��:�w�~���L
�C����Q,��xD.@Z���s��C�h�]�PrJD�\�6Z����0�m� %�$y�A��=Y�C[����
P��|#:�M�T����2����hK�,M�'����V�"��X�q������3�p֠�9��9z
��hB�m��ڮU&&p1�9k�S�ﴪ�
[Abbreviated for clarity and sanity...]
With cURL, you could easily redirect this to a file and poof get a binary RPD, but that seems a little… well… messy. With a byte[] datatype, it’s a matrix of numbers stored in nested arrays that we can easily convert to a String to print the payload (as we are doing here, including formatting)… or as we’ll see in the next section… use to easily write binary data to a file.
So when we execute the above code, we get the following JSON result, which I am also formatting using the groovy.json package:
{
"
}
The Matrix Downloaded
The OBIEE crowd is familiar with the uploadRepository JMX MBean from OBIEE 11g… Fusion Middleware Control interacted with it every time a binary repository was uploaded using the browser. But we also have the downloadRepository MBean in 11g, it’s just not exposed in Fusion Middleware Control anywhere. We have a comparable downloadrpd RESTful method which is exposed using datamodel.sh:
datamodel.sh downloadrpd -O current.rpd -W Admin123 -U weblogic -P Admin123 -SI ssi -S localhost -N 9502
…which produces the following in the log file:
209 > POST
209 > Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
209 > Authorization: Basic d2VibG9naWM6QWRtaW4xMjM=
209 > Connection: keep-alive
209 > Content-Length: 24
209 > Content-Type: application/x-www-form-urlencoded
209 > Host: localhost:9502
209 > User-Agent: Jersey/2.22.1 (HttpUrlConnection 1.8.0_101)
target-password=Admin123
Aug 24,2016 16:31:09 oracle.bi.lcm.rest.app.LCMApplication INFO - 209 * Server responded with a response on thread [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
209 < 200
209 < Content-Length: 30220
209 < Content-Type: application/vnd.oracle.rpd
So with the method parameters and the content types known, we can write the following Groovy code to download a binary repository:
')
new File('current.rpd').setBytes(
client.post(path: '/bi-lcm/v1/si/ssi/rpd/downloadrpd') {
urlenc "target-password": "Admin123"
}.data
)
Everything is the same until we get to the actual POST portion of the method… where we see the urlenc property. This is a shorthand way of expressing that the target-password parameter is a URL-encoded parameter… meaning it’s encoded in such a way to protect URL-specific literals from getting in the way. Let’s be honest: it’s not necessary to understand this content type except to say… the bi-lcm downloadrpd method expects a URL-encoded content type, and this is how we can pass it. We have the entire POST method, plus the return of the data result, wrapped in a setBytes() method, which will write the binary data returned from the POST into a new repository binary file.
Conclusion
I love Groovy… perhaps that is clear. We can mix and match compliant Java and Groovy in the same class file (heck… on the same line) and the Groovy compilier will make sense of it. This is why I would switch every single Java shop to Groovy immediately… especially when using a build tool like Gradle that can compile our code against the JVM regardless of which language it’s written in. We can strongly type, weakly type, do both from one line to the next, all while focusing on delivering an end product instead of reusing the same boiler-plate code time after time.
But closures are the real reason that projects like groovy-wslite are so perfect, and how they make DSL possible. It’s a pleasure to use external projects when the implementation methods are self-describing. It’s the difference between a formal dinner and a casual get-together: there’s a time and a place for each, but we all know which one is more fun.
Thank you for reading this Red Pill Analytics’ blog post. You can find more blogs by our amazing authors here. Check out more info about Red Pill Analytics at redpillanalytics.com. | https://medium.com/red-pill-analytics/groovy-obiee12-b146f8d54d7d | CC-MAIN-2017-26 | refinedweb | 2,470 | 53 |
Hi I made this game just for the fun of it:
I'm wondering how, after I either win or lose at the game, I would give an option to restart the game. Possibly a switch case? And how would I define the replay point in the game?I'm wondering how, after I either win or lose at the game, I would give an option to restart the game. Possibly a switch case? And how would I define the replay point in the game?Code:#include <stdafx.h> #include <iostream> #include <cstdlib> #include <time.h> using namespace std; int main() { const int lowest = 1; const int highest = 999; int nNumber, nGuess, nNoOfGuesses; time_t seconds; time(&seconds); srand((unsigned int) seconds); nNumber = rand() % (highest - lowest + 1) + lowest; cout<<"Guess the Number - by UPNPAD" <<endl <<"Hey you! Lets play guess the number! Okay, the rules are: " <<endl; cout<<"1. The number is anything from 1-999" <<endl <<"2. You have 10 guesses to get the number" <<endl; cout<<"3. If you get it wrong, I'll tell you if you should guess higher or lower next time." <<endl <<"OK! Let's Play!" <<endl; for (nNoOfGuesses = 1; nNoOfGuesses < 11; nNoOfGuesses++){ cout<< "Please type your guess: " <<endl; cin>>nGuess; cin.ignore(); if (nGuess < nNumber){ cout<<"Try guessing higher." <<endl; } else if (nGuess > nNumber){ cout<<"Try guessing lower." <<endl; } else if (nGuess = nNumber){ cout<<"Well done! You guessed correctly!" <<endl; cin.get(); return 0; } } cout<<"You didn't manage to guess the number in 10 tries. The answer you needed was " <<nNumber <<" :( Better luck next time!" <<endl; cin.get(); return 0; } | http://cboard.cprogramming.com/cplusplus-programming/88962-code-replaying-game-w-o-restarting.html | CC-MAIN-2015-11 | refinedweb | 267 | 85.08 |
11 March 2011 17:09 [Source: ICIS news]
LONDON (ICIS)--The downside risk for world oil demand comes from high international prices, OPEC said in its monthly oil report on Friday.
“Should strong price levels remain, this would lead to a reduction in the use of transportation fuel, especially in the summer driving season,” OPEC said in the report.
The report said that manufacturing activities were showing an upward trend, “indicating more oil consumption in most of the OECD countries and ?xml:namespace>
OPEC said: “World oil demand is forecast to grow by 1.4m bbl/day in 2011, averaging 87.8m bbl/day, broadly in line with the previous report.”
Meanwhile, crude oil futures dropped on Friday because of expectations that the earthquake in
At GMT 16:35, April Brent was trading at $113.80/bbl, down $1.63/bbl, while April WTI was at $100.42/bbl, down $2.28/b | http://www.icis.com/Articles/2011/03/11/9443209/current-high-oil-prices-could-lead-to-a-fall-in-oil-demand-opec.html | CC-MAIN-2014-52 | refinedweb | 153 | 66.03 |
Every time I send e-mail with Django I seem to do it slightly differently, especially when it comes to sending HTML-based emails.
So, I did what any good Djangonaut does and wrote a quick function that wraps up sending of a multi-part HTML / Text e-mail from templates you create.
Firstly, create your e-mail templates. You'll need both a HTML and a plain-text template; for the HTML template I strongly recommend the use of Premailer, which puts all CSS definitions inline.
Here's a sample HTML template - as it would come out of Premailer. We'll pretend it's in the emails template directory, with a name of newsite.html.
<h1 style='font: Arial; font-weight: bold; font-size: 15pt; color: #006;'>Thanks!</h1> <p style='font: Arial,Helvetica; size: 10pt;'>Hello, {{ username }}.</p> <p style='font: Arial,Helvetica; size: 10pt;'>Thank you for submitting your website, titled <strong>{{ title }}</strong>, to our listing.</p> <p style='font: Arial,Helvetica; size: 10pt;'>We'll verify it, take a screenshot, and publish it within the next few days.</p> <p style='font: Arial,Helvetica; size: 10pt;'>Regards,</p> <p style='font: Arial,Helvetica; size: 10pt;'><em>Your Favourite Webmaster.</em></p>
And here's that same e-mail, in plain-text format - also in the e-mails folder, called newsite.txt.
Hello, {{ username }}. Thank you for submitting your website, titled '{{ title }}', to our listing. We'll verify it, take a screenshot, and publish it within the next few days. Regards, Your Favourite Webmaster.
Those who are familiar with Django's template language will see that this template uses two variables, username and title. Let's populate them, shall we?
template_context = { 'username': 'joecitizen', 'title': 'My Movie Review Site', 'url': '', }
So far we have an e-mail message template in both HTML and text formats; all we need now to send an e-mail is a subject and a recipient.
recipient = 'joe@example.dom' # ['joe@example.dom',] would also be suitable subject = 'Site submission: {{ url }}'
That's pretty straightforward - our subject also contains Django template variables, in this case the URL from our template context we created earlier.
Now it's time to send the message. I have been using this function with much success:
def send_multipart_mail(template_name, email_context, subject, recipients, sender=None, fail_silently=False): """ This function will send a multi-part e-mail with both HTML and Text parts. template_name must NOT contain an extension. Both HTML (.html) and TEXT (.txt) versions must exist, eg 'emails/public_submit' will use both public_submit.html and public_submit.txt. email_context should be a plain python dictionary. It is applied against both the email messages (templates) & the subject. subject can be plain text or a Django template string, eg: New Job: {{ job.id }} {{ job.title }} recipients can be either a string, eg 'a@b.com' or a list, eg: ['a@b.com', 'c@d.com']. Type conversion is done if needed. sender can be an e-mail, 'Name <email>' or None. If unspecified, the DEFAULT_FROM_EMAIL will be used. """ from django.core.mail import EmailMultiAlternatives from django.template import loader, Context from django.conf import settings if not sender: sender = settings.DEFAULT_FROM_EMAIL context = Context(email_context) text_part = loader.get_template('%s.txt' % template_name).render(context) html_part = loader.get_template('%s.html' % template_name).render(context) subject_part = loader.get_template_from_string(subject).render(context) if type(recipients) != list: recipients = [recipients,] msg = EmailMultiAlternatives(subject_part, text_part, sender, recipients) msg.attach_alternative(html_part, "text/html") return msg.send(fail_silently)
Lastly, to put together the previous example:
from multipart_email import send_multipart_email # Assuming, of course, you saved the above functoin in multipart_email.py send_multipart_mail('emails/newsite', template_context, subject, recipient)
What this does, is uses our existing template context, subject, and recipient, to send a HTML and plain-text e-mail based off the templates we built earlier. Note that it automatically appends .html or .txt as required. Hopefully the extra documentation in the docstring is useful.
Recipients who can read HTML e-mail will see your nicely formatted HTML e-mail message, while everyone else will see the plain-text alternative.
Slowly, this method is finding it's way into each of my Django applications. Please, just don't overdo the HTML messages!. | https://www.rossp.org/blog/easy-multi-part-e-mails-django/ | CC-MAIN-2018-30 | refinedweb | 698 | 51.04 |
It worked! That problem had been driving me crazy for the past 2 days. I don't know why I couldn't find the answer via Google. Perhaps its because of all the brain damage from my Java programming. Thank you so much. - John 2008/2/10 Chad Austin <chad at imvu.com>: > Hi all, > > A month ago or so we discovered a bug in Boost.Python that manifests when > using enable_shared_from_this. Here is a test case that demonstrates the > bug: > > > #include <boost/python.hpp> > #include <boost/enable_shared_from_this.hpp> > > using namespace boost; > using namespace boost::python; > > class Test; > typedef shared_ptr<Test> TestPtr; > > class Test : public enable_shared_from_this<Test> { > public: > static TestPtr construct() { > return TestPtr(new Test); > } > > void act() { > TestPtr kungFuDeathGrip(shared_from_this()); > } > > void take(TestPtr t) { > } > }; > > void Export_test() { > class_<Test, TestPtr, noncopyable>("Test") > .def("construct", &Test::construct) > .staticmethod("construct") > > .def("act", &Test::act) > .def("take", &Test::take) > ; > } > > And here is the Python: > > x = Test.construct() > x.take(x) > x.act() > > The bug (as I understand it) is that the shared_ptr_from_python converter > creates a new shared_ptr for the Test instance to pass it into C++. This > new shared_ptr has a nop deleter, except that it keeps the Python object > alive as long as the new shared_ptr is alive. The problem here is that > creating a shared_ptr to an object of type T when T is > enable_shared_from_this<T> resets the weak pointer inside of > enable_shared_from_this<T>. (See shared_ptr's constructors for the details > of the implementation.) A fix that passes the test above and has worked for > us is to change shared_ptr's constructor to accept a > dont_enable_shared_from_this argument and pass that in from the > shared_ptr_from_python converter. The patch is attached (against boost > 1.33, but the bug didn't look fixed in 1.34 either). > > Cheers, > Chad > > p.s. I have seen other people with this problem as well. Googling for > bad_weak_ptr turns up several results. > > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > > > | https://mail.python.org/pipermail/cplusplus-sig/2008-February/012976.html | CC-MAIN-2020-29 | refinedweb | 323 | 75.3 |
Colouring a rectangle
Hi
This is my first post, I want to draw a rectangle with a blue colour, but the problem is that the method is not recognized (this thing drives me mad) can you please help me to set the colour.
import java.awt.*; </p> <p>public class MonRectangle extends Rectangle {<br /> //Les coordonnées<br /> int PosX, PosY ;<br /> int width, height;<br /> //Constructeur<br /> public MonRectangle(int PosX, int PosY, int width, int height){<br /> setSize(width,height);<br /> setLocation(PosX,PosY);<br /> setVisible(true); // cannot find symbol<br /> setBackground(Color.blue); // cannot find symbol<br /> }<br /> }
Thank you in advance.
The colour of the Rectangle is not stored in the object, you simply must specify it when it is drawn. The setBackground(Color.blue) is not recognized because neither the Rectangle or MonRectangle class have a method setBackground(Color c).
In order to draw the Rectangle blue, find the method that will be painting the Rectangle (e.g. paintComponent() in a JPanel class) and override it so that the Color is set to blue when the Rectangle is drawn.
e.g
@Override
public void paintComponent(Graphics ga) {
super.paintComponent(ga); //Carries out normal painting
Graphics2D g = (Graphics2D) ga;
MonRectangle mr = this.getRectangle();//You will need to fill this bit
g.setPaint(Color.blue);//change paint colour to blue
g.fill(mr); //paint rectangle
}
Thank you for your useful post. | https://www.java.net/node/702000 | CC-MAIN-2015-14 | refinedweb | 233 | 54.63 |
ASP.NET Core updates in .NET 6 Preview 3
Daniel
.NET 6 Preview 3 is now available and includes many great new improvements to ASP.NET Core.
Here’s what’s new in this preview release:
-
To get started with ASP.NET Core in .NET 6 Preview 3, 2 to .NET 6 Preview 3:
- Update all Microsoft.AspNetCore.* package references to
6.0.0-preview.3.*.
- Update all Microsoft.Extensions.* package references to
6.0.0-preview.3.*.
- Update calls to
TryRedeemPersistedStateon
ComponentApplicationStateto call
TryTakePersistedStateinstead.
- Update calls to
TryRedeemFromJsonon
ComponentApplicationStateto call
TryTakeAsJsoninstead.
See the full list of breaking changes in ASP.NET Core for .NET 6.
Smaller SignalR, Blazor Server, and MessagePack scripts
Thanks to a community contribution from Ben Adams the SignalR, MessagePack, and Blazor Server scripts are now significantly smaller, enabling smaller downloads, less JavaScript parsing and compiling by the browser, and faster start-up.
The download size reduction from this work is pretty phenomenal:
You also now only need the
@microsoft/signalr-protocol-msgpack package for MessagePack; no need to include
msgpack5. This means you only need an additional
29 KB rather than the earlier
140 KB to use MessagePack instead of JSON.
Here’s how this size reduction was achieved:
- Updated TypeScript and dependencies to latest versions.
- Switched from uglify-js to terser, which is webpack’s default and supports newer JavaScript language features (like
class).
- Marked the SignalR modules as
"sideEffects": falseso tree-shaking is more effective.
- Dropped the
"es6-promise/dist/es6-promise.auto.js"polyfill.
- Changed TypeScript to output
es2019rather than
es5and dropped the “es2015.promise” and “es2015.iterable” polyfills.
- Moved to
msgpack5from
@msgpack/msgpackas it requires less polyfills and is TypeScript & module aware.
You can find more details on these changes in Ben’s pull request on GitHub.
Enable Redis profiling sessions
We accepted a community contribution from Gabriel Lucaci to enable Redis profiling session with Microsoft.Extensions.Caching.StackExchangeRedis in this preview. For more details on Redis profiling, see the official documentation. The API can be used as follows:
services.AddStackExchangeRedisCache(options => { options.ProfilingSession = () => new ProfilingSession(); })
HTTP/3 endpoint TLS configuration
Work is beginning to ramp up on support for HTTP/3 in .NET 6. HTTP/3 brings a number of advantages over existing HTTP protocols, including faster connection setup, and improved performance on low-quality networks.
New in this preview is the ability to configure TLS certificates on individual HTTP/3 ports with
UseHttps. This brings Kestrel’s HTTP/3 endpoint configuration in-line with HTTP/1.1 and HTTP/2.
.ConfigureKestrel((context, options) => { options.EnableAltSvc = true; options.Listen(IPAddress.Any, 5001, listenOptions => { listenOptions.Protocols = HttpProtocols.Http3; listenOptions.UseHttps(httpsOptions => { httpsOptions.ServerCertificate = LoadCertificate(); }); }); })
Initial .NET Hot Reload support
Early support for .NET Hot Reload is now available for ASP.NET Core & Blazor projects using
dotnet watch. .NET Hot Reload applies code changes to your running app without restarting it and without losing app state.
To try out hot reload with an existing ASP.NET Core project based on .NET 6, add the
"hotReloadProfile": "aspnetcore" property to your launch profile in launchSettings.json. For Blazor WebAssembly projects, use the
"blazorwasm" hot reload profile.
Run the project using
dotnet watch. The output should indicate that hot reload is enabled:
watch : Hot reload enabled. For a list of supported edits, see. Press "Ctrl + R" to restart.
If at any point you want to force the app to rebuild and restart, you can do so by entering Ctrl+R at the console.
You can now start making edits to your code. As you save code changes, applicable changes are automatically hot reloaded into the running app almost instantaneously. Any app state in the running app is preserved.
You can hot reload changes to your CSS files too without needing to refresh the browser:
Some code changes aren’t supported with .NET Hot Reload. You can find a list of supported code edits in the docs. With Blazor WebAssembly only method body replacement is currently supported. We’re working to expand the set of supported edits in .NET 6. When
dotnet watch detects a change that cannot be applied using hot reload, it falls back to rebuilding and restarting the app.
This is just the beginning of hot reload support in .NET 6. Hot reload support for desktop and mobile apps will be available soon in an upcoming preview as well as integration of hot reload in Visual Studio.
Razor compiler no longer produces a separate Views assembly
The Razor compiler previously utilized a two-step compilation process that produced a separate Views assembly that contained the generated views and pages (.cshtml) defined in the application. The generated types were public and under the
AspNetCore namespace.
We’ve now updated the Razor compiler to build the views and pages types into the main project assembly. These types are now generated by default as
internal sealed in the
AspNetCoreGeneratedDocument namespace. This change improves build performance, enables single file deployment, and enables these types to participate in .NET Hot Reload.
For additional details about this change, see the related announcement issue on GitHub.
Shadow-copying in IIS
We’ve added a new feature in the ASP.NET Core Module for IIS to add support for shadow-copying your application assemblies. Currently .NET locks application binaries when running on Windows making it impossible to replace binaries when the application is still running. While our recommendation remains to use an app offline file, we recognize there are certain scenarios (for example FTP deployments) where it isn’t possible to do so.
In such scenarios, you can enable shadow copying by customizing the ASP.NET Core module handler settings. In most cases, ASP.NET Core application do not have a web.config checked into source control that you can modify (they are ordinarily generated by the SDK). You can add this sample
web.config to get started.
<?xml version="1.0" encoding="utf-8"?> <configuration> <!-- To customize the asp.net core module uncomment and edit the following section. For more info see --> <system.webServer> <handlers> <remove name="aspNetCore"/> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModulev2" resourceType="Unspecified"/> </handlers> /" /> <!-- Only enable handler logging if you encounter issues--> <!--<handlerSetting name="debugFile" value=".\logs\aspnetcore-debug.log" />--> <!--<handlerSetting name="debugLevel" value="FILE,TRACE" />--> </handlerSettings> </aspNetCore> </system.webServer> </configuration>
You require a new version of ASP.NET Core module to try to this feature. On a self-hosted IIS server, this requires a new version of the hosting bundle. On Azure App Services, you will be required to install a new ASP.NET Core runtime site extension
Vcpkg port for SignalR C++ client
Vcpkg is a cross-platform command-line package manager for C and C++ libraries. We’ve recently added a port to vcpkg to add CMake native support (works with MSBuild projects as well) for the SignalR C++ client.
You can add the SignalR client to your CMake project with the following snippet (assuming you’ve already included the vcpkg toolchain file):
find_package(microsoft-signalr CONFIG REQUIRED) link_libraries(microsoft-signalr::microsoft-signalr)
After this, the SignalR C++ client is ready to be #include’d and used in your project without any additional configuration. For a complete example of a C++ application that utilizes the SignalR C++ client, check out this repository.
Reduced memory footprint for idle TLS connections
For long running TLS connections where data is only occasionally sent back and forth, we’ve significantly reduced the memory footprint of ASP.NET Core apps in .NET 6. This should help improve the scalability of scenarios such as WebSocket servers. This was possible due to numerous improvements in
System.IO.Pipelines,
SslStream and Kestrel. Let’s look at some of the improvements that have contributed to this scenario:
Reduce the size of
System.IO.Pipelines.Pipe
For every connection that we establish, we allocate two pipes in Kestrel: one from the transport layer to the application for the request and another from the application layer to the transport for the response. By shrinking the size of
System.IO.Pipelines.Pipe from 368 bytes to 264 bytes (~28.2%), we’re saving 208 bytes per connection (104 bytes per Pipe).
Pool
SocketSender
SocketSender objects (that subclass
SocketAsyncEventArgs) are around 350 bytes at runtime. Instead of allocating a new
SocketSender object per connection, we can pool them since sends are usually very fast and we can reduce the per connection overhead. Instead of paying 350 bytes per connection, we now only pay 350 bytes per
IOQueue(one per queue to avoid contention). In our WebSocket server with 5000 idle connections we went from allocating ~1.75 MB (350 bytes * 5000) to now allocating just ~2.8kb (350 bytes * 8) for
SocketSender objects.
Zero bytes reads with
SslStream
Bufferless reads are a technique we already employ in ASP.NET Core to avoid renting memory from the memory pool if there’s no data available on the socket. Prior to this change, our WebSocket server with 5000 idle connections required ~200 MB without TLS compared to ~800 MB with TLS. Some of these allocations (4k per connection) were from Kestrel having to hold on to an ArrayPool buffer while waiting for the reads on SslStream to complete. Given that these connections were idle, none of reads completed and return their buffers to the ArrayPool forcing the ArrayPool to allocate more memory. The remaining allocations were in
SslStream itself: 4k buffer for TLS handshakes and 32k buffer for normal reads. In preview3, when the user performs a zero byte read on SslStream and it has no data available,
SslStream will internally perform a zero-byte read on the underlying wrapped stream. In the best case (idle connection), these changes result in a savings of 40 Kb per connection while still allowing the consumer (Kestrel) to be notified when data is available without holding on to any unused buffers.
Zero byte reads with
PipeReader
Once
SslStream supported bufferless reads, we then added the option to perform zero byte reads to
StreamPipeReader, the internal type that adapts a
Stream into a
PipeReader. In Kestrel, we use a
StreamPipeReader to adapt the underlying
SslStream into a
PipeReader and it was necessary to expose these zero byte read semantics on the
PipeReader.
You can now create a
PipeReader that supports zero bytes reads over any underlying
Stream that supports zero byte read semantics (e.g,.
SslStream,
NetworkStream, etc) using the following API:
var reader = PipeReader.Create(stream, new StreamPipeReaderOptions(useZeroByteReads: true));
Remove slabs from the
SlabMemoryPool
To reduce fragmentation of the heap, Kestrel employed a technique where it allocated slabs of memory of 128 KB as part of it’s memory pool. The slabs were then further divided into 4 KB blocks that were used by Kestrel internally. The slabs had to be larger than 85 KB to force allocation on the large object heap to try and prevent the GC from relocating this array. However, with the introduction of the new GC generation, Pinned Object Heap (POH), it no longer makes sense to allocate blocks on slab. In preview3, we now directly allocate blocks on the POH, reducing the complexity involved in managing our own memory pool. This change should make easier to perform future improvements such as making it easier to shrink the memory pool used by Kestrel.
BlazorWebView controls for WPF & Windows Forms
For .NET 6 we are adding support for building cross-platform hybrid desktop apps using .NET MAUI and Blazor. Hybrid apps are native apps that leverage web technologies for their functionality. For example, a hybrid app might use an embedded web view control to render web UI. This means you can write your app UI using web technologies like HTML & CSS, while also leveraging native device capabilities. We will be introducing support for building hybrid apps with .NET MAUI and Blazor in an upcoming .NET 6 preview release.
In this release, we’ve introduced
BlazorWebView controls for WPF and Windows Forms apps that enable embedding Blazor functionality into existing Windows desktop apps based on .NET 6. Using Blazor and a hybrid approach you can start decoupling your UI investments from WPF & Windows Forms. This is a great way to modernize existing desktop apps in a way that can be brought forward onto .NET MAUI or used on the web. You can use Blazor to modernize your existing Windows Forms and WPF apps while leveraging your existing .NET investments.
To use the new
BlazorWebView controls, you first need to make sure that you have WebView2 installed.
To add Blazor functionality to an existing Windows Forms app:
- Update the Windows Forms app to target .NET 6.
- Update the SDK used in the app’s project file to
Microsoft.NET.Sdk.Razor.
- Add a package reference to Microsoft.AspNetCore.Components.WebView.WindowsForms.
- Add the following wwwroot/index.html file to the project, replacing
{PROJECT NAME}with the actual project name:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>Blazor app</title> <base href="/" /> <link href="{PROJECT NAME}.styles.css" rel="stylesheet" /> <link href="app.css" rel="stylesheet" /> </head> <body> <div id="app"></div> <div id="blazor-error-ui"> An unhandled error has occurred. <a href="" class="reload">Reload</a> <a class="dismiss">🗙</a> </div> <script src="_framework/blazor.webview.js"></script> </body> </html>
- Add the following app.css file with some basic styles to the wwwroot folder:
html, body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; } .valid.modified:not([type=checkbox]) { outline: 1px solid #26b050; } .invalid { outline: 1px solid red; } .validation-message { color: red; } #blazor-error-ui { background: lightyellow; bottom: 0; box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); display: none; left: 0; padding: 0.6rem 1.25rem 0.7rem 1.25rem; position: fixed; width: 100%; z-index: 1000; } #blazor-error-ui .dismiss { cursor: pointer; position: absolute; right: 0.75rem; top: 0.5rem; }
- For all files in the wwwroot folder, set the Copy to Output Directory property to Copy if newer.
- Add a root Blazor component, Counter.razor, to the project:
@using Microsoft.AspNetCore.Components.Web <h1>Counter</h1> <p>The current count is: @currentCount</p> <button @Count</button> @code { int currentCount = 0; void IncrementCount() { currentCount++; } }
- Add a
BlazorWebViewcontrol to the desired form to render the root Blazor component:);
- Run the app to see your
BlazorWebViewin action:
To add Blazor functionality to an existing WPF app, follow the same steps listed above for Windows Forms apps, except:
- Substitute a package reference for Microsoft.AspNetCore.Components.WebView.Wpf
- Add the
BlazorWebViewcontrol in XAML:
<Window x: <Grid> <blazor:BlazorWebView <blazor:BlazorWebView.RootComponents> <blazor:RootComponent </blazor:BlazorWebView.RootComponents> </blazor:BlazorWebView> </Grid> </Window>
- Set up the service provider as a static resource in the XAML code-behind file (such as
MainWindow.xaml.cs):
var serviceCollection = new ServiceCollection(); serviceCollection.AddBlazorWebView(); Resources.Add("services", serviceCollection.BuildServiceProvider());
- To workaround an issue with the WPF runtime build not finding Razor component types, add an empty partial class for the component in Counter.razor.cs:
public partial class Counter { }
- Build and run your Blazor based WPF app:
Give feedback
We hope you enjoy this preview release of ASP.NET Core in .NET 6. We’re eager to hear about your experiences with this release. Let us know what you think by filing issues on GitHub.
Thanks for trying out ASP.NET Core!
Will shadow copying for ASP.NET Core + IIS in ANCM still be experimental when .NET 6 releases? Will the extension still need to be explicitly added to Azure App Services?
These dev/deployment quality of life features are nice to see.
Ideally, Shadow Copying will not be experimental when .NET 6 releases. However, we want to make sure we are delivering the right solution that customers want for Shadow Copying. ANCM is also a separate module from the rest of .NET, which makes it difficult to iterate of features like shadow copying. Hence, we started with the “experimental” variable name for this release. Based on customer feedback and our overall comfort level (reliability, feature completeness, etc.), we will then remove the experimental naming.
Once .NET 6 release, you will not need to explicit add the site extension to Azure App Services. We will ship a new version of ANCM on Azure App Services instead.
Hooray for BlazorWebView!!
Hi @Daniel
Kudos to all involved with this release.
Quick question: In the “Get Started” section – you say “Install .NET 6 SDK” plus you say on windows it’s recommended to be on the latest preview of VS2019. What’s confusing is – Should I just install VS2019 latest preview and will that give me .NET 6 preview or install .NET 6 preview 3 + install the VS2019 16.10 Preview 1 (which is the latest) …
If somebody reads this for the first time it can be a little confusing to get started with .NET 6 preview 3.
Sorry if this has been addressed somewhere else. i was reading this and it startled me for a moment. I have VS2019 16.10 Preview 1 – and i though i already have .NET 6. So checked dotnet –info. then i realized i need to manually install .NET 6 Preview 3.
thoughts ?
Hi Lohith. You currently have to install the .NET 6 SDK separately from Visual Studio. We haven’t inserted .NET 6 into any Visual Studio previews yet. It will be a few months yet before that happens.
I thought so too. It may be good to make that clear in the getting started section. Thanks.
Hot Reload is neither working in ASP.NET Core MVC/Razor Pages nor in Blazor Wasm with Visual Studio 2019 Preview (16.10.0 Preview 1.0).
Here is my Blazor Wasm
launchSettings.josn:
You need to have installed VS2019 16.10 Preview 1 + .NET 6 SDK Preview 3 … have you done both ?
Hi Tanvir. Your launchSettings.json file looks right. I assume you’ve also installed .NET 6 Preview 3. You can check that by running
dotnet --versionfrom a command-prompt. It should show 6.0.100-preview.3.21202.5. You also need to run the app using
dotnet watchfor .NET Hot Reload to work currently. We haven’t integrated .NET Hot Reload into the latest VS yet, but that’s coming soon! The output of
dotnet watchshould say that hot reload is enabled if everything is working properly. If you’re still having issues, go ahead and create a GitHub issue with details about your environment and we’ll take a look.
He Daniel , if i have a WASM project backed by an asp.net core Web Api (In the same solution ) should i add “hotReloadProfile”: “blazorwasm” to it too ? and what about class library ?
Hi Yasser. Great question! Right now you have to pick a hot reload profile and go with it (blazorwasm or aspnetcore). We don’t have a great solution yet for doing full stack hot reload. That’s something we expect to address in a future preview. For class libraries though, hot reload should work for whatever process depends on that library. It it doesn’t work it’s a bug.
Hello,
Thanks for this post.
Could you add that TryRedeemPersistedState method (described in the previous post) no longer works for ApplicationState and can now be replaced by the TryTakeAsJson method please?
Have a good day.
Hi Max. Thanks for pointing this out! I’ve updated the upgrade steps accordingly.
Awesome Dan!
Thanks! The Hot reload will be super powerful.
I have a problem with the hot reload.
I have a Blazor WASM PWA (ASP.NET Core hosted) and changes in the actual .Client project doesn’t get updated, even though the console is saying:
… Client\Pages\Counter.razor.
watch : Hot reload of changes succeeded.
But changes are updated if a change is comming from my Component project (Razor Class Library), ViewModel project (Class Library).
Any ideas?
I’ve updated all packages to 6.0.0-preview.3.21201.13
dotnet –version
6.0.100-preview.3.21202.5
Thanks!
Hi Erik. It’s possible that a hot reload was attempted, but failed. Do you see any errors in the console output? Or is it possible the hot reload succeeded but the updated code wasn’t executed yet? Remember, .NET Hot Reload updates the code of the running app without restarting it. If you update initialization logic, the code will get updated but not necessarily rerun unless you do something to cause reinitialization.
Thanks for your reply!
Yes, didn’t see it at first. After a hot reload I get this error: (sorry for long text…)
Okey I think I found what’s causing the error.
If I create a new Blazor WASM project (Core hosted) and add hot reload to launchsettings.json everything works fine (both .Client proj and a simple RCL proj change works).
But if I install MatBlazor () and import it in my _Imports.razor the hot reload stops working and throws the above error. (Important to restart using CTRL + R after importing the MatBlazor library in _Imports.razor to trigger the error)
Is that expected?
Not expected. Please open a GitHub issue with these details and we’ll investigate:. Thank you for helping us identify this issue!
Created Issue:
Erik that normal .razor pages are still not supported ,, from what Daniel wrote :
With Blazor WebAssembly only method body replacement is currently supported. We’re working to expand the set of supported edits in .NET 6. When dotnet watch detects a change that cannot be applied using hot reload, it falls back to rebuilding and restarting the app.
Hmm okey, but if I create a new Blazor WASM (PWA) solution, the hot reload is working for a simple HTML change in Counter.Razor… So in my “real” application, I must have something that breaks the hot reload functionality.
I’ve added the problem causing the error in my answer to Daniel.
Hi Yasser. Changes in .razor files are supported, but in a limited way. The contents of .razor files get compiled in a generated C# class. All of the markup rendering logic is captured in a render method on that class, which can then be updated using hot reload. Other changes though, like adding members are not yet supported with the WebAssembly based runtime like they are with CoreCLR.
Awesome work! The hot-reload will speed up my development significantly!!!!!
With BlazorWebView components does not seem to be able to call methods or receive state change?
Is this a bug?
One bit of Blazor magic that you might be missing is you need to have the Microsoft.AspNetCore.Components.Web namespace in scope for the web specific constructs to take effect, like
@onclick. Typically this is done in your _Imports.razor file which then gets imported to all your other .razor files. Does adding an
@usingfor this namespace resolve your issue?
Hey, yes just discovered that and was about to post it but you got to it first.
The BlazorWebView will greatly simplify our project and spare us a lot of work that we would have to do for IPC if we had our app running on WebAssembly and simple WebView.
Can only say big thank you for the team work!
Also is there any chance we would see BlazorWebView on .NET 5?
Hi Oleg. Unfortunately no, BlazorWebView relies on changes that are only available with .NET 6. Also please note that .NET 6 is the next Long Term Support (LTS) release for .NET, while .NET 5 is a Current release. We strongly recommend updating from .NET 5 to .NET 6 once it is available. For more details on the .NET support policy, please see.
Thanks! We all looking forward to .NET 6!
I just try hot reload and it’s really fast. Great job! I can’t wait to .net 6 release. You are the best team in the entire world 😉
Great work guys. I created a new WPF application to test Blazor desktop, only step failing is adding Razor component. i have latest Visual studio and SDK.
Error is: no template could be found with the identity ‘microsoft.aspnetcore.components.razorcomponent’.
Any regression here?
I created working example here:
Looks like you accidentally put Counter.razor under the wwwroot folder. Here’s a PR that fixes things up so that they now work:. | https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-preview-3/ | CC-MAIN-2021-43 | refinedweb | 4,051 | 59.6 |
CPU limits and aggressive throttling in Kubernetes
Have you seen your application get stuck or fail to respond to health check requests, and you can’t find any explanation? It might be because of the CPU quota limit. We will explain more here.
TL;DR:
We would highly recommend removing CPU Limits in Kubernetes (or Disable CFS quota in Kublet) if you are using a kernel version with CFS quota bug unpatched. There is a serious, known CFS bug in the kernel that causes un-necessary throttling and stalls.
At Omio, we are 100% Kubernetes. All our stateful and stateless workloads run completely on Kubernetes (hosted using Google’s Kubernetes Engine). Since the last 6 months, we’ve been seeing random stalls. Applications stuck or failing to respond to health checks, broken network connections and so on. This sent us down a deep rabbit hole.
This article covers the following topics.
- A primer on containers & kubernetes
- How CPU request and limit is implemented
- How CPU limit works in multi-core environments
- How do you monitor CPU throttling
- How do you recover
A primer on Containers & Kubernetes
Kubernetes (abbreviated as k8s) is pretty much a de-facto standard in the infrastructure world now. It is a container orchestrator.
Containers
In the past, we used to create artifacts such as Java JARs/WARs or Python Eggs or Executables, and throw them across the wall for someone to run them on servers. But to run them, there is more work — application runtime (Java/Python) has to be installed, appropriate files inappropriate places, specific OSes and so on. It takes a lot of configuration management, and is a frequent source of pain between developers and sysadmins. Containers change that. Here, the artifact is a Container image. Imagine it as a fat executable with not only your program, but also the complete runtime (Java/Python/…), necessary files and packages pre-installed & ready to run. This can be shipped and run on a variety of servers without any further customized installations needed.
Containers also run in their own sandboxed environment. They have their own virtual network adapter, their own restricted filesystem, their own process hierarchy, their own CPU and memory limits, etc. This is a kernel feature called namespaces.
Kubernetes
Kubernetes is a Container orchestrator. You give it a pool of machines. Then you tell it: “Hey kubernetes — run 10 instances of my container image with 2 cpus and 3GB RAM each, and keep it running!”. Kubernetes orchestrates the rest. It will run them wherever it finds free CPU capacity, restart them if they are unhealthy, do a rolling update if we change the versions, and so on.
Essentially, Kubernetes abstracts away the concept of machines, and makes all of them a single deployment target.
Understanding Kubernetes request and limit
OK, we understand what Containers and Kubernetes are. We also see that, multiple containers can fit inside the same machine.
This is like flat sharing. You take some big flats (machines/nodes) and share it with multiple, diverse tenants (containers). Kubernetes is our rental broker. But how does it keep all those tenants from squabbling with each other? What if one of them takes over the bathroom for half a day? ;)
This is where request and limit come into picture. CPU “Request” is just for scheduling purposes. It’s like the container’s wishlist, used mainly to find the best node suitable for it. Whereas CPU “Limit” is the rental contract. Once we find a node for the container, it absolutely cannot go over the limit.
And here is where the problem arises…
How Kubernetes request & limit is implemented
Kubernetes uses kernel throttling to implement CPU limit. If an application goes above the limit, it gets throttled (aka fewer CPU cycles). Memory requests and limits, on the other hand, are implemented differently, and it’s easier to detect. You only need to check if your pod’s last restart status is OOMKilled. But CPU throttling is not easy to identify, because k8s only exposes usage metrics and not cgroup related metrics.
CPU Request
For the sake of simplicity, let’s discuss how it organized in a four-core machine.
The k8s uses a cgroup to control the resource allocation(for both memory and CPU ). It has a hierarchy model and can only use the resource allocated to the parent. The details are stored in a virtual filesystem (
/sys/fs/cgroup). In the case of CPU it’s
/sys/fs/cgroup/cpu,cpuacct/*.
The k8s uses
cpu.share file to allocate the CPU resources. In this case, the root cgroup inherits 4096 CPU shares, which are 100% of available CPU power(1 core = 1024; this is fixed value). The root cgroup allocate its share proportionally based on children’s
cpu.share and they do the same with their children and so on. In typical Kubernetes nodes, there are three cgroup under the root cgroup, namely
system.slice,
user.slice, and
kubepods. The first two are used to allocate the resource for critical system workloads and non-k8s user space programs. The last one,
kubepods is created by k8s to allocate the resource to pods.
If you look at the above graph, you can see that first and second cgroups have 1024 share each, and the
kubepod has 4096. Now, you may be thinking that there is only 4096 CPU share available in the root, but the total of children’s shares exceeds that value (6144). The answer to this question is, this value is logical, and the Linux scheduler (CFS) uses this value to allocate the CPU proportionally. In this case, the first two cgroups get 680 (16.6% of 4096) each, and kubepod gets the remaining 2736. But in idle case, the first two cgroup would not be using all allocated resources. The scheduler has a mechanism to avoid the wastage of unused CPU shares. Scheduler releases the unused CPU to the global pool so that it can allocate to the cgroups that are demanding for more CPU power(it does in batches to avoid the accounting penalty). The same workflow will be applied to all grandchildren as well.
This mechanism will make sure that CPU power is shared fairly, and no one can steal the CPU from others.
CPU Limit
Even though the k8s config for Limit and Requests looks similar, the implementation is entirely different; this is the most misguiding and less documented part.
The k8s uses CFS’s quota mechanism to implement the limit. The config for the limit is configured in two files
cfs_period_us and
cfs_quota_us(next to
cpu.share) under the cgroup directory.
Unlike
cpu.share, the quota is based on time period and not based on available CPU power.
cfs_period_us is used to define the time period, it’s always 100000us (100ms). k8s has an option to allow to change this value but still alpha and feature gated. The scheduler uses this time period to reset the used quota. The second file,
cfs_quota_us is used to denote the allowed quota in the quota period.
Please note that it also configured in
us unit. Quota can exceed the quota period. Which means you can configure quota more than 100ms.
Let’s discuss two scenarios on 16 core machines (Omio’s most common machine type).
Let’s say you have configured 2 core as CPU limit; the k8s will translate this to 200ms. That means the container can use a maximum of 200ms CPU time without getting throttled.
And here starts all misunderstanding. As I said above, the allowed quota is 200ms, which means if you are running ten parallel threads on 12 core machine (see the second figure) where all other pods are idle, your quota will exceed the limit in 20ms (i.e. 10 * 20ms = 200ms), and all threads running under that pod will get throttled for next 80ms (stop the world). To make the situation worse, the scheduler has a bug that is causing unnecessary throttling and prevents the container from reaching the allowed quota.
Checking the throttling rate of your pods
Just login to the pod and run
cat /sys/fs/cgroup/cpu/cpu.stat.
nr_periods— Total schedule period
nr_throttled— Total throttled period out of nr_periods
throttled_time— Total throttled time in ns
So what really happens?
We end up with a high throttle rate on multiple applications — up to 50% more than what we assumed the limits were set for!
This cascades as various errors — Readiness probe failures, Container stalls, Network disconnections and timeouts within service calls — all in all leading to reduced latency and increased error rates.
Fix and Impact
Simple. We disabled CPU limits until the latest kernel with bugfix was deployed across all our clusters.
Immediately, we found a huge reduction in error rates (HTTP 5xx) of our services:
HTTP Error Rates (5xx)
p95 Response time
Utilization costs
What’s the catch?
We said at the beginning of this article:
This is like flat sharing. Kubernetes is our rental broker. But how does it keep all those tenants from squabbling with each other? What if one of them takes over the bathroom for half a day? ;)
This is the catch. We risk some containers hogging up all CPUs in a machine. If you have a good application stack in place (e.g. proper JVM tuning, Go tuning, Node VM tuning) — then this is not a problem, you can live with this for a long time. But if you have applications that are either poorly optimized, or simply not optimized (
FROM java:latest) — then results can backfire. At Omio we have automated base Dockerfiles with sane defaults for our primary language stacks, so this was not an issue for us.
Please do monitor USE (Utilization, Saturation and Errors) metrics, API latencies and error rates, and make sure your results match expectations.
This was a wild ride and discovery. The following resources helped us a lot in understanding:
-
-
-
-
- Kubernetes bug reports: | |
Did you encounter similar issues or want to share your experiences with throttling in containerized production environments? Let us know in the Comments below!
If you liked this article and want to work on similar challenges at scale, why not consider joining forces :) | https://medium.com/omio-engineering/cpu-limits-and-aggressive-throttling-in-kubernetes-c5b20bd8a718 | CC-MAIN-2020-16 | refinedweb | 1,697 | 64.91 |
Subject: Re: [boost] [accumulator] A lot of unused "parameter" warnings
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2011-10-01 14:51:09
Le 01/10/11 20:03, Eric Niebler a écrit :
> On 10/1/2011 9:29 AM, Vicente J. Botet Escriba wrote:
>> Would you accept a patch that resolve them by commenting the
>> parameter name?
> Patches gladly accepted. Just open a ticket on svn.boost.org and
> attach the patch. Thanks!
>
Well, I have reached to remove the warnings in Boost.Parameter and
Boost.Fusion.
The warnings in Boost.Accumulators are related to static variables
included in a unnamed namespace such as
../../../boost/accumulators/numeric/functional_fwd.hpp:187:38: warning:
unused variable 'min_assign' [-Wunused-variable]
extern op::min_assign const &min_assign;
Unfortunately, I don't know how to silent these warnings :(
Have you an idea how to silent them?
Best,
Vicente
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2011/10/186384.php | CC-MAIN-2020-10 | refinedweb | 167 | 54.49 |
How to build a heatmap in Python
Heatmaps are effective visualization tools for representing different values of data over a specific geographical area. You could, for example, use them for temperatures, rainfall or electricity use. In this tutorial, I will provide a step-by-step guide on how to make a heatmap using Python and the Google Maps API.
First, you need to install three packages.
Numpy is a commonly-used package in Python. It can perform mathematical functions such as adding and multiplying, as well as creating N-dimensional array objects to store numbers. In this tutorial, we will be using it to create two-dimensional arrays to store values so they can then be plotted on the heatmap.
Pandas is a dataframe that makes reading CSV files very convenient. With this package installed, you can easily select specific rows or values inside a csv.
gmaps is the package we need to connect with Google Maps so we can create a heatmap with it.
Let’s import the packages first.
import numpy as np
import pandas as pd
import gmaps
import gmaps.datasets
Now let’s read our csv file with pandas. The data is from Analyze Boston, the City of Boston’s open data hub.
crime=pd.read_csv("Boston_crime_incidents.csv")
crime.head()
The pandas dataframe makes it convenient to select specific values in your csv.
crime['year'][0]
2019
crime['lat'][2736]
42.35331987
Next, select your latitude and longitude range. Since I am plotting a heatmap for 2018 Boston crime rates, I will choose the longitude range to be between -71.21 and -71, and latitude 42.189 to 42.427.
The first line of code below divides the longitude range into 100 equal intervals, and second line of code divides the latitude range into 100 equal intervals. These two lines are required because to plot the heatmap. We will input different crime rates into 10,000 cells on a 100 x 100 grid over Boston based on their locations. If you want to increase the resolution of your heatmap, feel free to use a 500 x 500 or a 1000 x 1000 grid.
Lon = np.arange(-71.21, -71, 0.0021) Lat = np.arange(42.189, 42.427, 0.00238)
First, we create arrays of 0s that are 100 wide and 100 tall to store crime rates.
Crime_counts = np.zeros((100,100))
Next, we select crime rates from 2018.
crime_2018 = crime[crime['year'] == 2018]
Next, we’ll organize the data.
The first for loop is created to go through all 2018 crime data. The second for loop is created to store crime rates by location. To do this, we go through latitude and longitude values for each incident. If lat-lon values of an incident match with one of the small cells in the 100×100 grid we created over Boston, we add 1 to that small cell. By the end of this execution, all locations will be recorded in one of the small cells in the 100×100 grid.
for a in range(len(crime_2018)):
for b1 in range(100):
if Lat[b1] – 0.00105 <= crime_2018[‘lat’].values[a] < Lat[b1] + 0.00105:
for b2 in range(100):
if Lon[b2] – 0.00119 <= crime_2018[‘long’].values[a] < Lon[b2] + 0.00119:
Crime_counts[b1,b2] += 1
To create the heatmap, you need to type in your Google API key. Instructions on how to create it can be found here.
gmaps.configure(api_key=”AI….”)
The pandas dataframe, the package we use to input data into gmaps, can’t take two-dimensional arrays per column. So we need to put the values of latitudes, longitudes and crime counts in 1d arrays.
longitude_values = [Lon,]*100 latitude_values = np.repeat(Lat,100) Crime_counts.resize((10000,))
heatmap_data = {'Counts': Crime_counts, 'latitude': latitude_values, 'longitude' : np.concatenate(longitude_values)} df = pd.DataFrame(data=heatmap_data)
locations = df[['latitude', 'longitude']] weights = df['Counts'] fig = gmaps.figure() heatmap_layer = gmaps.heatmap_layer(locations, weights=weights) fig.add_layer(gmaps.heatmap_layer(locations, weights=weights)) fig
… and now we have a heatmap!
- What I learned applying data science to U.S. redistricting - January 20, 2020
- How to build a heatmap in Python - February 18, 2019
- The future of machine learning in journalism - January 2, 2019
Hi Floris,
I am a Python newbie. I have tried this in Idle and Pycharm 2019 Community edition. How and where does the heatmap display? I can run the program without errors but not get any output.
if anyone installed gmap for the first time they need to restart kernal so that maps can be displayed properly otherwise they will not be able to see any map
Hi,
This code is great, but I get the “arrays must all be same length” error. Please can you let me know where I’m going wrong?
Regards,
Plto77
same error i am also getting…u got solution or not?
hi, the same for me 🙁
Hello, could you provide a link to the source code itself? Maybe upload it on GitHub/GitLab?
Thanks for the guide. I follow exactly but the heat map does not show. I am using Visual Code Studio. Any possible setting could be wrong?
Hi I think you need to use Jupyter notebooks and not VS Code Editor for this. | https://www.storybench.org/how-to-build-a-heatmap-in-python/ | CC-MAIN-2022-05 | refinedweb | 872 | 76.01 |
SOAP Encodings, WSDL, and XML Schema Types
February 20, 2002
Martin Gudgin and Timothy Ewald
Using a web service involves a sender and a receiver exchanging at least one XML message. The format of that message must be defined so that the sender can construct it and the receiver can process it. The format of a message includes the overall structure of the tree, the local name and namespace name of the elements and attributes used in the tree, and the types of those elements and attributes..
SOAP Encoding
The SOAP encoding defines a set of rules for mapping programmatic types to XML. This includes rules for mapping compound data structures, array types, and reference types. With respect to compound data structures, the approach taken is reasonably straightforward; all data is serialized as elements, and the name of any given element matches the name of the data field in the programmatic type. For example, given the following Java class,
class Person { String name; float age; }
the
name and
age fields would be serialized using elements whose
local names where
name and
age respectively. Both elements would
be unqualified, that is, their namespace name would be empty. In cases where the name
of a
field would not be a legal XML name Appendix A of the spec provides a mapping algorithm.
The mapping of reference types is more complicated. It involves serializing the instance
and marking it with an unqualified attribute whose local name is
id. All other
references to that instance are then serialized as empty elements with an unqualified
attribute whose local name is
href. The value of the
href is a URI
that references the relevant serialized instance via its
id attribute. This
mechanism provides a way to serialize graphs, including cyclic graphs in XML.
Mapping Types
The SOAP Encoding also provides mappings from programmatic data types to the data types found in XML Schema Part 2: Datatypes. Thus given a programmatic data structure, the name and type of each element in the serialized XML can be determined. People have observed that the SOAP Encoding rules are as much about mapping between type systems as they are about mapping between instance formats.
Given a web service that accepts
Person data structures as input, perhaps to
add them to some list of people that it maintains, a SOAP message to that web service
might
look like this:
<soap:Envelope xmlns: <soap:Body> <pre:Add xmlns: <person> <name>Hayley</name> <age>30</age> </person> </pre:Add> </soap:Body> </soap:Envelope>
The value of the
encodingStyle attribute states that the SOAP Encoding rules
were followed when serializing the data. This enables the deserializer at the other
end of
the pipe to deserialize the message correctly. Other encoding styles can be used with
SOAP
in which case the
encodingStyle attribute would have a different URI value..
There are some cases where exact type information may not be known until runtime.
One is
the case of a web service which accepts data in a similar fashion to the COM
VARIANT, CORBA
any, or Java
Object. Such a service
specifies nothing about the type of the data at design time. Rather type information
must be
provided at runtime. Such services in reality do not accept absolutely any type but
work on
a reasonably small subset of types, generating errors when unknown types are encountered.
Another case is where further classes are derived from the
Person class, for
example,
RacingDriver and
FootballPlayer. Assuming the web service
understands these classes, they could be submitted in request messages.
In both cases, the "totally" polymorphic element and the more specific case of explicitly derived types, the element name is no longer enough to fully identify the type of the element. Something more is needed.
The SOAP Encoding rules allow the use of the
type attribute from the namespace to be used to specify
that a particular type is being passed at runtime. The
person element in the
message would then appear look like
<person xmlns: <name>Martin</name> <age>34</age> <bestplace>6th</bestplace> </person>
It is worth noting that the
xsi:type attribute is of type
QName.
Thus, strictly speaking, the above example refers to an unqualified
RacingDriver type. In reality a namespace should probably be assigned to
types to avoid name clashes. Also,
xsi:type is only needed when the exact type
is not known until runtime. In cases where both sides know the types in advance, the
most
common case,
xsi:type, is redundant.
Conclusions
Whenever messages are sent some type information is known in advance. In some cases
all
types are completely known and further information beyond the element names is not
needed.
In other cases, more specific type information may be communicated at runtime. In
such
cases, the
xsi:type attribute is used and the types really need to be assigned
to namespaces.
It would seem that whenever and however we define message formats for a given web service exchange we are really defining a schema for those messages. Thus the SOAP encoding is really about mapping from programmatic type systems to an XML type system, that of XML Schema. Some aspects of that mapping work very well; other aspects, such as references, do not map particularly well, due to the tree nature of XML. Given that the serialization format is XML, and XML is a tree, serious thought should be given to whether more esoteric programmatic constructs such as references need to be directly modeled in SOAP. If such constructs really are needed, an XML Schema friendly approach should be taken. | https://www.xml.com/pub/a/2002/02/20/endpoints.html | CC-MAIN-2018-51 | refinedweb | 929 | 50.46 |
Source
backmongo / README.md
BackMongo
You could install all with
$ [sudo] pip install -r requirements.txt
Use
as a Flask extension
from flask import Flask from flask.ext import backmongo app = Flask(__name__) backmongo.init_app(app) if __name__ == "__main__": app.run(debug=True)
From the command line
$ python flask_backmongo.py path/to/project/dir
Examples
There's an example in examples/todos/ (a slightly modified version of this) later install the other required modules locally
$ npm install should $ npm install jquery $ npm install backbone $ npm install xmlhttprequest
Then you have to type in the console
$ make
this starts a flask app that use backmongo, execute the javascript tests with mocha and stop the flask app.
By default the tests are working in a data base called backmongo. If you need to change this create a file named backmongo_conf.py in the root folder, or in some place in your PYTHONPATH, and set the data base name in the variable DATABASE. You could see an configuration file example in examples/todo/static/backmongo_conf.py | https://bitbucket.org/remosu/backmongo/src/e1f3f6fe28bd/README.md | CC-MAIN-2015-48 | refinedweb | 173 | 57.37 |
User Tag List
Results 1 to 1 of 1
Thread: Error loading Page
- Join Date
- Jan 2006
- 10
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Error loading Page
Hope anyone can be of help to me.
I'm working on this small application and I'm experiencing this message coming up when I test the page. In IE, I get this message below but Its too vauge I can't seem to trace the problem eventhough the page displays but with error.
Line: 63
Char: 16
Error: Exptected '/'
Code: 0.
URL:
Firstly, the Default.aspx has got a line 63. I disabled the javascript files attached but the same message keeps coming up so I figure its not the javascript file
In Firefox, the page doesn't display at all but the following message is displayed:
XML Parsing Error: no element found
Location:
Line Number 1, Column 1:
The Default.aspx file is using a master file so i figured the XML namespace might just be the problem but the declaration is fine. Not sure what it means by no element found. I have double checked the syntax in both the aspx files and the master pages put can't seem to find the problem. I figured intellisense would have highlighted that for me in anycase.
Has anyone encountered a similar thing before? Any clues or leads? Its really frustrating and been at it a few days now.
Thanks in advance
Bookmarks | http://www.sitepoint.com/forums/showthread.php?504634-Error-loading-Page&p=3554210 | CC-MAIN-2017-13 | refinedweb | 243 | 72.56 |
I was reading More Joel on Software when I came across Joel Spolsky saying something about a particular type of programmer knowing the difference between an
int and an
Integer in Java/C# (Object Oriented Programming Languages).
So, what is the difference?
2016年12月02日50分48秒
In Java, the 'int' type is a primitive , whereas the 'Integer' type is an object.
In C#, the 'int' type is the same as
System.Int32.
2016年12月02日50分48秒
Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:
Integer i = new Integer(6);
You could call some method on i:
String s = i.toString();//sets s the string representation of i
Whereas with an int:
int i = 6;
You cannot call any methods on it, because it is simply a primitive. So:
String s = i.toString();//will not Ojbect vs. int primitive comparison
2016年12月02日50分48秒
I'll add to the excellent answers given above, and talk about boxing and unboxing, and how this applies to Java (although C# has it too). I'll use just Java terminology, because I am more au fait with that.
As the answers mentioned,
int is just a number (called the unboxed type), whereas
Integer is an object (which contains the number, hence a boxed type). In Java terms, that means (apart from not being able to call methods on
int), you cannot store
int:
Deque<Integer> queue; void add(int n) { queue.add(n); } int remove() { return queue.remove(); }
Java 1.4 or earlier (no generics either):
Deque queue; void add(int n) { queue.add(Integer.valueOf(n)); } int remove() { return ((Integer) queue.remove()).intValue(); }!
2016年12月02日50分48秒
I'll just post here since some of the other posts are slightly inaccurate in relation to C#.
Correct:
int is an alias for
System.Int32.
Wrong:
float is not an alias for
System.Float, but for
System.Single
Basically, int is a reserved keyword in the C# programming language, and is an alias for the
System.Int32 value:
int i;
defines a variable
i of:
object o = i;
this will create a boxed copy of the contents of
i on.)
2016年12月02日50分48秒:
Integer i1 = new Integer(127); Integer i2 = new Integer(127); System.out.println(i1 == i2); // true
While this returns false:
Integer i1 = new Integer(128); Integer i2 = new Integer(128); System.out.println(i1 == i2); //.
System.out.println(i1.equals(i2)); // true
More info at java.net Example at bexhuff.com
2016年12月02日50分48秒.
int aNumber = 4; int anotherNum = aNumber; aNumber += 6; System.out.println(anotherNum); // Prints 4
An object is a dynamically created class instance or an array. The reference values (often just references) are pointers to these objects and a special null reference, which refers to no object. There may be many references to the same object.
Integer aNumber = Integer.valueOf(4); Integer anotherNumber = aNumber; // anotherNumber references the // same object as aNumber
Also in Java everything is passed by value. With objects the value that is passed is the reference to the object. So another difference between int and Integer in java is how they are passed in method calls. For example in
public int add(int a, int b) { return a + b; } final int two = 2; int sum = add(1, two);
The variable two is passed as the primitive integer type 2. Whereas in
public int add(Integer a, Integer b) { return a.intValue() + b.intValue(); } final Integer two = Integer.valueOf(2); int sum = add(Integer.valueOf(1), two);
The variable two is passed as a reference to an object that holds the integer value 2.
@WolfmanDragon: Pass by reference would work like so:
public void increment(int x) { x = x + 1; } int a = 1; increment(a); // a is now 2
When increment is called it passes a reference (pointer) to variable a. And the increment function directly modifies variable a.
And for object types it would work as follows:
public void increment(Integer x) { x = Integer.valueOf(x.intValue() + 1); } Integer a = Integer.valueOf(1); increment(a); // a is now 2
Do you see the difference now?
2016年12月02日50分48秒
In C#, int is just an alias for
System.Int32, string for
System.String, double for
System.Double etc...
Personally I prefer int, string, double, etc. because they don't require a
using System; statement :) A silly reason, I know...
2016年12月02日50分48秒
In platforms like Java,
ints are primitives while
Integer.
2016年12月02日50分48秒
int is used to declare primitive variable
e.g. int i=10;
Integer is used to create reference variable of class Integer
Integer a = new Integer();
2016年12月02日50分48秒
There are many reasons to use wrapper classes:
2016年12月02日50分48秒:
void DoStuff() { System.Console.WriteLine( SomeMethod((int)5) ); System.Console.WriteLine( GetTypeName<int>() ); } string SomeMethod(object someParameter) { return string.Format("Some text {0}", someParameter.ToString()); } string GetTypeName<T>() { return (typeof (T)).FullName; }
2016年12月02日50分48秒
2016年12月02日50分48秒
An int and Integer in Java and C# are two different terms used to represent different things. It is one of the the primitive data types that can be assigned to a variable that can store exactly. One value of its declared type at a time.
For example:
int number = 7;
Where
int is the datatype assigned to the variable number which holds the value seven. So an
int is just a primitive not an object.
While an
Integer:
Integer number = new Integer(5);
2016年12月02日50分48秒
In both languages (Java and C#)
int which is a value type using a part of memory that belongs to the reference type on the heap.
java provides
java.lang.Integer which is a reference type operating on
int. The methods in
Integer can 4-byte value in memory can be interpreted as a primitive int, that can be manipulated by instance of System.Int32.So int is an alias for
System.Int32.When using integer-related methods like
int.Parse(),
int.ToString() etc. Integer is compiled into the FCL
System.Int32 struct calling the respective methods like
Int32.Parse(),
Int32.ToString().
2016年12月02日50分48秒 :
int x; Integer y;
x and y are both variables of type int but y is wrapped by an Integer class and has several methods that you use,but i case you need to call some functions of Integer wrapper class you can do it simply.
Integer.toString(x);
but be aware that both x and y are corect but if you want to use them just as a primitive type, use the simple form (used for defining x).
2016年12月02日50分48秒.
2016年12月02日50分48秒
In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.
For example:
double doubleValue = 156.5d; Double doubleObject = new Double(doubleValue); Byte myByteValue = doubleObject.byteValue (); String myStringValue = doubleObject.toString();
Primitive data types are store the fastest available memory where the Helper class is complex and store in heep memory.
reference from "David Gassner" Java Essential Training.
2016年12月02日50分48秒:
Integer(int num) Integer(String str) throws NumberFormatException Double(double num) Double(String str) throws NumberFormatException
Example of boxing/unboxing:
class ManualBoxing { public static void main(String args[]) { Integer objInt = new Integer(20); // Manually box the value 20. int i = objInt.intValue(); // Manually ubox the value 20 System.out.println(i + " " + iOb); // displays 20 20 } }
Example of autoboxing/autounboxing:
class AutoBoxing { public static void main(String args[]) { Integer objInt = 40; // autobox an int int i = objInt ; // auto-unbox System.out.println(i + " " + iOb); // displays 40 40 } }
P.S. Herbert Schildt's book took as a reference.
2016年12月02日50分48秒
In java as per my knowledge if you learner then, when you write int a; then in java generic it will compile code like integer a=new integer. So,as per generics integer is not used but int is used. so there is so such difference there.
2016年12月02日50分48秒 | http://www.91r.net/ask/608.html | CC-MAIN-2016-50 | refinedweb | 1,283 | 57.98 |
twisted.logger.Logger(object)class documentation
twisted.loggerView Source (View In Hierarchy)
A
Logger emits log messages to an observer. You should instantiate it as a class or module attribute, as documented in
this module's documentation.
Derive a namespace from the module containing the caller's caller.
When used as a descriptor, i.e.:
# File: athing.py class Something(object): log = Logger() def hello(self): self.log.info("Hello")
a
Logger's namespace will be set to the name of the class it is declared on. In the above example, the namespace would be
athing.Something.
Additionally, its source will be set to the actual object referring to the
Logger. In the above example,
Something.log.source would be
Something, and
Something().log.source would be an instance of
Something.
Emit a log event to all log observers at the given level.
Log a failure and emit a traceback.
For example:
try: frob(knob) except Exception: log.failure("While frobbing {knob}", knob=knob)
or:
d = deferredFrob(knob) d.addErrback(lambda f: log.failure("While frobbing {knob}", f, knob=knob))
This method is generally meant to capture unexpected exceptions in code; an exception that is caught and handled somehow should be logged, if appropriate, via
Logger.error instead. If some unknown exception occurs and your code doesn't know how to handle it, as in the above example, then this method provides a means to describe the failure in nerd-speak. This is done at
LogLevel.critical by default, since no corrective guidance can be offered to an user/administrator, and the impact of the condition is unknown.
Emit a log event at log level
LogLevel.debug.
Emit a log event at log level
LogLevel.info.
Emit a log event at log level
LogLevel.warn.
Emit a log event at log level
LogLevel.error.
Emit a log event at log level
LogLevel.critical. | https://twistedmatrix.com/documents/20.3.0/api/twisted.logger.Logger.html | CC-MAIN-2022-05 | refinedweb | 313 | 60.82 |
EU, UN to Wrestle Internet Control From US 1974
Anonymous Coward writes "The Guardian is reporting that the EU, obviously unimpressed with the US's refusal to relinguish control of the Internet, will be forming several comittees and forums with a mind to forcibly remove control of the Internet from the United States." From the article: ."
The UN has finally lost it (Score:3, Insightful)
I've said it before, and I'll say it again. The internet root servers are working fine. The UN has presented no compelling arguments as to why it should be turned over to an overly beaurocratic entity that has a poor track record for making joint ventures work. In absence of a compelling argument, the only thing that the UN should hear is, "If it ain't broke, don't fix it!"
Keep in mind that the root servers are currently under the control of a private organization. While the servers themselves may reside in the US, the organization that controls them is a true international entity. The US government does not exert direct control over ICANN, and will not agree to do so in order to satisfy a UN hissy fit.
I can only speak for myself, but I would be ashamed of my government's actions if I lived in one of the UN countries that is pushing this resolution. I think this quote from the article sums it up:
"The idea of the council is so vague. It's not clear to me that governments know what to do about anything at this stage apart from get in the way of things that other people do."
Amen.
Re:The UN has finally lost it (Score:4, Insightful)
Re:The UN has finally lost it (Score:4, Insightful)
As for the UN and EU split, that was a distinction made by the fine article, and one I only carried as far as the article did. Beyond that, we are speaking purely of the UN. The UN *has* made resolutions, then failed to act on them. The UN *has* censured the United States for acting on those resolutions. The perfect example of this has been the Iraq war, which was a UN resolution that the UN got upset about when the US took action. Do you deny these things? If so, please be more detailed.
It's easy to say, "ha ha, you're wrong", but it's much more difficult to carry on a reasonable ccnversation.
Re:The UN has finally lost it (Score:4, Interesting)
France (and other security councle members) said before voting on the last UN resolution that it was not allowing it to be used as an excuse for military action. The resolution was made to force Saddam to allow weapon inspectors. If military action would be necessary a new UN resolution would be have to be made with a new vote. The US went anyway without such a resolution, and has got the ass kicked in Iraq with a war done under false pretenses. Now the US administration is using the UN resolution as an excuse for invading a sovereign nation!!! Of course, it is the same administration that is trying to undermind UN on every turn. Make up your mind, either you follow what UN says and you don't invade, or you invade and take responsibility for your own action without blaming the UN. Show some balls.
pot to kettle: sloppy argument! (Score:5, Insightful)
You miss the principle of Charity. Rather than call his logic invalid because he started with "EU/UN" and then dropped it in favor of just "UN", you should charitably add the "EU/" yourself and see if his argument holds up. Otherwise, you're just nitpicking at spelling errors at best or launching a veiled ad hominem "UN-hating gingoistic bigot!" attack at worst. As always win you ignore Charity, you may win points with the audience, but logic isn't a popularity contest.
That said, you completely failed to address his major arguments, which were:
There are obvious counterpoints to all of these, and I only consider #3 to be worthwhile. But you didn't make those counterpoints at all.
What is about to happen is that the Silver Age of the Internet is about to end. The Golden Age was before the web; the Silver age has lasted since '91 or so. Now we'll see fragmentation and provincialism. Whether that is good or bad is an open question, but it will surely be different.
What's really at stake in this struggle is who will have the power to block network access to and from a given country. Some countries are afraid of the US having that power, which they would "never" use, while the US is afraid of the UN having that power, which they also would "never" use.
It's neither more, nor less, than that.
Re:The UN has finally lost it (Score:3, Insightful)
The fact is that the Internet has moved beyond the national level. Whether you like it or not, the US' role WILL WANE. Taking a hard-line stance will, potentially, simply ensure that the rest of the wo
Re:The UN has finally lost it (Score:4, Insightful)
The US always has paid for its own messes
... and eventually, for everyone else's.
Re:The UN has finally lost it (Score:4, Insightful)
Let's see how long the US holds together without the monetary support of the rest of the world. If countries like China were to just stop buying your government debt (let alone trying to get rid of it) then you won't even be able to pay for your mighty military. You've already given up control of your country and destiny to foreign powers who could crush you and the global economy if they had to.
And people with your attitude wonder why there is so much rampant anti-Americanism around the world today. You're too arrogant and conceited to see it. Thank goodness 99% of the Americans I know are fantastic people and don't live up to this stereotype.
Re:The UN has finally lost it (Score:5, Insightful)
If countries like China were to just stop buying your government debt (let alone trying to get rid of it) then you won't even be able to pay for your mighty military.
Actually we weren't using deficit spending to pay for our military (or anything else for that matter) until Dubya took office and gave a giant tax cut to the rich. Based on that fact I'd say that we really don't require you buying up all our debt to pay for our war machine.
And people with your attitude wonder why there is so much rampant anti-Americanism around the world today. You're too arrogant and conceited to see it.
And people with your attitude wonder why Americans distrust the UN and dislike Europe. I've heard Europeans pick apart every part of America from our welfare system, our politics, our religious beliefs, our support of Israel, our banking system, etc etc etc. You call us arrogant? You are too arrogant to think that just maybe we are right once in awhile.
I have a revolutionary new theory (Score:5, Insightful)
Maybe, just maybe...
the US is a bunch of hos.
the EU is a bunch of hos.
people in general, are a bunch of hos.
I assume your world has been rocked.
(people aren't really that different. stop pretending your nationstate is unique! it's not!)
Re:The UN has finally lost it (Score:5, Interesting)
> rest of the world.
Just a point; if anyone tried to destroy the US monetarily, the effect on the rest of the workl would be easily as bad. The dependency works both ways. Yes, the US is dependent of foreign trade, but most of the nations we trade with are dependent on it as well. Some few nations would just suffer loss of income and products, but many would suffer pains equal to some of the worst natural disasters.
> And people with your attitude wonder why there is so much rampant
> anti-Americanism around the world today. You're too arrogant and conceited
> to see it.
Just a point. There are a few hundred million people in the US. All of them are not arrogant and conceited, any more than all the French are rude and smelly, all Muslims are terrorists, or all the Chinese are great at math.
Yes, there are legitimate grievances against the US. But much or what is perceived as US arrogance is merely the US attempting to retain it's own constitutional structure. A large portion of the world wants the US to tear up our constitution and remake ourselves in the image of the EU. And we aren't interested, now or ever.
> Thank goodness 99% of the Americans I know are fantastic people and
> don't live up to this stereotype.
Good to hear it. But stereotypes are like that. Most of the what the world knows about the US is garbage, heavily influenced by Hollywood. Just as most of what most Americans know about the Middle East is from Hollywood bull and news reports showing scenes of war and terror.
Thanks for your observations.
Re:The UN has finally lost it (Score:4, Funny)
I am assuming that the majority of Americans you know are not from internet message boards....
Re:The UN has finally lost it (Score:5, Insightful)
The clear statement was: "No, we will not". Some folks ask: "Well, why not?"
Now the EU and other countries will install their own root DNS servers and that's the end of the story.
No need to get emotional about it.
Lesson? Don't go back on your deals (Score:5, Informative)
Back in July the US surprised everyone by saying that despite the previous agreement that ICANN control of root servers would end in Sept 2006, they would instead keep control into the future, not matter what everyone else thought. [theregister.co.uk]
Everyone else was understandable miffed, particularly when they saw it was being driven politically, by Bush, and that ICANN continued to be ICANN and were trying to tax domain registrations, including country specific domain registrations [theregister.co.uk] (.de,
.uk, etc.)
Work was ongoing to redefine things on the run up to the expected ending of ICANN control, including automated management functions [theregister.co.uk] and working groups to define future structure [theregister.co.uk]. I'm sure Bush and his fundamentalist Christian take on the
.XXX domain [theregister.co.uk] was just the last straw.
I expect that given the preceeding agreement, and the relative simplicity of changing control of the root servers that live outside the US, the UN, EU, and the rest of the world expected negotiation at the recent PrepCom3 conference [theregister.co.uk]. What they got however was arrogance and statements that made it clear the US failed to understand they didn't have the choice to ignore past agreements.
So, the timetable is clear. ICANNs contract ends between March-Sept 2006 and during that time the new body will take control. Given the likelihood that they won't charge the registrar tax (remember that automated system), just about everyone will switch and Bush will end up with egg on his face. Thus I'll bet that in the real summit in November he will have to give in an acceptable change, since he really has no control of the matter.
Re:The UN has finally lost it (Score:5, Informative)
Couple that with anycast [wikipedia.org] and other emerging redundancy methods and I'd say we have a pretty global effort to maintain DNS going on.
Again, according to wikipedia.org:
Re:The UN has finally lost it (Score:5, Funny)
Oh dear me. What, if the EU decides to establish its own independent root servers, you're going to invade? Very funny.
Re:The UN has finally lost it (Score:5, Insightful)
Re:The UN has finally lost it (Score:3, Funny)
That was easy: Al Gore of course!
Re:The UN has finally lost it (Score:5, Insightful)
The Internet is best described with organic terms, it grew out of the interconection of networks, colonising new nodes and spreading as more wanted it. The US is where it all started, not who created it. To say so surmounts to claiming that they built it as well, which is blatantly rediculous given it was and has always been since its cessation as a darpa and academic project, a commercial undertaking by telecomunications and networking companies.
The internet owes it existance to a number of things outside the US, Vint Cerf and the CERN folks as well for instance, in the very least that proves something, since "the net" by and large when disscussed is reffering to the interconected layer of html and hypertext linked pages of html that are the result of their work, without these the internet would likely have remaind a technical place, as it was before the AOL explosion and the september that never ended.
I personaly only care about this as it is jabing me in the side nagging partialy if theres a way to profit from this somehow... I know that the US isnt stupid enough to declare war over the internet, and the US isnt strong enough in any way other than militarily (they got them nukes and thats why i said that, no ones got as many as em) that they can attempt to force control over the rest of the world, this isnt some kind of US/UN cold war... this is a rediculous schism between those with the power and those who want them to relinquish it for a lower amount of control.
Re:The UN has finally lost it (Score:5, Insightful)
those with the power and those who want them to relinquish it for a lower amount of control.
What control, what power? The US government stopped "operating" the internet a while ago. The government doesn't own any of the public backbones. The government doesn't own any of the public DNS root servers. The millions of miles of fibre that blanket the US aren't owned by the government.
The maybe was some point in the past when one entity could have "owned" the internet. The internet isn't some flat homogenious collection of nodes. It's a whole bunch of castles with draw bridges between them.
Re:The UN has finally lost it (Score:5, Insightful)
I can see some sort of international consortium running the root server system if you could trust that the censor queens would not have a voice in it. The UN is not that body. The UN will never be that body.
Re:The UN has finally lost it (Score:4, Insightful)
Unfortunately, there are a lot of NOn-democracies in the UN with a voting power...that could make non-democratic friendly policy decisions....
That's a good reason not to turn it over to them...
Actually, he's right, in a way... (Score:5, Insightful)
The US funded the research which created the protocols upon which the Internet is based. The Internet first existed in the US, but it wasn't invented, it evolved.
The Internet itself is simply a bunch of individual networks which have agreed to connect together using those protocols. For that reason, any attempt to "control" it is fatally flawed. There's nothing to control. One can presume to "take control" of the DNS "root servers," but there's nothing preventing someone else from creating their own set. Who wins depends strictly upon which set the individual networks point to, and no one has control over that decision except the individual network admins.
Let the Euros piss and moan, after which if they don't like the US influence over the Internet, they can instead join Fidonet [fidonet.us]
:)
Re:Actually, he's right, in a way... (Score:5, Insightful)
Re:The UN has finally lost it (Score:5, Funny)
Maybe the Internet started as a vast secretive US government network... oh wait...
-eventhorizon
WWW != The Internet (Score:4, Informative)
It is neither; it is IP, TCP, UDP, DNS and so on. These were all invented in the US. And the specific item in question is not the internet at large, but DNS in particular.
Y'know, I expect my grandmother to fall into the fallacy of believing that the World Wide Web is the same thing as the Internet, but I expect more from a Slashdot reader. Silly me.
Re:WWW != The Internet (Score:5, Insightful)
huzzah another person that gets it (Score:5, Insightful)
Re:Vint Cerf invented the Internet , _NOT_ the U.S (Score:5, Insightful)
When was the last time you worked on a project for some Corporate entity where YOU ended up owning the work? I'll help you out with that one, never. The company owns it.
Re:The UN has finally lost it (Score:4, Funny)
Well fine. I'll go invent my own internet, with hookers! And blackjack!
Re:The UN has finally lost it (Score:5, Funny)
Your ideas intrigue me and I would like to subscribe to your newsletter.
Re:The UN has finally lost it (Score:5, Insightful)
What's with all this "we" business? Unless the poster actually had a founding hand in setting up what became the Internet, then how do they have any more right to it than anyone else? Because they happen to have been born in the same country as people who did? Accident of birth is no ethical basis for distributing non-local resources.
Do the US posters here really feel they have more in common with all other americans than they do with counterpart techies in Europe or Asia or Africa? Which community are you going to give precedence to? The US government that is comprised of tech-ignorant people with vested corporate interests (RIAA / MPAA, Pentagon, et al) and little adventurous spirit, or the IT literate and neophile tech community?
There is no reason why DNS could not be a distributed community effort. We've reached the level where such a thing could be implemented reliably. Hand it over to the techies. No-one will be happy with the means of modern information exchange under the control of one governmental organization no matter how much they tell us that "it's okay - we're the good guys."
People here spouting Fuck Em comments about the UN should ask themselves why they identify so much with their government. Why this sudden rush of Us and Them? Allowing a government to assign your loyalties to you by accident of birth seems a little old fashioned. Most posters at
Re:The UN has finally lost it (Score:4, Insightful)
"Wow. So if a foreign spy asked you to sell secrets for some cash you would be a taker? No allegiance to country, that being a silly 'old fashioned value.'"
Well it's a hypothetical, because I value my integrity very highly. But if I lived in Nazi Germany I would have few qualms aiding the allies. If I lived in Massacheusetts in 1775, then I would have no problems betraying my British government. The nation does not have the power to tell me where my loyalties lie and is not entitled to them regardless of their actions. It can earn them the same way anyone else does.
What is wrong with that?
Re:The UN has finally lost it (Score:5, Insightful)
It's interesting. That's what many countries say about the US... That we sit on our high horse and tell them what to do.
Re:The UN has finally lost it (Score:5, Funny)
Re:The UN has finally lost it (Score:5, Insightful)
Some people don't like being assholes maybe?
2. Why take their word over your own trust in your own county?
I have a better suggestion for you..
Provided that there is anything in that thing you consider to be your head, try using it.
You should listen to both and decide for yourself. Listening to one side of a story is going to make you a fool by definition.
Re:The UN has finally lost it (Score:4, Insightful)
1. Why do you care?
Because when people don't care, Bad Things happen. It is vital that individuals are involved.
2. Why take their word over your own trust in your own county?
Why would anyone trust their own country? How many times do you need to be duped before you learn one of the foundations of American citizenship, which is "a healthy distrust of government"?
I personally trust the UN more than I trust the US. Why? Because the individuals of US government have shown me again and again that they do not fight for OUR interests, but rather THEIR OWN interests -- although they claim the opposite. At least the UN is more honest.
Re:The UN has finally lost it (Score:5, Insightful)
This came about because of the UN sanctions upon Iraq following the Kuwait invasion. The sanctions were intended primarily to keep Hussein from redeveloping a military force. A secondary agenda was to plummet the economy of the country such that the people rose up against Hussein.
The secondary agenda did not work. Hussein maintained an iron grip, as all despots do. He kept what he needed for himself and gave little to the people who had no say by force of a gun to their head.
The Oil for Food program was setup as a way to alleviate the suffering of the people, as well as get Iraqi oil back into the system to help lower global prices.
Now there were two failures:
#1. A handful of people at the UN got involved in a kickback scheme in awarding the contracts.
#2. Hussein smuggled Oil, outside of the Oil for Food program.
The first failure is that of the UN, and it's being dealt with.
The second failure is the fault of the United States and the other nations who knew all along this was going on but turned a blind eye because we were hungry for that oil. Plus, the oil was smuggled through Turkey and Jordan and we didn't want to hurt their profits either.
But now we get back to the primary purpose of the UN sanctions. To keep Hussein from redeveloping a military power.
So what's more important to you? Obviously not the oil, and not the kickbacks, because we turned a blind eye. What was important was the sanctions keeping weapons out of Husseins army.
As it turns out, The UN sanctions were a success, as proven by the invasion of Iraq finding no WMDs and nothing even anything remotely resembling a defensive military force
The complaints regarding Oil for Food are politically motivated John Birch society bullshit.
Re:The UN has finally lost it (Score:5, Insightful)
1. Why do you care?
Why do I care? Simply put, we live in a global economy and as such we are heavily dependent upon our neighbors to buy and sell goods. That means we need somewhat good relations with them.
If we create purposefully hostile relations, you know what happens? They suddenly realize "hey, you know, we don't really need the US", and they go off and form their own trading partners, etc. And Frankly, we are at a time in history now that the US is more dependent upon the world than the world is upon the US. Look at our trade imbalance, and then look at what nations like China, Russia and all of Europe have been doing. They're negotiating their own deals, outside of our arena.
2. Why take their word over your own trust in your own county?
Well that's a difficult question. My country, I trust. I think our business leaders understand in the broader scheme why what I said in #1 is important, and they are putting a great effort into making this work.
Our Government? Them I don't trust. Why should I/ The President doesn't represent America, he only represents his one political party. His policy goals and actions are not determined by what is in the best interest for the nation to help it grow, but rather what is in the best interests of maintaining their political power.
Never before have I seen this in my lifetime. And you can bet, that those living outside our country see it even more vividly as has been evidenced by the US's declining popularity.
You cannot force someone to like you. You cannot force someone to love you.
Re:The UN has finally lost it (Score:5, Insightful)
Bull. This is in fact a very simple matter. The internet is now a key part of the infrastructure of many countries and no matter if you like it or not, nations don't like it when a critical part of their infrastructure is controlled by a foreign government. The US wouldn't like and accept such a situation and other nations won't either, so the interesting question is not if this situation will change, but how it will change.
If they're going to try to "force" the US, I can certainly see the US resigning. The UN has been nothing but a pain for the longest time, passing resolutions that no one but the US is supposed to carry out. Then when we do carry out UN resolutions, we're censured as being an "empire builders" or "warmongerers". Isn't it nice that so many countries can tell us what to do while they sit on their high horses? The next natural step after resigning would be to setup defensive positions in case someone wants to take it farther than that. I'm hoping that the member countries would be smart enough to leave things alone and recognize that a US resignation would be their own fault.
I know that people like you don't want to hear it, but being part of the UN is of great benefit to the US (do you really think the "war against terror" can be won by the US alone for example) so the US leaving the UN, thereby destroying the international system would be a very stupid move indeed, to put it mildly.
Btw., I'd really like to hear some examples of the US carrying out UN resolutions and then getting blamed for it. Thanks in advance.
I hope that was sarcasm? Because you may be surprised at what you find in the history of the internet's invention.
Hihi, watching people like you rave about how the US invented the internet is just to funny.
Why? First because it is pretty senseless. So what if they did? What follows from it? That only the US should be able to use the inernet? Well, have fun then, cause a global network is sure going to be useful when it's not global. And what about other inventions? How about the US not using any technology that wasn't invented in the US? Wouldn't that be fun?
Second, what about the www? It sure wasn't invented in the US, but in Europe? So what follows from this? You guys keep the internet while we take the www? How utterly silly, childish and senseless.
Re:The UN has finally lost it (Score:5, Insightful)
I'd be real interested to hear how the UN has helped with the "war on terror"? It seems to me that the "war on terror" has continued despite the UN's attempted interference at every turn.
How about UN Resolution 1441? To refresh your memory, that's the one that contains the admission by Iraq that they had Weapons of Mass Destruction, and that they would dispose of those weapons, and that they would prove that disposal to the UN.
Iraq failed to do so. Maybe they did get rid of their WMDs, but part of their responsibility was to prove to the UN that those were destroyed, and not just hidden for later use.
So it was up to the UN to enforce it. The UN went against its own resolution and refused to enforce it. So the US was the one who got to do the actual "enforcing"... And once it was complete and Saddam was out of power, the world turned on us for going AGAINST the UN (despite the fact that it was simply enforcing the UNs own resolution).
Re:The UN has finally lost it (Score:5, Insightful)
Yea but unfortunatly they must have missed the fact that "George" knew that "Herb" was a a viscious killer that had killed many people.
So are half of the club members, including George. In fact George used to pay Herb to beat people up, but now he is upset because Herb does not want to be a pawn anymore.
BECAUSE GEORGE IS NOT A PUSSY LIKE MOST OF THE MEMBERS OF THIS STUPID CLUB...
George is a coward and a bully and a liar and everyone knows it.
Heh, not likely. He stays in the club because he does not want the others to gang up on him, because he needs them as much as they need him financially, because he owes half of them a lot of money and does not want his car repossessed, because he and some other club members used to get in fights and this was the only place they could talk without much risk of a real fight breaking out, and because he is smart enough to know isolation makes you weak. He also know if he picks a fight with the biggest clique in the club they will probably kick his ass and take his stuff and because he knows Lee could go kung-fu on his ass and probably turn him into dog meat.
The smart ones know that it's not him that needs us, it's us that needs him.
Need him for what? To borrow money from them? To try to pick fights? To extort money from the littlest guys? Any one who is fool enough to think the world needs the U.S. more than the U.S. needs the world is an idiot of unbelievable proportions, and any American who believes it is just promoting the stupid, arrogant American stereotype. The U.S. has lower standards of living, worse education, and more civil rights problems than about half of the U.N. members. They bring nothing special to the table.
Re:The UN has finally lost it (Score:5, Insightful)
Of various nationalities? Yes, but these were employees of American universities that had vested interests by US tax payers.
If I were an American workign in Germany and was part of an engineering team that built some great technology I can not suddenly decide that it belongs to the American people simply because I, as an American, worked on it.
Re:The UN has finally lost it (Score:4, Funny)
The US is the largest financial contributor. (Score:5, Informative)
"The United States is the largest financial contributor to the UN, and has been every year since its creation in 1945. U.S. contributions to the UN system in 2003 were well over $3 billion. In-kind contributions include items such as food donations for the World Food Program.
The U.S.-assessed contribution to the UN regular budget in 2003 was $341 million, and to UN specialized agencies was over $400 million. The United States also contributed $686 million in assessments to the peacekeeping budget; $57 million for the support of the international war crimes tribunals for Rwanda and the former Yugoslavia; and $6 million for preparatory work relating to the Capital Master Plan to renovate the UN Headquarters in New York. Moreover, each year the United States provides a significant amount in voluntary contributions to the UN and its affiliated agencies and activities, largely for humanitarian and development programs."
Re:The UN has finally lost it (Score:3)
-everphilski-
Re:The UN has finally lost it (Score:5, Informative)
Re:The UN has finally lost it (Score:5, Informative)
"In December 2000, the Assembly agreed to revise the scale of assessments to make them better reflect current global circumstances. As part of that agreement, the regular budget ceiling was reduced from 25 to 22 percent; this is the rate at which the United States is assessed. The United States is the only member that meets that ceiling, all other members' assessment rates are lower."So make no mistake, without US backing, the UN would be nothing.
Re:Funding (Score:5, Funny)
Maybe you should just obliterate the rest of the world so that there will be no problem after that with any foreign entity. What do you think?
Re:Funding (Score:5, Insightful)
And they aren't being sarcastic.
The current brouhaha is merely the first public example of the US coming into conflict with the rest of the world as a result of recent changes in its image.
You (the USA) are currently the only global superpower.
Nobody minded this too much[1] while you were seen as trustworthy, democratic, meritocratic, the least corrupt and the most "free" (libre) society on earth.
In the last two presidential terms, your reputation has become more and more tarnished (sorry, but it's true), to the point that the benefit of the doubt has simply been withdrawn. Please note that I'm not saying whether this is right, wrong, fair or unfair... merely that it is the case.
No, I don't expect you to agree, or even to realise. You're part of the US, famously one of the most insular cultures on earth, and people are always the last to hear gossip about themselves anyway.
Since you are no longer trusted to be trustworthy, democratic, meritocratic, uncorrupt or free, you are no longer adoringly looked up to by other nations. They no longer feel safe banking on your currency, they no longer trust you as an honest broker in international politics, and they sure as hell don't want you in any kind of position of power over them.
For the entire lifetime of the net nobody's cared who ran the root servers. Now, the explosive rise of the internet's importance has met the free-falling reputation of the US, and it's hardly surprising that other countries are getting antsy about your position of "authority" over them in this area.
Short version: You were the Google of international politics, now you're more the Microsoft. Expect a lot more international anti-trust arguments in the future.
Footnotes:
[1] Well, most of the relatively powerless middle east didn't like it much, but the West, the far East and their allies didn't mind, and China (as always) just studiously ignored everyone else.
Re:Funding (Score:5, Insightful)
We've had our fingers in everyone's pies since WWII. We've gone around telling other countries what government they can and can't have. Our little tiff with the Soviet Union caused trouble for all kinds of places that weren't otherwise involved at all.
We've ignored our own constitution and persecuted people's freedom of speech (see the McCarthy trials). We've broken treaty after treaty with the American Indians. We've fueled wars and sold weapons to both sides.
We've funded revolutions, we've changed loyalties (see Vietnam and Cuba), and we've pulled every stop to build U. S. market dominance in the world. We've got a military that we can drop damn near anywhere and if not take over, at least cause a lot of strife.
I wouldn't trust us. Hell, I don't, and I used to be in the U. S. military.
Granted though, in my opinion, you asked for it. We had a policy of letting Europeans kill each other all they wanted without our involvement until Germany dragged us into WWI by trying to get Mexico to attack us. Then, when we decided to go back to our policy of leaving everyone else alone, Germany and Japan dragged us back into it with WWII. It's always one asshole that ruins it for everyone. Saddam dragged us into the gulf war by attacking one of our allies, and good ol' bin Laden, in an attempt to get us out of the middle east, started the current chain of events that led to our invading Afghanistan (personally, I think Iraq was just finishing daddy's work for ol' dubya, but that's just me).
We're the big kid on the block, and if you're tired of our bullying, you're going to have to fight back. And I'm not talking with words, mind you. The American people don't care, by and large, and our politicians have no reason to put an end to it. Until then, you're just going to have to wait until either an economic crisis cripples us, or civil war breaks out. I don't see either happening any time soon.
Re:The UN has finally lost it (Score:5, Insightful)
Incorrect. My argument is:
1. That the private company is already an international entity that serves international interests.
2. That said company has done an excellent job to date, and has shown no need for a government run entity.
3. That it is not the US policy to force private companies to give up ownership.
4. That the UN has no compelling argument for wanting control other than the fact that it wants it.
5. That the UN has a far poorer track record on joint ventures than ICANN has.
That is the argument, and I daresay that it's pretty ironclad. The moment someone can poke a reasonable hole in that logic, I will change my position. So far, no one has done more than insult me for my "american elitist position". Boo hoo. Find an argument that works, then we'll talk.
Re:The UN has finally lost it (Score:5, Insightful)
ICANN right now arguably is illegal. They unconstitutionally removed the "At Large" members of their board, and the decisions they've made since then really have had little or no mandate. Meanwhile they sat on proposals to expand the range of DNS domains for years, announcing new TLDs without doing anything about it, and they continue to allow Verisign to run
.COM despite well documented abuses of their position.
Your description of the UN situation is ludicrous too. The ITU, for example, has a stellar record of fair, reasonable, standardization of telecommunication standards. And right now, the position of non-US companies is that they want such a body in charge of the type of thing ICANN is, because ICANN is both a US-body and a body that's proven repeatedly it cannot be trusted. ICANN isn't even answerable to US law, it's proven that by the At Large fiasco. How is it reasonable to put any trust in it? And why are so many so dead set against independent, accountable, bodies being put in charge of some of the most important consensus-driven decision making activities currently decided by unaccountable, anti-democratic, elitist, dysfunctional, body, answerable only slightly to one of the governments whose citizens access the net, with a track record of fucking things up?
Re:The UN has finally lost it (Score:5, Interesting)
Please name how the ICANN has failed to perform its duties. I can name how it *has* performed its duties:
1. It has successfully kept the root servers highly available to all countries.
2. It has spent significant time with foreign interests looking to meet the needs of these people.
3. It has shown forethought in decisions, not jumping on new concepts that could be harmful in the long term.
4. Yet it has managed to approve a variety of top level domains (including the new
Doing an excellent job to date is debatable and, regardless, offers no guarantee that it will continue to do so as political situations change.
Show me a guarantee that the UN will do as good or better job. If you cannot, then why place more trust in an entity that has no track record on management of these servers over an entity that DOES have a track record?
[Forcing private companies] is not really relevant. This is an international issue as the Internet is an international resources with countless billions invested by numerous nations all of which rely upon the system to function properly.
No, it is relevant. US laws protect against illegal seizure, and seizure without compensation. Show a REAL ARGUMENT as to why ICANN's holdings should be seized, THEN the US government can consider seizure and compensation.
You've mischaracterized even that basic argument entirely: the UN, or rather, the international community, wants to move control from ICANN to a truly international organization that can operate transparently and that is required to acknowledge and assimilate the input from those governments represented in the UN. Again, the alternative is just to trust ICANN to play fair.
Considering the lack of evidence that ICANN is not "playing fair", I fail to see how this argument is any stronger. I'll say it again, find a reasonable argument and I'll switch positions. Simply, "we don't trust an entity that has shown overall good judgement and has worked well for the past decade" is not a reasonable argument.
[UN has a far poorer track record] is true, but is not sufficient to override the objections to your prior points.
It is however, sufficient to point out the problem with simply turning over control to the UN. No one has yet shown what is wrong with ICANN control. No strong arguments exist. In absense of such arguments, the relative histories of the two entities must be compared. ICANN has done a satisfactory job at its task and has shown no signs that it has been doing any poorer in recent history. If anything, the ICANN has been slowly improving. You have agreed, OTOH, that the UN has had a poor track record in other joint ventures. Why change something that obviously works the way it is?
Re:The UN has finally lost it (Score:4, Insightful)
Your post implies that Saddam was armed, and armed with WMDs, as those were the primary target of UN resolutions.
That is false. Iraq had no WMDs, nor any plans to build them, nor any facilities capable of building them.
So it would appear that all those weakly worded resolutions might have had an affect after all, although in many respects the whole sanctions regime, oil-for-food, etc., was a disaster.
Re:The US is Losing the World (Score:4, Insightful)
If you don't like it, then set up your own DNS. If you think DNS needs to be more decentrilized (which is kind of stupid to do), then write a set of protocols to do so. If people like it, they will use it. Just like how DNS started to be used.
Why in the hell do we need the UN trying to forcibly take control of anything? We have independant countries for very good reasons. The UN is not a lawmaking body, and the EU isn't supposed to be either. How does this have any basis in the foundings of these organizations?
No, this whole set of shenanigans perpetrated by the UN and the several countries is ridiculous, and just about the worst possible way of doing it.
This again? Where's the problem? (Score:3, Insightful)
It will be officially raised at a UN summit of world leaders next month and, faced with international consensus, there is little the US government can do but acquiesce.
Is that a fact? Right or wrong have you looked at our Government lately? Do you really think that international consensus will bother us in the least?
I'm sure my friends in Europe will take exception to this line of reasoning but why shouldn't the US retain control over the root servers? We built the Internet in the first place. Do you really want to see it turned over to the UN?
In the early days, an enlightened Department of Commerce (DoC) pushed and funded expansion of the internet.
Not only did we invent and build it -- we paid for it. That doesn't entitle us to something? The British got to define the Prime Meridian based on their global empire. Subsequently this has defined GMT. Wouldn't it make more sense for GMT to be based on New York (the center of the World Financial System and headquarters of the United Nations)? Isn't that whole argument just as silly as insisting that DoC hand over the root servers? Where is the problem here that they want to fix?
Re:This again? Where's the problem? (Score:5, Insightful)
Re:This again? Where's the problem? (Score:5, Insightful)
NEWSFLASH:
Growth rate of US economy: not much. A few percent possibly.
Growth rate of China's economy: huge. About 11% IIRC.
Which means China is on course to become the largest economy in the world in about 30 years' time. (Figures all OTOH, but there or thereabouts.)
The US and Europe may be far and away the biggest economic blocs in the world at the moment, but we're going to have to get used to sharing economic might sooner than some people realize. And I doubt China (and India) will have the same ideas about where the centres of world power should be that we do.
Re:This again? Where's the problem? (Score:4, Insightful)
Growth rate of China's economy: huge. About 11% IIRC.
Which means China is on course to become the largest economy in the world in about 30 years' time. (Figures all OTOH, but there or thereabouts.)
Err. No. If you see a linear trend line, it is generally foolish to extrapolate out that trend line 30 years. China has and will continue to see a lot of growth. Thinking that they are going to maintain 11% growth for the next 30 years on the other hand is close to insane.
People don't realize this, but business in China has a LOT of problems. The most obvious problems are the extremely high level of corruption and constant government meddling. China has a lot of people just starting to get out of third world style poverty and very cheap labor, but it isn't the business utopia people seem to think it is.
One of the other little talked about problems with China is their gross inefficiency. When the oil crunch comes, China and the developing world are going to be the ones to be hit the hardest. Granted, the first world will feel the burn too, especially in the indirect cost of having the developing world's economies getting a good shaking, but the pain in places like China will be much greater. The amount of oil it takes to grow the GDP in china 1% is significantly higher then that of US, and higher still then places like Europe and Japan.
I am not saying China can't become a super power, but it has some very serious hurdles to overcome first. China is still a mess politically, they are extremely bureaucratic and corrupt, their market is riding essentially only on the fact that they have cheap labor and a billion potential consumers, and their levels of oil consumption per percent of growth of the GDP makes the US look down right green. China has its share of problems. Boiling down China's rise as a super power to seeing a 11% growth rate is a naïvely simplistic way of examining the issue.
Re:This again? Where's the problem? (Score:5, Insightful)
What, like Cuba? They may be suffering, but last I check there were still there, doing business, living their lives free of US control. Sometimes freedom is more important than money..
I have a whole lot of problems with them and since it was my tax dollars and not the EU's that paid for the Internet in the first place (from the R&D to the initial deployments) I'll be damned if my Government turns it over to the World.
Then be damned, because you will lose control one way or another. You did NOT pay for the cables in countries outside the US. You did not pay for the routers, the power usage, the servers that are outside the US. You payed for a small part of the internet that connects your military servers and some academic institutions. Last I checked, no one was demanding that you give the World control over these segments.
Re:This again? Where's the problem? (Score:3, Insightful)
"We" (Americans) didn't invent it. It was a much more impressive collaboration from people from many countries, not the least of whom is Tim Berners-Lee [wikipedia.org] [Wikipedia.org]. I'll agree that we funded it, and greatly helped it come to fruition but let's not make it look like "We" think it was the singular efforts of one country and one people that birthed the Internet as we now know it. To do so not only makes "Us" look quite egocentric. I don't believe
Re:This again? Where's the problem? (Score:5, Informative)
Re:This again? Where's the problem? (Score:5, Insightful)
Your comment, "how technically it is very difficult for one country to "control the internet."" You think that's hard, wait until you see a committee of twenty countries trying to do it.
And I just can't wait until the UN/EU tries to impose a "Root Fee" to pay for managing it, that every man, woman, and child with an Internet conneection will have to pay. If you don't think the UN is thinking about this, then you don't understand the most fundamental rule of politics -- "It's all about the money."
Re:This again? Where's the problem? (Score:5, Insightful)
No. Because then the date line (meridian opposite of the prime meridian) would pass through heavily inhabited zones (Asia) rather than through the Pacific, which would be kind of disruptive.
Re:This again? Where's the problem? (Score:5, Insightful)
Either way, this is irrelevent. The point is that, today, the Internet is a global network. It needs to be "governed" globally, not by one major player. I'm finding the nationalistic cries of outrage posted here difficult to stomach. Something tells me that if it were proposed that control of the World Wide Web be handed over to the EU, on the grounds it's a European invention, you'd be pretty pissed.
Re:This again? Where's the problem? (Score:4, Informative)
He never dreamed that the "Web" would become anything like it has become. The idea that he was standing over people's shoulders and forging the Web from red-hot steel with his bare hands is totally misleading. Yes, he put up the first web site (info.cern.ch) on August 6, 1991. Big deal. Who created the sockets library he was using? Who created the RFC system that let him publish his RFC? What country invented the programming language he wrote it in? Heck, what country built the machine he wrote it on? And what country produced the Apple HyperDeck that inspired him to use internal hyperlinks? When he wrote HTTP, there were new protocols hitting the Net almost every day. His just happened to be the one to catch on because it was mind-numbingly simple.
If this is your "reasoning" that the EU should own the Internet, then I imagine that you'd want to enslave everyone in the World, after all Francis Crick was from England, and he discovered DNA. Let us all hail our new EU overlords.
Re:This again? Where's the problem? (Score:4, Insightful)
Re:This again? Where's the problem? (Score:5, Insightful)
We invented the type of government where the people are represented by representatives in a legislative body, separate from an executive branch, commonly known as the Republic. Your use of the aforementioned type of government infringes on our Intellectual Property rights. Please cease to use the aforementioned type of government within 30 days.
Best regards,
The Old World The internet is, by definition, the sum of its constituing networks. The constituing networks are build and paid by their respective owners. Basic property rights. You don't own anything you can't show the receipt for.
In the case of the domain name system, that is payed for by the owners of domain names. Year after year they pay for it through their registrars. Other then whining on
You want more examples? Graham Bell invented the phone. Does that mean the US has the final say in deciding whether Moldavia gets country prefix 0418 or 0418? No, that is decided by the ITU, which is a special organization of the UN. (Which are known to be anti-American communists, having done such terrible things as providing North America with the obscenely long country code "1" just to make it harder for the rest of the world to call the US.)
Re:This again? Where's the problem? (Score:5, Insightful)
i suggested this in the previous discussion (Score:5, Insightful)
Re:i suggested this in the previous discussion (Score:5, Insightful)
WHAT WILL THEY GRANDSTAND OVER!!??!!
I mean, who ever got elected for making sensible arguments. You get elected for mandating hearings on steroid use among professional athletes or intefering in state matters like the right of a husband to let his wife die a natural death. Yes, I realize these are particular instances of American issues, but it is the same in all democracies. All the politicians have to make a large hue and cry over insubstantial or trivial issues in order to remove attention from the fact that they're basically doing nothing or are powerless to do anything about real issues that they were elected/appointed to do.
I'm with one of the earlier posters. Tell 'em all to fuck off. They can create their own root servers any time they want. For redundancy reasons, it is something they should do anyway.
Re:i suggested this in the previous discussion (Score:5, Insightful)
News to me. Where are those rights enumerated and by which body were they passed?
Re:i suggested this in the previous discussion (Score:5, Insightful)
Re:i suggested this in the previous discussion (Score:4, Insightful)
And the specs for those protocols are all written in American English.
Screw You EU ... (Score:3, Funny)
non-governmental control? (Score:5, Insightful)
Re:non-governmental control? (Score:5, Insightful)
I honestly don't believe that any government has the right to control it. What needs to happen is for private citizens to take it back.
Lets remove DNS (Score:5, Interesting)
So... (Score:4, Insightful)
-theGreater.
PS: Yes, I realize only the -summit- was in Tunisia; I needed a smaller country to make my point.
View in a larger context (Score:5, Insightful)
It's really not that hard to imagine, for instance, that our government might force the root name servers to stop handing out answers for the
That all probably seems like hyperbole. It does to me, too. But if you're the leader of a foreign country, it would seem a lot less so. And if you're responsible for your nation's economy and the internet plays a significant role in that, I'd say you've got a responsibility to mitigate such risks. While I think the root DNS is safe with us, it doesn't surprise or anger me that the rest of the world doesn't agree. If anything, it surprises me that it hasn't happened sooner.
C.O.N.T.R.O.L. vs. C.H.A.O.S., RIP Maxwel (Score:5, Interesting)
Which is, of course, exactly why the US wants to maintain control of it.
EU. EU. You management style is PU (Score:4, Funny)
Please god not the UN (Score:3, Insightful)
Hilarious! (Score:5, Funny)
The internet will never be the same again.
You've already lost the battle against melodrama.
Who should have control? (Score:5, Insightful)
But if we mean the millions of small and large (e.g. China) internets, each of these can and probably should be owned.
The problem of root DNS servers appears to be an artificial one, relatively easily solved if there was the political will to relinquish control and allow the free creation of arbitrary top level names. There are parallels where control has successfully been relinquished and the results are a nice mix of anarchy and order, suiting everyone. Newsnet is a good example.
Let the internet be divided! (Score:4, Interesting)
The UN, dictatorships and the Internet... (Score:5, Insightful)
Correct me if I'm wrong, but won't dictatorships that terrorize their people have the same ability to vote in important matters as democratic countries? Hasn't there been a history of less than decent governments being represented in, say the Security Council? I mean, what is China doing there?
Regarding the Internet, I'm leaning towards saying "if it ain't broken, don't fix it". It's working OK the way it does today (although Verisign needs to get the boot). I also want to make sure that China and other such governments have no say over my Internet connection.
And the EU sure seems to be taking the hardball approach to this! I can't even see how they can possible force the control away from the US. They will be making complete fools of themselves if they end up splitting the Internet. Unlikely, but I'm sure they are willing to do so just to prove that the EU has the balls to stand up to the US...
Re:The UN, dictatorships and the Internet... (Score:5, Insightful)
Devils Advocate (Score:4, Interesting)
I am anti-US on many things, but let back them by saying this.
The USA created the Internet as we know it today, it is their creation, from their tax payers money. As much as I dislike many things that the USA is doing and has done in the past. I'm going to have to say that I'm behind them on keeping control of what is theirs, which happens to be the foundation of the Internet as we know it.
Just due to the fact that it is now a globally used system that effects everyone in the modern world does not give any body/group the right to demand rights of control over that system. Just as new protocols are created over time and are layered ontop of the old to keep the system running regardless of 'obsolete' hardware/software that might be in some remote corner of the web, so to should the U.N create a system that runs along side the current one if it so desperatly wants control. That is the most logical solution to the problem at hand. Countries and corporations can create 'internal' networks that overide the current systems of the Internet.
The fact that the developing world does not see that as the most logical first step attempt at a solution at hand is evidence that they are not ready to have control over a system such as complex as the Internet.
I whole heartly back the US on their choice to not hand it over.
No one will notice (Score:5, Informative)
But you know what? To the extent that the data coming out of the latest alt-roots conflict with the ICANN, they will be generally perceived as broken, particularly but not exclusively from the point of view of users in the US. For example, domain names will fail to resolve, or will resolve to the "wrong" place. If the new alt-roots do much of anything differently, users will start pointing their DNS clients at nameservers that resolve up to the ICANN. So for example if China sets up something that won't resolve (say) freechina.net, the individual users will soon learn to point their DNS clients at US nameservers.
The only way I can see these new alt-roots being heavily subscribed is if they make sure they agree with the ICANN everywhere ICANN has a route to a name, and if their use is legally mandated so that ISPs are forced to go through the hassle of changing. If they do that, the only value that they could possibly add would be of including extra domains that resolve for the alt-roots, and that ICANN does not yet have. Is there really a lot of demand for such a thing? I'm not sure.
Re:No one will notice (Score:5, Insightful)
This doesn't spell the end to ICANN at all. All it does is reinforce the idea that the EU thinks they control the economic members and doesn't really respect member countries, and that the UN is powerless. People bitch and moan that the US tries to take things from other countries, well here is the exact same thing.
What the Internet is... (Score:5, Insightful)
But hey, it'll be fun to watch....
The telling views.. (Score:4, Insightful)
All modded up as insightful and informative.
Well.. That's the reason the UN really wants things to be run by an international board, not a US controlled one. The net, as the article states, is now vital to many countries.
Which means the rest of the world would also like to have it's fair share of the say, without having to listen to the US, which has recently showed it's absolute contempt for international view (and in the posts here, is showing it all over again).
The aim, from my interpretation of the article, is that an international body, that fills the shoes that ICANN now fills will be formed as a technical arena to ensure that the needs of the world are fulfilled.
The rest of the world is perfectly able to build it's own root servers, although this will then lead to the US being cut off if it refuses to use the new ones, and fragmentation of the whole will occur.
This is what the ongoing argument is about.
Not 'Give us the root servers. All of them. Give us what you paid for.'.
The infrastructure outside the US was paid for outside the US, by the companies that operate outside the US.
Without that foreign buy in to a Standard, there would be no worldwide internet. It would be the US military net it started off as, or perhaps their academic net, like UK had JANET, and Europe's other competing national networks.
What is being requested is that the ownership becomes joint. No one country can pull the plug and get overall control to suddenly yank a whole area out of the system at will.
The amount of inventions used in the US created outside of it (or before it existed) are many and multifarious.
Without those, it's entirely probably that the ideas that lead to the creation of the Internet would have not formed for a goodly long time.
But, the ideas did come around in the US, and honestly, all credit to the guys that did come up with it. And for the forsight to put it into the academic arena, which led to it's increase in scope worldwide (I still remember the net from it's almost entirely academic days).
Now the choice comes to either make it a truly worldwide and international entity and show real enlightenment, or to hoard it, use it as a lever to gain other concessions, or a stick to beat people with if needed.
This whole issue is a lot more complex than most here give it credit for.
Personally, I'm interested in seeing how it evolves.
I think a lot of the character of both the UN and the US will come out here, and I very much doubt that either one will end up smelling of roses.
They want it, let them have it (Score:5, Insightful)
Now they want to force the issue, I think we should help them along. Tell the EU and the UN to pick a date on which the US root zone file will no longer be responsible for containing the look-up information for non US country domains such as
Now if they actually did this, the US part of the internet would not be order the control of an organization that is not beholden in the slightest way to the American people, while the rest of the world gets to deal with something administered by the UN or the EU. Really, what is so hard about this?
Oh, as for the internet being essential to the infrastructure of some countries, might it be said that the internet pretty much IS the infrastructure of the US economy, government and whotnot? Turn off the internet everywhere, and the transistion in the US would be substantially more severe than the transistion in Brazil (I am sure they would still get their taxes somehow).
To paraphrase Andrew Jackson: (Score:4, Insightful)
I can imagine it went something like this: (Score:5, Funny)
In A.D. 2005, war was beginning.
BUSH : What happen ?
ICANN : Somebody set up us the root
AMBASSADOR : We get signal
BUSH : What !!
BUSH : Main screen turn on
BUSH : Its you !!
E.U. : How are you gentlemen !!
E.U. : All your domain are belong to us
E.U. : You are on the way to destruction
BUSH : What you say !!
E.U. : You have no chance to survive make your time
E.U. : Ha ha ha ha
....
AMBASSADOR : President !!
BUSH : Take off every 'Zig'
BUSH : You know what you doing
BUSH : Move 'Zig'
BUSH : For great justice
RUMSFELD : THEY'RE CALLED F-16'S, DUMBASS
Re:If the EU hasn't noticed (Score:5, Insightful)
More to the point, the US doesn't have any control over the Internet it could hand over to the UN even if it wanted to. The article talks about the DNS system - or so I presume anyway, since it mentions root servers; it doesn't actually state anything about DNS. The US currently hosts the root DNS servers. Those root servers are special only in that everyone keeps using them; they have any authority only because everyone agrees that they do. There is nothing whatsoever stopping the UN from making its own root servers and telling everyone to use them; they will be ignored, but that's not US's fault. Such things has been tried in the past ("use our special DNS servers, and you can type keywords into your browsers address bar", and they died off from simple lack of interest.
I don't see how US could hand over something, which, in the end, is authority by being voluntarily recognized as the authoritative data source by everyone. Even if the US would take the root servers offline, there is no reason why everyone would start using UN's brave new root servers. More likely we would get a period of total chaos as several conflicting DNS namespaces would be in competition against each other.
This entire proposition is nonsensical and should be silently ignored.
Re:what a crock of shit (Score:5, Insightful)
If there's not, then I propose one.
Melanie's law states:
That when ever Americans get in an argument with Europeans they will bring up WW2 and claim to have saved the Europeans arses.
Anyone who uses such an argument in a thread is invoking Melanie's law and like Gibson's law, loses the argument by defaulting.
P.S. The Brits prevented the invasion of the UK by themselves before the US was in the fight and the Russians saved our collective arses by bogging down the German army so much that it gave the Allies a chance to fight back.
Re:Slashdotters should be ashamed of themselves (Score:5, Insightful)
Um. No. Not even close. Not even all of the root DNS servers managed by US companies and organisations are located in the US due to the fairly recent attempts to DDoS the root servers. There might only be one IP listed for [A-M].ROOT-SERVERS.NET, but each of those IPs has multiple physical hosts behind it that are distributed across the globe. At the present time, less than half of the actual boxes performing the root DNS service are located within the USA, so I think we can realistically expect one hell of a lot of political posturing over the next several months. Given the importance of the Internet to governments and Big Business, this could well turn out to be a bigger political issue than Kyoto. | http://tech.slashdot.org/story/05/10/06/1241227/eu-un-to-wrestle-internet-control-from-us?sdsrc=nextbtmprev | CC-MAIN-2016-07 | refinedweb | 11,626 | 71.24 |
SCO Announces Final Termination of IBM's Licence 807
ickle_matt writes "SCO have announced the final termination of IBM's UNIX license, despite Novell telling them they can't. Interestingly enough there's a new set of "stolen code" figures in the release - .' "
Interesting... (Score:5, Interesting)
Also, aren't the NUMA and RCU multi-processor patents owned by IBM? SCO might own some of the code, but since they are licensing IBM's patents IBM could sue them for infringing on their patents. Is this part of the current IBM v SCO lawsuit?
Re:Interesting... (Score:5, Interesting)
Maybe. As far as I understand the stories, IBM has written NUMA and RCU code for their System V based Unix (AIX)
IBM's System V license seems to state that when they add code to their SysV (==AIX) that code has to be treated as the rest of the SCO owned SysV code. So IBM wrote some code, included it in SysV/AIX, and now they can't include the exact same code in Linux, because of their SysV contracts with SCO...
Thats what SCO Says but....... (Score:5, Interesting)
IBM has owned those patents since '92 when they bough sequent, sequent had those patents since the late 80's so either way SCO SOL.
Re:Thats what SCO Says but....... (Score:5, Informative)
According the press release .'
So IBM's patents aren't transferred or licensed to SCO, but if they write code for a System V derivative work (such as AIX) they can't use the code in Linux. The contract basically says 'All your AIX code are belong to SCO'
Re:Thats what SCO Says but....... (Score:5, Informative)
This letter specifically gave back to IBM the rights of any code they created to enhance or extend the AIX/SYS5R4 OS.
This straight away rules out such claims unless SCaldera believe they can convince a Judge and Jury that the superceeding agreement is invalid in someway.
Something I rather doubt
:)
Re:Thats what SCO Says but....... (Score:5, Insightful)
Re:Thats what SCO Says but....... (Score:5, Interesting)
It might turn out that the code in question was really only supportave code, libraries and header information taken from a common ancestor, BSD or earlier unixies
SCO might be trying to make the point that by taking some code from BSD/AIX and merging with other code then releasing it to Linux, IBM in fact released all the code to linux.
I point to other posts, made throughout all this time, that AIX's supportave architecture and framework is fastly different then Linux, and a direct copy of code would not work.
Re:Thats what SCO Says but....... (Score:5, Informative)
Infact SCO admit they down own the copyrights to RCU, NUMA or JFS as per this story:
Cutting through the noise SCO are claiming that IBM can not add technology added to AIX to Linux it's more to do with contracts than copyrights.
Re:Thats what SCO Says but....... (Score:5, Insightful)
Just a point of clarification, AIX is actually SVR3-based, not SVR4. And there's been a LOT done do it since AT&T handed the code over, as anyone who's programmed for or adminned AIX can tell you.
Like it or loathe it, you know it is 'different' from both SVR4 and BSD.
AIX vs. Dynix/ptx (Score:5, Interesting)
Yes, it did. However, if they don't have such an agreement over Dynix/ptx, then IBM may very well be screwed. If what SCO says is true (even though what they said about their right to terminate AIX wasn't), then IBM may be in a world of hurt. If Dynix/ptx code must be treated as a derivative of System V, then there may be actual trouble here. Remember, AIX and Dynix/ptx are completely separate products with completely separate licensing schemes. SCO may have actually found a legal leg to stand on. Unless IBM can produce similar documentation about Sequent's code, it may belong to SCO.
(By the way, how does SCO have Dynix/ptx source code to compare against the Linux kernel?)
Re:Thats what SCO Says but....... (Score:4, Interesting)
Re:Thats what SCO Says but....... (Score:5, Informative)
The GPL doesn't take away any rights _you_ have to _your_ code, including adding it to other products under other licences. What it says is that if you combine your code with other GPL code you have to release the result under the GPL.
SCO seem to be claiming that if you add your code to their unix code, it isn't just the resulting unix variant that is a derivative work, but your code (in isolation) is also.
If SCO are correct, if you took code from another of your products and added it to Unix you would lose the right to ship that other product. That wouldn't happen if you added that code to a GPL product.
Re:Thats what SCO Says but....... (Score:5, Interesting)
(I'm an ex-IBMer who transfered to Beaverton right after the sale, and it's absolutely terrible to see what IBM did to the Sequent culture.)
Re:Thats what SCO Says but....... (Score:5, Insightful)
There are many reasons for the failure of the business, but none of them had to do with the people working there.
Re:Thats what SCO Says but....... (Score:5, Informative)
IBM != Sequent (for year values less than 1992)
IBM had a contract/license variation with AT&T. Sequent did not. Anything IBM developed, IBM owned. Anything Sequent developed (before being bought and becoming part of IBM), based on the original AT&T license, belongs to the owner of SYS V, so the (rights to the) developements did not belong to Sequent and could not be sold to IBM in '92, so IBM does not own them, never did own them, and can not give them away - they belonged to Novell, and now to SCO.
Could this possibly be a (perhaps THE) legal leg for SCO's lawsuit?
This reply completely does not address your admittedly very good point about the patents, as I don't know how the license issue would afftect the patent issue. I.e., can I patent an idea that legally belongs to someone else, even thought it was my idea and I submitted it myself? I would guess 'yes', but it would depend greatly on the exact wording of any contracts/licenses - and we are right back to the license issue. Also, would you be able to charge me license fees on the idea you own, but I patent? Could I charge you for using my patent if you legally own the idea?
My head is starting to hurt...
Re:Interesting... (Score:5, Interesting)
However, IBM (and Sequent before them) has made very sure that they wrote up a general outline of how the process works, and then made an implementation on AIX (and Dynix/ptx). They then made a very similar implementation on Linux. As long as they can show that both implementations came from the general outline, there should be no problem.
Heck, they should be able to argue that they can copy their stuff from AIX to Unix as long as there is a general outline. They may be able to argue that as long as they wrote it, and nothing of Unix comes out to the public, that they're in the clear.
Re:Interesting... (Score:5, Insightful)
That was a few days ago. Today SCO are claiming the same thing but in relation to Sequent (now owned by IBM). Basically claiming that any code Sequent added to their Unix has to be treated as if it is part of the original Sys V code base.
The story is confusing in mentioning Novell. It seems Novell are a party to the original IBM deal, and can prevent termination of IBM's AIX license. I'm not sure it follows that Novell have the same position in relation to the Sequent / SCO deal. I guess we'll have to wait for IBM to respond.
Re:Interesting... (Score:5, Interesting)
HOWEVER, the contract between Sequent and AT&T has NOT been made public by SCO nor IBM and so it is not clear to third parties whether or not the Sequent-AT&T agreements give Sequent the same rights as were given to IBM, though one may speculate based on the format of the IBM-AT&T agreements (see my article for full details).
Fundamentally, this is a contract law case in which the status of the Sequent-AT&T and IBM-AT&T agreements are defined. In other words, when IBM bought Sequent, what happened to the Sequent-AT&T agreement? Were it made null and all dealings between Sequent and AT&T now under the stipulations of the IBM-AT&T agreement? Or is it the case that code developed by Sequent is still bound by the original Sequent-AT&T contract?
Someone more familiar with contract law will have to respond; however, I believe that if in fact ANY code developed by Sequent BEFORE it was bought by IBM AND that code was placed in a SysV derivative (in this case probably Dynix/ptx) AND that code was placed in the Linux kernel, then it may very well be the case that SCO is standing of firm legal ground on that issue.
There are, of course, other details to this situation which may invalidate SCO's claims to right of the code, such as the GPL, and unclean hands doctrine (both arguments which IBM has included in its rebuttal) but I suppose we'll have to wait and see what happens. Also, read my article.
Re:Interesting... (Score:5, Funny)
It just goes to show that whether it's object-oriented programming or contract law, multiple inheritance is likely to be hard to understand.
AT&T - Sequent contracts available here (Score:4, Informative)
Exhibit G [sco.com]
I agree with the meat of your analysis about Sequent. I don't know enough contract law to comment on SCO's thesis about Sequent.
Re:Interesting... (Score:4, Funny)
Re:Interesting... (Score:5, Insightful)
It was my understanding they were not suing for use of those products though they probably should. What I find interesting is SCO terminates the license violating their agreement with Novell. I wonder if they can be sued by Novell for violating the contract. Exactly what SCO 'claims' IBM did.
SCO claims IBM can't be trusted because they violated a contract and now SCO goes out of their way to violate another contract. Sounds like an internal problem with the company. I strongly suggest they see a shrink. These guys can't see straight anymore.
injunction (Score:5, Interesting)
Good point. I don't know why IBM hasn't filed for a temporary injunction against the license termination. It would accomplish two things. 1) it would put AIX users a bit at ease (even if IBM has indemnified them), and 2) would get this thing in a courtroom quicker which is *obviously* the last thing SCO wants. I believe when they start getting legal defeats the stock will tank.
Maybe IBM and SCO are colluding (Score:5, Interesting)
IBM and SCO make it known that IBM is thinking of buying SCO. Instead, SCO sues IBM. SCO's stock price goes up. SCO's owners dump stock (getting rich) and SCO uses the inflated stock price to buy up small companies. Once SCO has all the pieces in place, IBM suddenly forces things into court and SCO is blown away. SCO stock plummets. *THEN* IBM buys them for a basement bargin price.
This does multiple things for IBM. (1) Publicity. (2) Good PR with the Linux crowd as IBM "saves the day". (3) They get more stuff in the SCO buyout. (4) It places IBM's competitors in the Linux arena on shaking ground while all this is happeneing, possibly forcing some out of business.
Suddenly, in the end, IBM has a Linux distro, AIX for the high-end, lots of other IP, and a rep as being the big champion for Linux that is willing to put its money where its mouth is.
Right about that time, IBM would be ready to take on Microsoft again for the servers and desktops. IBM gives away the desktop OS just to have an in and starts recapturing the mid-level servers. As IBM becomes the "leader" of Linux, why would you not go with IBM and AIX on the big iron since IBM makes it one smooth continuum of *nix?
Man, I have got to stop drinking 10 diet cherry cokes while on medicine for a head cold before I post. =)
Damn, *that's* interesting (Score:5, Insightful)
I tell ya, it's definitely wacko, but it's not completely retarded, I have to say that. The one key is that when SCO does all this buying up of small companies, it would have to be done with SCO *stock* - I'm sure that's what you intended - which would actually be plausible in their situation, since they're a stock-rich/cash-poor company.
There are two problems I see with the theory. First, I don't see SCO taking over any small companies right now.
;) Second, the time frames are a little off. SCO would need time to perform all these takeovers, as those never proceed quickly. Second, IBM can't afford the lawsuit spectre to last too long, as there's the threat that companies will get scared of linux and such, fleeing into the arms of Sun or MS. That would make the whole scheme counterproductive.
So I don't think that's what's going on here. That said, it *is* a pretty nice scheme, and I wouldn't be surprised to see it pop up elsewhere, assuming it hasn't already. I think it would be outrageously illegal, but might not be impossible to pull off. The only real problem I see from a practical standpoint is trust - when the lawsuits start, puffing up the value of the smaller company to be taken over, they gain an advantage that could be acted upon if they decide to make the fake lawsuit real.
They'd almost have to give the larger company some faked "smoking gun" evidence that gave them a clear "out" of the lawsuit, if filed. In this situation, it would be like some SCO developer last year sending a memo saying something like, "Hey, have fun with the JFS code I posted to the kernel dev team yesterday. Free of charge compliments of Caldera."
But I will say, it's not impossible.
Man, I have got to stop drinking 10 diet cherry cokes while on medicine for a head cold before I post. =)
I think that would be a good policy for sure.
Re:Interesting... (Score:5, Informative)
There is an interesting article "Novell letters throw new light on SCO-IBM case" published in The Age [theage.com.au] that discuss letters sent to SCO by Novell asserting that Novell has "the right to compel SCO to waive or revoke any of its (SCO's) rights under the contract [involving SCO, IBM, and Novell]." In the letters Novell basically tells SCO that SCO cannot terminate IBM's license. These letters were apparently used as exhibits in IBM's countersuit of SCO.
Re:Interesting... (Score:5, Insightful)
Now as I understand it (Score:5, Interesting)
I suppose you can sign a contract stipulating just about anything - and since we havn't seen the Sequent contract yet (if ever) there could be something idiotic like that in there.
Re:Interesting... (Score:5, Interesting)
Thanks for that explanation.
Now what I am wondering is, even if it was not legal for Sequent/IBM to add the code to Linux, how can SCO sell a license to use that code with Linux if they don't even own it?
Novel (Score:5, Interesting)
They have already indicated that Novell has the right to tell SCO that they can not do this action. It now becomes breach of contract unless there was some item in the contract about this.
NUMA and RCU? Then why... (Score:5, Insightful)
It's part of the kernel that you can't even use if you wanted on a single-CPU box!
So what's the fee for, again?
Regards,
--
*Art
The real game... (Score:5, Insightful)
SCO's Shell Game [computerworld.com]
Some quotes:
None of the threats make legal sense. If they did, SCO would be able to get an injunction to shut down Linux users. In practice, SCO hasn't even been able to get an injunction against IBM and won't get a court hearing on its request to do that until 2005.
Meanwhile, a German court told SCO in June that it must stop threatening Linux users. And an Australian government agency is looking into charges that SCO is essentially running a shakedown racket by claiming that Linux users must buy a license they don't actually need.
And SCO's tactics don't make business sense, either..
And apparently it worked. Which means we can expect that as long as Canopy can find ways of cashing in on SCO's threats against Linux users, those threats will keep coming -- no matter how little sense they make.
IBM's solution (Score:5, Insightful)
That's not true. IBM's solution is simple. Since there is no breach, the offer to cure is contained in the countersuit.
Tomorrow SCO's quarterly report comes out, sell your stock before the insiders [yahoo.com] can.
Re:IBM's solution (Score:5, Interesting)
Those nefarious nogoodniks - trying to ensnare innocent customers in their illegal activities!!!
Re:IBM's solution (Score:5, Interesting)
Mcbride can stop chewing his pinky and mouthing off about "1 million dollars" now, cos that won't even pay for the ink to write all the 0's on the end of the cheque he will soon have to write
The next headline? (Score:5, Funny)
Ahhhh.....I can dream, can't I?
Re:The next headline? (Score:3, Funny)
Re:The next headline? (Score:5, Funny)
SCO is S0C1
For those not from the Mainframe world, a S0C1 is an abend code meaning 'Operation Exception'. That means the program attempted to perform an operation which is not legal.
Yahoo Mirror (Score:5, Informative) [yahoo.com]
C'mon SCO! (Score:5, Funny)
Incidentally, they claim 2.5 kernels too... is that new? I thought only 2.4 was an issue.
Re:C'mon SCO! (Score:5, Informative)
Re:C'mon SCO! (Score:5, Insightful)
Just look on your bookshelf. How many programming books do you have that contain "hello.c". All the books are copyright, and yet anyone can copy "hello.c" without infringing. Why? Because copyright applies to specific works (the book, for example), not insignificant snippets, or even loosely-derived derivative works (wholesale copying is another matter - characters, plot, setting all the same == probable copyright infringement). And if you can show that you developed it independently (clean-room implementation of BIOS, for example), you haven't violated someone else's copyright anyway.
web server running IIS? (Score:5, Interesting)
$ HEAD
200 OK
Connection: close
Date: Wed, 13 Aug 2003 14:42:15 GMT
Server: Microsoft-IIS/5.0
Content-Type: text/html
Client-Date: Wed, 13 Aug 2003 14:42:16 GMT
Client-Response-Num: 1
Page-Completion-Status: Normal
Page-Completion-Status: Normal
Re:web server running IIS? (Score:5, Interesting)
ir.sco.com is running IIS. [netcraft.com]
Re:web server running IIS? (Score:5, Informative)
Details are coming out (Score:3, Insightful)
Finally, this case has become interesting.
But I'm sure
Matching Source code found!! (Score:5, Funny)
printf("\nstuff");
and
main() {
and
int x,y;
and dont forget:
}
Tm
pump pump pump (Score:3, Funny)
Angry... (Score:5, Interesting)
"...was terminated for improper transfer of Sequent's UNIX source code and development methods into Linux." (emphasis mine)
You heard it here first, people. SCO owns the UNIX development methods too. That means that producers of just about any software (because who hasn't been influenced by UNIX development methods?) will have to pay off SCO. What a bunch of bull.
Re:Angry... (Score:5, Funny)
It's okay (Score:5, Funny)
Re:It's okay (Score:5, Funny)
F:\PUBLIC>revoke.exe
Usage: REVOKE rightslist* [FOR path] FROM [USER|GROUP] name [options]
Options:
286 Rights: 386 Rights:
--------------- --------------------
ALL = All ALL = All
R = Read S = Supervisor
W = Write R = Read
O = Open W = Write
C = Create C = Create
D = Delete E = Erase
P = Parental M = Modify
S = Search F = File Scan
M = Modify A = Access Control
* Use abbreviations listed above, separated by spaces.
Novell is clearly still the holder of the right to revoke.
So can IBM attack SCO now? (Score:3, Funny)
I'd rather see IBM send in the attack lawyers in the black limos (their version of the black helicopters)...
That would be like shooting fish in a barrel with a cannon...
and well worth a video copy; would put it right next to my Rocky and Bullwinkle cartoons...
bluff much? (Score:5, Funny)
gimme a break. SCO, WHY WON'T YOU DIE???
Bah! Final! (Score:3, Insightful)
Final Stock Pump (Score:5, Insightful)
SEC...hello!!!
Re:Final Stock Pump (Score:5, Insightful)
Re:Final Stock Pump (Score:5, Insightful)
How do we know that the SEC isn't already watching the SCO? They could be giving them enough rope to hang themselves before they spring the trap. Until their case proves to be fraudulent (it appears to be overwhelmingly so now, but there is no irrefutable proof... that will be coming soon), there may actually be nothing with which the SEC can actually prosecute at this point. Once everything is in the clear and their lawsuit is proven to be what we all here believe it to be, then the SEC, who has probably been gathering evidence all of this time, will be prepared to move in. I highly doubt that the SEC is failing to notice a story of this magnitude.
McBride? McBriii-ide? Hello? (Score:5, Funny)
Sequent's code belongs to IBM! Hello? McBride?
Re:McBride? McBriii-ide? Hello? (Score:5, Funny)
Think, McBride. If I checked in my NUMA code under your copyright, I'd get sued. You wouldn't want that to happen, would you?
... Would you!?
Look, your stock's down.
:poke: Ha hah, don't be so gullible, McBride.
No Threatening Of Customers (Score:5, Interesting)
In a departure from their standard MO, SCO doesn't threaten IBM customers who currently hold Dynix/ptx licenses, and instead just claims that no new licenses may be issued.
Maybe they are starting to worry about gettting nailed on extortion charges?
Class-action suit (Score:3, Interesting)
SCO planting code (Score:5, Interesting)
But what is preventing SCO from adding in code from Linux (which is openly available) into their (closed) UNIX code and then claiming is was there first and was 'stolen' by Linux? C'mon, we are not expecting SCO's management to play fair here - how hard would it be to backdate code additions?
Forensics (Score:5, Interesting)
I'm betting that SCO would not be smart enough to take the original Linux version, but would take a newish Linux version. Showing that Linux had older (less "good") versions and SCO did not would be evidence that SCO had taken the code from Linux, not vice-versa.
So assuming that the code base(s) change(s) significantly over time, determining the provenance of version-controlled code is not all that difficult. Think of it in biological terms -- we can identify the lineage of various species/specimens by comparing their DNA and their ancestors' DNA.
Okay. (Score:3, Interesting)
So, the truth's out, is it? (Score:5, Interesting)
So, what we're really talking about is IBM code. No more BS weasle-words, they're talking about code they NEVER owned in the first place.
Well, that tears it: SCO's suing IBM for contributing their own code to the kernel. Yeah, that's totally gonna hold up in court.
Code won't be released until trial (Score:4, Insightful)
Linux kernel developers would probably have the offending pieces rewritten in a week and back-ported to all 2.4/2.5 kernels within another week.
But honestly, I really don't think IBM cares what SCO does at this point. They know their argument is probably not going to hold water in court.
Unfortuately, with the way our justice system works, it will not be heard in court until probably late 2004/2005.
Re:Code won't be released until trial (Score:4, Interesting)
That's why RedHat's suit is interesting, because they are asking for a fast decision based on the BS that SCO has been shoveling. If SCO refuses to prove it's claims of infringement by showing the code, and proving not only that SCO holds the copyright, but that their code predates the Linux stuff
... RedHat gets not only a legal declaration that it's kernel code does not infringe, but gets damages too.
They could end up owning SCO before IBM even gets to court, which means that they would therefore be suing IBM
... and I think they could settle amicably.
Re:Code won't be released until trial (Score:5, Insightful)
The clock on SCO's ability to sue the infringer/s started ticking last summer, when they claim to have noticed the problem. They have under two years to file a proper infringement of copyright suit aginst any and all infringers. (3-year time limit) Undre copyright law, whoever submitted the code is the infringer, not the unknowing distributors or totally innocent user. AFTER the infringement case/s are settled, the court may, at the court's discreton, order destruction of all copies of the infringing material. But not until the whole damned thing is settled
...
Distributors are much the same as book or magazine publisher: you must formally notify them of a copyright infringement by one of their authors (specifying not only that there is infringement, but EXACTLY what is infirnged (showing your proof of holding the copyright), and where (in a book you published in the last decade is not enough). You have to give them enough information to investigate and decide if it's infringing or not. Only after all this, and a court decision, if they continue to publish or distribute the infringing material, do they become actual infringers.
SCO has not even begun the processs that you have to follow to get copyright infringements cleared up. And their flat REFUSAL to identify the infringing material would certainly be held against them by a judge. Freezing downloads and quickly rewriting the offending code is what the developers not only WOULD do, it's what they legally MUST do, and SCO is preventing them from doing it
...
Re:Code won't be released until trial (Score:4, Insightful)
SCO isn't suing over copyright claims, they're suing over breech of contract and disclosure of trade secrets. If they can prove that then it doesn't matter, vis a vis the IBM suit, whether or not the Linux code is changed -- IBM still broke the contract and released trade secrets. The kernel devs could release a 100% brand new, totally non-infringing kernel tomorrow and it wouldn't change the arguments in the IBM suit.
All of this would have a dramatic effect on the Red Hat suit though, and I agree that that's the more interesting and relevant suit anyway. After all, even if IBM did breech contract and release trade secrets, SCO can't stuff the toothpaste back in the tube -- those trade secrets are null and void now and there's nothing that can be done about them (except for IBM paying a ton of money).
Of course, SCO's suit against IBM is only slightly less flimsy than their nebulous copyright infringement claims...
isn't this enough to find matches? (Score:5, Insightful)
Doesn't some linux zealot happen to have these sources lying around? Can't he/she just start looking for long matches in the Linux kernel?
Can't Linux developers just audit all their "critical NUMA and RCU multi-processor code", to look for shady origins? There's a big difference between the 80 lines previously claimed and the 168,000 lines now claimed!
Re:isn't this enough to find matches? (Score:4, Insightful)
SCO is finally admitting that it is Sequent code in Linux that they are upset about. There's no reason Linux developers should have to remove this code since IBM now owns Sequent and is legally allowed to contribute code it helped develop and now owns.
Re:isn't this enough to find matches? (Score:4, Interesting)
What will be interesting is if when the dust settles this is the kernel code that SCaldera have claimed is theirs and has been copied verbatim into the Kernel.
Pretty amusing when you consider that not a single line of this code originated with SCO/Caldera/AT&T or Novell and in fact the SCO group have never owned any of this code and agreements and amendments to the original SYS 5r4 license signed between IBM and AT&T grant IBM full control over any code they create for use with AIX, and that Sequent developed the technology seperate from Unix but implemented it on Unix which disallows claims from SCaldera that the code is a derivative of their work.
Since when have Press Releases (Score:5, Insightful)
This really pisses me off that companies put out "press releases" covering what should be a private matter between the parties involved.
Why don't journalists just ignore SCO in the same way a parent ignores a screaming child pushing for an ice cream?
Re:Since when have Press Releases (Score:4, Insightful)
RCU, NUMA... (Score:5, Interesting)
Re:RCU, NUMA... (Score:5, Interesting)
In other words, they are distributing the same thing they are saying has been stolen.
In other news... (Score:5, Funny)
Other SCO news/Computer Associates Settles (Score:4, Interesting)
This is an unrelated case (remember, Canopy Group makes a living suing people). However, given the timing, I am now lead to believe that part of the settlement was that CA agreed to buy some of SCO's phony "Linux Licenses".
Not the UNIX license. (Score:5, Informative)
Interestingly, this contract is with Sequent, not IBM. They're now alleging that Sequent gave IBM (it's parent) the code, breaching this contract. But seeing as IBM is a different company than Sequent, surely they were not under an obligation to keep that code to themselves; Sequent fudged up by giving it to IBM, so why should IBM's license to AIX be revoked? The Sequent contract read, according to this press release, that derivative could should be treated "as if" it were UNIX code, not that it actually became the property of SCOX.
It looks to me that the code was a trade secret at Sequent ("treaded as if..") but they retained copyright. Then it got divulged to IBM, who even obtained the copyrights, and could disperse of it as they pleased. Liability is then ristricted to Sequent's officers who breached the contract with SCOX, and perhaps some IBM officers if it can be prover they coerced Sequent. IBM's AIX license and copyrights (and thus ability to GPLize) stand, IFF this press release contains the actual facts!
It's official (Score:5, Insightful)
For those who don't know, Sequent was a super-computer company that developed a lot of the software techniques that make today's multi-processor machines (especially the more-than-2 processor systems) work well. Sequent's code was its own, and IBM bought Sequent, so at first glance IBM has every right to contribute this code to Linux, even though it has also been sold to USL/SCO.
So why is SCO suing? Because they feel that this code was written "for UNIX" and thus cannot be contributed to Linux without carrying a "taint" of UNIX IP.
SCO has made many claims about "stolen UNIX code", but that's a sham as we now see. What SCO is really upset about is that code that they think is encumbered by them, but not actually theirs was inappropriately licensed without compensation to SCO. It's not UNIX code, it's allegedly-UNIX-encumbered code, but that doesn't sound as good in a press release demanding $32 from every TiVo user....
In fact it sounds suspiciously like a case where SCO will have to fight an up-hill battle over IP rights that aren't really clear to begin with, and even then they have to fight the GPL issue, which (given that they still offer a Linux kernel for download) will be difficult....
Re:It's official (Score:5, Insightful)...
Yeah, sure. Just like all the executives at Enron and Worldcom went to jail after all their illegal acounting and other shady business practices. I don't think so. Your faith in the FTC and SEC makes me laugh!
Sequent (Score:4, Insightful)
Not just a super-computer company... they also built high end Unix servers. Georgia Tech had a Sequent box running Dynix as the main campus computer system from the late 80's to early 90's. IIRC, hydra was a 16-CPU system with 386DX's. And while at the end of its life (1993 I think) it was godawful slow, it was still better than the Sun box (which later became boxes) that replaced it (GT and Sun discovered that Solaris did very poorly in a heavily task switched environment, spending up to 80% of CPU time in overhead... that's improved since, but AFAIK they never quite fixed the problem). Dynix was the first Unix OS I ever used. It was a helluva lot better than Ultrix, but that's about all I recall about it.
at first glance IBM has every right to contribute this code to Linux
Yeah, but SCO is claiming that Sequent's license didn't include transferral of license, that the various multiprocessor technologies were derivative works, and that SCO retained rights to all derivative works under that license. IBM did buy a perpetual, non-revokable, fully paid, yadda yadda yadda license for Unix, but that was prior to the purchase of Sequent. SCO is thus claiming that Sequent's license holds true here and that IBM didn't have the right to distribute the code without SCO's approval. IBM does, however, hold the patents to the technologies in question. It may become a question not only of which license applies, but also whether or not the code contributed to Linux was the same as the code that Sequent had or if it was a re-implementation of the patent that IBM holds.
Curiouser and Curiouser (Score:4, Interesting)
Right?
I wonder who bought the stock that's been selling off.
SCO is using RIAA math -- Explains all! (Score:5, Funny)
Maybe they're using RIAA-math? They might mean that one file is typically 50 lines, so any file with say 2000 lines counts as "the equivalent of 40 files"
(for those who don't get it, see here [gnutellanews.com])
I posted this late last time... (Score:4, Funny)
SCOX (Lola) Song [slashdot.org]
Enjoy...
(To the tune of "Lola" by The Kinks)
I met them in a club down in Santa Cruz
where you code in C and it looks just like
the Linux kernel... K-E-R-N Kernel
They walked up to me and asked me to desist
I asked them their name and in a cowardly voice they said,
"SCOX"... S-C-O-X SCOX, sco sco sco sco-X
Well I'm not the world's most intelligent guy
But when they showed me the code I almost cried
Oh my SCOX, sco sco sco sco-X
Well I'm not dumb but I can't understand
How they stay in business with blood on their hands
Oh my SCOX, sco sco sco sco-X
Well they filed their claims and sued all night,
thanks to Microsoft's failing might
They picked me up and sat me on their knees
Saying, "Linux coder won't you turn and flee?"
Well I'm not the world's most logical guy
And when I looked at the comments
I almost fell for their bullshit
bull bull bull bull-shit
sco sco sco sco sco-X
I laughed them away. I walked to the court.
I filed a countersuit. They'll be down on their knees.
Now that IBM is looking out for me
And that's the way that I want it to be
They'll clean them out and make them pay
Oh my SCOX, sco sco sco sco-X
Linux will be UNIX, and UNIX will be Linux
It's a scratched-out, messed-up, crazy diagram
thanks to SCOX. sco sco sco sco-X
Well I posted to LKML just a week before
saying I never ever leaked code before
SCOX smiled and said "We understand,"
saying, "Linux coder, you can do what you can"
Well I'm not the world's most open source guy
but I know Richard Stallman and I bet that they'll fry
oh my SCOX, sco sco sco sco sco-X
sco sco sco sco-X
Troubling moves by SCO.... (Score:5, Insightful)
When McBride came onto the scene he started to talking about IP issues. I have no issues with a company setting out to see their IP is being used and whether the parties that are using it have paid the appropriate licenses for it.
Lets fast forward a little. SCO suddenly kills off their Linux business and throws all their programmers to SuSE so basically SCO simply becomes a reseller. Considering that they have made no profits so far from Linux and have almost a 0% marketshare, maybe their last resort is hair spliting.
Over the next several months the accusations have moved from being IP vioations to contractural issues.
Lets give a brief rewind, the last version of SCO Linux to be released before Ransom Love left was Caldera OpenLinux 3.1.1 and it was loaded with 2.4.13. Having the RCU code in the Linux kernel since the VERY early test releases, and it has taken almost 21 releases, around 2 years for SCO to come out of the wood works and complain.
Here is my take, when Ransom Love was in "their" they most likely looked at the possibility of litigation, however, due to a gray area in the IBM contract Love most likely decided not to persue a dead end law suite.
Fast forward to today and we have a new management trying their luck in a vein hope of sucking money out of IBM to prop up their failing business.
Sorry, UnixWare and OpenServer failed because they "suck". Sorry, I can't come up with a better adjective for their current line up. Poor scalability, waaaaaay over priced, heck, it makes Microsoft look charietable with their license pricing and they have next to no ISV and IHV support. No wonder SCO is dying.
Actual transcript smuggled out of the courthouse (Score:5, Funny)
IBM-What?
SCO-None shall compile.
IBM-I have no quarrel with you, brave SCO, but I must distribute UNIX.
SCO-Then you shall be sued.
IBM-I command you to stand aside.
SCO-I move for no corporation.
IBM-So be it!
IBM draws his sword and approaches the SCO. A furious fight now starts lasting about fifteen seconds at which point IBM delivers a mighty blow which completely severs the SCO's left
arm at the shoulder. IBM steps back triumphantly.
IBM-Now stand aside worthy adversary.
SCO-(glancing at his shoulder)
'Tis but a scratch.
IBM-A scratch? Your arm's off.
SCO-No, it isn't.
IBM-(pointing to the arm on ground)
Well, what's that then?
SCO-I've had worse.
IBM-You're a liar.
SCO-Come on you pansy!
Another ten seconds furious fighting till IBM chops the SCO's other arm off, also at the shoulder. The arm plus sword, lies on the ground.
IBM-Victory is mine.
(sinking to his knees)
I thank thee O Lord that in thy...
SCO-Come on then.
IBM-What?
He kicks IBM hard on the side of the helmet. IBM gets up still holding his sword. The SCO comes after him kicking.
IBM-You are indeed brave SCO, but the fight is mine.
SCO-Had enough?
IBM-You stupid bastard. You haven't got any arms left.
SCO-Course I have.
IBM-Look!
SCO-What! Just a flesh wound.
(kicks IBM)
IBM-Stop that.
SCO-(kicking him)
Had enough?
IBM-I'll have your leg.
He is kicked.
IBM-Right!
The SCO kicks him again and IBM chops his leg off. The SCO keeps his balance with difficulty.
SCO-I'll do you for that.
IBM-You'll what... ?
SCO-Come Here.
IBM-What are you going to do. bleed on me?
SCO-I'm invincible!
IBM-You're a loony.
SCO-SCO always triumphs. Have at you!
IBM takes his last leg off. The SCO's body lands upright.
SCO-All right, we'll call it a draw.
Proprietary Code Snippet...? (Score:5, Funny)
#include "enron.h"
void SCO_keep_alive()
{
while(!inCourt()){
try{
generateFUD();
extortLicensesFromLinuxUsers();
}
catch(ImpendingIBMSuit suit)
{
int numShares = MAX_INT;
dumpStock(numShares);
terminateLicense("IBM");
}
}
fileChapter(11);
}
"UNIX-based development methods" (Score:4, Insightful)
Sleeping Giant (Score:5, Insightful)
"I fear that we have awakened a sleeping giant
and filled him with a terrible resolve"
Admiral Isoroku Yamamoto
December 7th, 1941
Anybody not see the parallels? SCO has launched an unprovoked sneak attach against the sleeping giant, (IBM) and the Linux community. And this war will end the same way, with the legal equivalent of an atomic bomb delivered to SCO.
Linux's Future After SCO (Score:4, Insightful)
RCU Code NOT from Sequent Unix (Score:5, Informative)
One of the copyright notices from a file:
Support for deferred freeing of memory using Read-Copy Update: Dipankar Sarma [dipankar@sequent.com]
(Based on a Dynix/ptx implementation by
Paul Mckenney [paul.mckenney@us.ibm.com])
IBM aquired Sequent in 1999, the copyright notice on this file from 2001. The important thing is that this code is based on an implementation and not the actual original code as such this is not Dynix/pty code.
SCO could argue that since it is based on the code then it is actually a copy, however from what I have seen of the contract clauses (mainly from groklaw) IBM are free to use any knowledge/processes/etc gained from adding to AIX.
Probably the two pieces of code look similar and I can believe even the comments since the implementor had access to original code. In addition to this it could be argued that it would be impossible to implement the code without there being similarities or even being nearly identical in places. For example try implementing a bouble-sort/linked list/etc without the code looking similar.
The only thing left are the RCU patents and IBM own these.
Having looked at this now SCO's case is pretty thin, they could win of course nothing is impossible (though unlikely), however it would just be a case of copyright violation and someone outside of IBM could do a re-implementation of RCU. In addition since RCU is n't part of the mainstream Linux kernel so I cant see how they could claim any substantial damages let alone $3 billion.
SCO's carefully phrased release... (Score:5, Interesting)
The release says that IBM was (allegedly) contractually obligated to treat its OWN work product which it developed based on SCO's predecessor's code in the same way (i.e., subject to the same restrictions) as the code it had licensed from SCO. It quite carefully says that IBM contributed "148 files of direct Sequent UNIX code" to Linux. But what SCO is talking about here ("Sequent UNIX code") is IBM's code, and not SCO's or AT&T's code. If IBM agreed to make its own code be subject to the license (and IBM says that it did not, since it claims that this provision was overriden by a side letter agreement that made completely different arrangements), then this would be a matter of contract between IBM and SCO (which IBM is very vigorously contesting). It would not mean that SCO owns the copyright to subject matter independently developed by IBM.
It would not, even if true, give SCO any rights vis-a-vis a Linux user who had nothing to do with IBM and/or its contract with SCO. Off hand, I would say that the only way a Linux user would be at risk would be if there were substantial code written by the original copyright owner that found its way in some recognizable form into the Linux 2.4 or 2.5 kernels, and (even it that turned out to be the case), if the copyright owner never gave its permission for that code to be included. I have not seen where either of these contentions has been clearly alleged, except by implication, as a result fo SCO's threats.
It is of course possible that there is such code overlap, but it is SCO's burden to prove it. I have not seen any proof of this. Even if they were to prove it, the Linux user would then be allowed to show SCO's consent to this inclusion, such as by the authorized release of the code in question under the GPL.
It seems to me that SCO's case against the typical Linux business user is awfully speculative at this point.
Interesting stock reporting. (Score:5, Informative)
Ralph Yarro
Darcy Mott
Canopy Group Inc
John Wall
If you then check out The Canopy Group [canopy.com] website you will see the following as board members
Ralph Yarro - CEO & Presedent
Darcy Motto - Vice President, Treasurer and Chief Financial Officer
This gives the Canopy group at least a 15% stake in SCO, possibly more.
If you look at SCO's board [sco.com] and then have a look at their share trading [nasdaq.com], you see the following:-
Charles BROUGHTON (VP world ops) sold about 120,000 USD worth of shares in the last two months
Robert BENCH (CFO) sold about 120K USD in last few months
Jeff HUNSAKER (s. VP)sold about 120K USD in last few months
Other than McBride (CEO) most of the board have ofloaded shares in the last month or two. To give you an idea of the "peak" of share selling. According to the Nasdaq the number of "insider" trades (i.e. board members) in the last 12 months was 15, and 12 (all of which were sales) of those were in the last 3 months (or as its know just after the Linux thing).
Yarro and Mott both also sit on the board of SCO.
Does that stink or is it just me?
Jaj
SCO = Calvinball (Score:5, Funny)
Contract disputes are legal play, except on Reverse Days or while standing in the Invisible Box. SCO attacks Linux users with FUD, and Novell makes them sing the Sorry Song. But SCO claims Novell was in the Reciprocity Zone, so it has to sing the song instead.
SCO says it owns IBMs code because IBM crossed the Hidden Contract line, but IBM claims today was negative day and now it wants everything that SCO owns.
The score is now 12 to Q, and I eagerly await the next round.
SCO's legal approach - derived work (Score:5, Interesting)
What constitutes a derived work is going to be the real copyright issue here. Outside the software arena, the notion of a derived work has been very broadly interpreted. Movies based on novels have been held to be derived works even when the connection between the two included little more than the title and the name of the lead character.
IBM has retained Cravath, Swaine, and Moore, probably the strongest litigation firm for difficult cases in the world. The Cravath approach on big cases is to put an army of lawyers on the problem and litigate everything to death. We'll probably see a detail-oriented litigation, rather than one based on broad principles. Following a Cravath lawsuit tends to be a mind-numbing experience for all concerned.
SCO is really getting desperate (Score:4, Interesting)
In fact, IBM addresses both the issue of the stock price manipulation and SCO's continued misrepresentation of the AIX license in their counterclaim. For SCO to continue to make these sorts of public statements is insane.
NUMA from SCO my ass (Score:5, Informative)
/*
* Written by Kanoj Sarcar, SGI, Aug 1999
*/
arch/x86_64/mm/numa.c:
/*
* Generic VM initialization for x86-64 NUMA setups.
* $Id: numa.c,v 1.6 2003/04/03 12:28:08 ak Exp $
*/
/*
* linux/arch/alpha/mm/numa.c
*
* DISCONTIGMEM NUMA alpha support.
*
*/
Re:multi processor, eh? (Score:4, Interesting) | http://slashdot.org/story/03/08/13/146246/sco-announces-final-termination-of-ibms-licence | CC-MAIN-2015-48 | refinedweb | 8,283 | 71.04 |
# About embedded again: searching for bugs in the Embox project

Embox is a cross-platform, multi-tasking real-time operating system for embedded systems. It is designed to work with limited computing resources and allows you to run Linux-based applications on microcontrollers without using Linux itself. Certainly, the same as other applications, Embox couldn't escape from bugs. This article is devoted to the analysis of errors found in the code of the Embox project.
A few months ago, I already wrote an [article](https://www.viva64.com/en/b/0684/) about checking FreeRTOS, another OS for embedded systems. I did not find errors in it then, but I found them in libraries added by the guys from Amazon when developing their own version of FreeRTOS.
The article that you are reading at the moment, in some way continues the topic of the previous one. We often received requests to check FreeRTOS, and we did it. This time, there were no requests to check a specific project, but I began to receive emails and comments from embedded developers who liked the previous review, and wanted more of them.
Well, the new publication of the column «PVS-Studio Embedded» is completed and is right in front of you. Enjoy reading!
The analysis procedure
----------------------
The analysis was carried out using PVS-Studio — the static code analyzer for C, C++, C#, and Java. Before the analysis, the project needs to be built — this way we will be sure that the project code is working, and we will also give the analyzer the opportunity to collect the built information that can be useful for better code checking.
The instructions in the [official Embox repository](https://github.com/embox/embox/) offer the ability to build under different systems (Arch Linux, macOS, Debian) and using Docker. I decided to add some variety to my life — to build and analyze the project under Debian, which I've recently installed on my virtual machine.
The build went smoothly. Now I had to move on to the analysis. Debian is one of the Linux-based systems supported by PVS-Studio. A convenient way to check projects under Linux is to trace compiler runs. This is a special mode in which the analyzer collects all the necessary information about the build so that you can then start the analysis with one click. All I had to do was:
1) Download and install PVS-Studio;
2) Launch the build tracking by going to the folder with Embox and typing in the terminal
```
pvs-studio-analyzer analyze -- make
```
3) After waiting for the build to complete, run the command:
```
pvs-studio-analyzer analyze -o /path/to/output.log
```
4) Convert the raw report to any convenient format The analyzer comes with a special utility PlogConverter, with which you can do this. For example, the command to convert the report to task list (for viewing, for example, in QtCreator) will look like this:
```
plog-converter -t tasklist -o /path/to/output.tasks /path/to/project
```
And that's it! It took me no more than 15 minutes to complete these steps. The report is ready, now you can view the errors. So let's get going!
Strange loop
------------
One of the errors found by the analyzer was the strange *while* loop:
```
int main(int argc, char **argv) {
....
while (dp.skip != 0 ) {
n_read = read(ifd, tbuf, dp.bs);
if (n_read < 0) {
err = -errno;
goto out_cmd;
}
if (n_read == 0) {
goto out_cmd;
}
dp.skip --;
} while (dp.skip != 0); // <=
do {
n_read = read(ifd, tbuf, dp.bs);
if (n_read < 0) {
err = -errno;
break;
}
if (n_read == 0) {
break;
}
....
dp.count --;
} while (dp.count != 0);
....
}
```
**PVS-Studio warning**: [V715](https://www.viva64.com/en/w/v715/) The 'while' operator has empty body. Suspicious pattern detected: 'while (expr) {...} while (dp.skip != 0) ;'. dd.c 225
Hm. A weird loop indeed. The expression *while (dp.skip != 0)* is written twice, once right above the loop, and the second time — just below it. In fact, now these are two different loops: one contains expressions in curly braces, and the second one is empty. In this case, the second loop will never be executed.
Below is a *do… while* loop with a similar condition, which leads me to think: the strange loop was originally meant as *do… while*, but something went wrong. I think, this piece of code most likely contains a logical error.
Memory leaks
------------
Yes, they also sneaked in a plug.
```
int krename(const char *oldpath, const char *newpath) {
char *newpatharg, *oldpatharg;
....
oldpatharg =
calloc(strlen(oldpath) + diritemlen + 2, sizeof(char));
newpatharg =
calloc(strlen(newpath) + diritemlen + 2, sizeof(char));
if (NULL == oldpatharg || NULL == newpatharg) {
SET_ERRNO(ENOMEM);
return -1;
}
....
}
```
**PVS-Studio warnings:**
* [V773](https://www.viva64.com/en/w/v773/) The function was exited without releasing the 'newpatharg' pointer. A memory leak is possible. kfsop.c 611
* [V773](https://www.viva64.com/en/w/v773/) The function was exited without releasing the 'oldpatharg' pointer. A memory leak is possible. kfsop.c 611
The function creates the local variables *newpatharg* and *oldpatharg* inside itself. These pointers are assigned the addresses of new memory locations allocated internally using *calloc*. If a problem occurs while allocating memory, *calloc* returns a null pointer.
What if only one block of memory can be allocated? The function will crash without any memory being freed. The fragment that happened to be allocated will remain in memory without any opportunity to access it again and free it for further use.
Another example of a memory leak, a more illustrative one:
```
static int block_dev_test(....) {
int8_t *read_buf, *write_buf;
....
read_buf = malloc(blk_sz * m_blocks);
write_buf = malloc(blk_sz * m_blocks);
if (read_buf == NULL || write_buf == NULL) {
printf("Failed to allocate memory for buffer!\n");
if (read_buf != NULL) {
free(read_buf);
}
if (write_buf != NULL) {
free(write_buf);
}
return -ENOMEM;
}
if (s_block >= blocks) {
printf("Starting block should be less than number of blocks\n");
return -EINVAL; // <=
}
....
}
```
**PVS-Studio warnings:**
* [V773](https://www.viva64.com/en/w/v773/) The function was exited without releasing the 'read\_buf' pointer. A memory leak is possible. block\_dev\_test.c 195
* [V773](https://www.viva64.com/en/w/v773/) The function was exited without releasing the 'write\_buf' pointer. A memory leak is possible. block\_dev\_test.c 195
Here the programmer has shown neatness and correctly processed the case in which only one piece of memory was allocated. Processed correctly… and literally in the next expression made another mistake.
Thanks to a correctly written check, we can be sure that at the time the *return -EINVAL* expression is executed, we will definitely have memory allocated for both *read\_buf* and *write\_buf*. Thus, with such a return from the function, we will have two leaks at once.
I think that getting a memory leak on an embedded device can be more painful than on a classic PC. In conditions when resources are severely limited, you need to monitor them especially carefully.
Pointers mishandling
--------------------
The following erroneous code is concise and simple enough:
```
static int scsi_write(struct block_dev *bdev, char *buffer,
size_t count, blkno_t blkno) {
struct scsi_dev *sdev;
int blksize;
....
sdev = bdev->privdata;
blksize = sdev->blk_size; // <=
if (!sdev) { // <=
return -ENODEV;
}
....
}
```
**PVS-Studio warning**: [V595](https://www.viva64.com/en/w/v595/) The 'sdev' pointer was utilized before it was verified against nullptr. Check lines: 116, 118. scsi\_disk.c 116
The *sdev* pointer is dereferenced just before it is checked for *NULL*. It is logical to assume that if someone wrote such a check, then this pointer may be null. In this case, we have the potential dereferencing of the null pointer in the line *blksize = sdev->blk\_size*.
The error is that the check is not located where it is needed. It should have come after the line"*sdev = bdev->privdata;*", but before the line "*blksize = sdev->blk\_size;*". Then potential accessing by the null address could be avoided.
PVS-Studio found two more errors in the following code:
```
void xdrrec_create(....)
{
char *buff;
....
buff = (char *)malloc(sendsz + recvsz);
assert(buff != NULL);
....
xs->extra.rec.in_base = xs->extra.rec.in_curr = buff;
xs->extra.rec.in_boundry
= xs->extra.rec.in_base + recvsz; // <=
....
xs->extra.rec.out_base
= xs->extra.rec.out_hdr = buff + recvsz; // <=
xs->extra.rec.out_curr
= xs->extra.rec.out_hdr + sizeof(union xdrrec_hdr);
....
}
```
**PVS-Studio warnings:**
* [V769](https://www.viva64.com/en/w/v769/) The 'xs->extra.rec.in\_base' pointer in the 'xs->extra.rec.in\_base + recvsz' expression could be nullptr. In such case, resulting value will be senseless and it should not be used. Check lines: 56, 48. xdr\_rec.c 56
* [V769](https://www.viva64.com/en/w/v769/) The 'buff' pointer in the 'buff + recvsz' expression could be nullptr. In such case, resulting value will be senseless and it should not be used. Check lines: 61, 48. xdr\_rec.c 61
The buf pointer is initialized with *malloc*, and then its value is used to initialize other pointers. The *malloc* function can return a null pointer, and this should always be checked. One would think, that there is the *assert* checking *buf* for *NULL*, and everything should work fine.
But not so fast! The fact is that asserts are used for debugging, and when building the project in the Release configuration, this *assert* will be deleted. It turns out that when working in Debug, the program will work correctly, and when building in Release, the null pointer will get further.
Using *NULL* in arithmetic operations is incorrect, because the result of such an operation will not make any sense, and you can't use such a result. This is what the analyzer warns us about.
Someone may object that the absence of the check after *malloc*/*realloc*/*calloc* is not crucial. Meaning that, at the first access by a null pointer, a signal / exception will occur and nothing scary will happen. In practice, everything is much more complicated. If the lack of the check does not seem dangerous to you, I suggest that you check out the article "[Why it is important to check what the malloc function returned](https://www.viva64.com/en/b/0558/)".
Incorrect handling of arrays
----------------------------
The following error is very similar to the example before last:
```
int fat_read_filename(struct fat_file_info *fi,
void *p_scratch,
char *name) {
int offt = 1;
....
offt = strlen(name);
while (name[offt - 1] == ' ' && offt > 0) { // <=
name[--offt] = '\0';
}
log_debug("name(%s)", name);
return DFS_OK;
}
```
**PVS-Studio warning**: [V781](https://www.viva64.com/en/w/v781/) The value of the 'offt' index is checked after it was used. Perhaps there is a mistake in program logic. fat\_common.c 1813
The *offt* variable is first used inside the indexing operation, and only then it is checked that its value is greater than zero. But what happens if *name* turns out to be an empty string? The *strlen()* function will return *0*, followed by epic shooting yourself in the foot. The program will access by a negative index, which will lead to undefined behavior. Anything can happen, including a program crash. Not good at all!

Suspicious conditions
---------------------
Just can't do without them! We find such errors literally in every project that we check.
```
int index_descriptor_cloexec_set(int fd, int cloexec) {
struct idesc_table *it;
it = task_resource_idesc_table(task_self());
assert(it);
if (cloexec | FD_CLOEXEC) {
idesc_cloexec_set(it->idesc_table[fd]);
} else {
idesc_cloexec_clear(it->idesc_table[fd]);
}
return 0;
}
```
**PVS-Studio warning**: [V617](https://www.viva64.com/en/w/v617/) Consider inspecting the condition. The '0x0010' argument of the '|' bitwise operation contains a non-zero value. index\_descriptor.c 55
In order to get where the error hides, let's look at the definition of the *FD\_CLOEXEC* constant:
```
#define FD_CLOEXEC 0x0010
```
It turns out that there is always a nonzero constant in the expression *if (cloexec | FD\_CLOEXEC)* to the right of the bitwise «or». The result of such an operation will always be a nonzero number. Thus, this expression will always be equivalent to the *if(true)* expression, and we will always process only the then branch of the if statement.
I suspect that this macro constant is used to pre-configure the Embox OS, but even if so this always true condition looks strange. Perhaps authors wanted to use the *&* operator, but made a typo.
Integer division
----------------
The following error relates to one feature of the C language:
```
#define SBSIZE 1024
static int ext2fs_format(struct block_dev *bdev, void *priv) {
size_t dev_bsize;
float dev_factor;
....
dev_size = block_dev_size(bdev);
dev_bsize = block_dev_block_size(bdev);
dev_factor = SBSIZE / dev_bsize; // <=
ext2_dflt_sb(&sb, dev_size, dev_factor);
ext2_dflt_gd(&sb, &gd);
....
}
```
**PVS-Studio warning**: [V636](https://www.viva64.com/en/w/v636/) The '1024 / dev\_bsize' expression was implicitly cast from 'int' type to 'float' type. Consider utilizing an explicit type cast to avoid the loss of a fractional part. An example: double A = (double)(X) / Y;. ext2.c 777
This feature is as follows: if we divide two integer values, then the result of the division will be integer as well. Thus, division will occur without a remainder, or, in other words, the fractional part will be discarded from the division result.
Sometimes programmers forget about it, and errors like this come out. The SBSIZE constant and the *dev\_bsize* variable are of the integer type (int and size\_t, respectively). Therefore, the result of the *SBSIZE / dev\_bsize* expression will also be of the integer type.
But hold on. The *dev\_factor* variable is of the *float* type! Obviously, the programmer expected to get a fractional division result. This can be further verified if you pay attention to the further use of this variable. For example, the *ext2\_dflt\_sb* function, where *dev\_factor* is passed as the third parameter, has the following signature:
```
static void ext2_dflt_sb(struct ext2sb *sb, size_t dev_size, float dev_factor);
```
Similarly, in other places where the *dev\_factor* variable is used: everything indicates that a floating-point number is expected.
To correct this error, one just has to cast one of the division operands to the floating-point type. For example:
```
dev_factor = float(SBSIZE) / dev_bsize;
```
Then the result of the division will be a fractional number.
Unchecked input data
--------------------
The following error is related to the use of unchecked data received from outside of the program.
```
int main(int argc, char **argv) {
int ret;
char text[SMTP_TEXT_LEN + 1];
....
if (NULL == fgets(&text[0], sizeof text - 2, /* for \r\n */
stdin)) { ret = -EIO; goto error; }
text[strlen(&text[0]) - 1] = '\0'; /* remove \n */ // <=
....
}
```
**PVS-Studio warning**: [V1010](https://www.viva64.com/en/w/v1010/) Unchecked tainted data is used in index: 'strlen(& text[0])'. sendmail.c 102
Let's start with considering what exactly the *fgets* function returns. In case of successful reading of a string, the function returns a pointer to this string. In case if *end-of-file* is read before at least one element, or an input error occurs, the *fgets* function returns *NULL*.
Thus, the expression *NULL == fgets(....)* checks if the input received is correct. But there is one detail. If you pass a null terminal as the first character to be read (this can be done, for example, by pressing Ctrl + 2 in the Legacy mode of the Windows command line), the *fgets* function takes it into account without returning *NULL*. In doing so, there will be only one element in the string supposed for writing which is *\0*'.
What will happen next? The expression *strlen(&text[0])* will return 0. As a result, we get a call by a negative index:
```
text[ 0 - 1 ] = '\0';
```
As a result, we can crash the program by simply passing the line termination character to the input. It is rather sloppy and it could potentially be used to attack systems that are using Embox.
My colleague who was developing this diagnostic rule even made a recording of an example of such an attack on the NcFTP project:
I recommend checking out if you still do not believe that it might happen :)
The analyzer also found two more places with the same error:
* V1010 Unchecked tainted data is used in index: 'strlen(& from[0])'. sendmail.c 55
* V1010 Unchecked tainted data is used in index: 'strlen(& to[0])'. sendmail.c 65
MISRA
-----
MISRA is a set of guidelines and rules for writing secure C and C++ code for highly dependable embedded systems. In some way, this is a set of guidelines, following which you will be able to get rid of so called «code smells» and also protect your program from vulnerabilities.
MISRA is used where human lives depend on the quality of your embedded system: in the medical, automotive, aircraft and military industries.
PVS-Studio has an [extensive set](https://www.viva64.com/en/misra/) of diagnostic rules that allow you to check your code for compliance with MISRA C and MISRA C++ standards. By default, the mode with these diagnostics is turned off, but since we are looking for errors in a project for embedded systems, I simply could not do without MISRA.
Here is what I managed to find:
```
/* find and read symlink file */
static int ext2_read_symlink(struct nas *nas,
uint32_t parent_inumber,
const char **cp) {
char namebuf[MAXPATHLEN + 1];
....
*cp = namebuf; // <=
if (*namebuf != '/') {
inumber = parent_inumber;
} else {
inumber = (uint32_t) EXT2_ROOTINO;
}
rc = ext2_read_inode(nas, inumber);
return rc;
}
```
**PVS-Studio warning**: [V2548](https://www.viva64.com/en/w/v2548/) [MISRA C 18.6] Address of the local array 'namebuf' should not be stored outside the scope of this array. ext2.c 298
The analyzer detected a suspicious assignment that could potentially lead to undefined behavior.
Let's take a closer look at the code. Here, *namebuf* is an array created in the local scope of the function, and the *cp* pointer is passed to the function by pointer.
According to C syntax, the name of the array is a pointer to the first element in the memory area in which the array is stored. It turns out that the expression *\*cp = namebuf* will assign the address of the array *namebuf* to the variable pointed by *cp*. Since *cp* is passed to the function by pointer, a change in the value that it points to will affect the place where the function was called.
It turns out that after the *ext2\_read\_symlink* function completes its work, its third parameter will indicate the area that the *namebuf* array once occupied.
There is only one slight hitch: since *namebuf* is an array reserved on the stack, it will be deleted when the function exits. Thus, a pointer that exists outside the function will point to the freed part of memory.
What will be at that address? No one can say for sure. It is possible that for some time the contents of the array will continue to be in memory, or it is possible that the program will immediately replace this area with something else. In general, accessing such an address will return an undefined value, and using such a value is a gross error.
The analyzer also found another error with the same warning:
* [V2548](https://www.viva64.com/en/w/v2548/) [MISRA C 18.6] Address of the local variable 'dst\_haddr' should not be stored outside the scope of this variable. net\_tx.c 82

Conclusion
----------
I liked working with the Embox project. Despite the fact that I did not cite all the found errors in the article, the total number of warnings was relatively small, and in general, the project code is of high quality. Therefore, I express my gratitude to the developers, as well as to those who contributed to the project on behalf of the community. You did great!
On this occasion, let me send my best to the developers. Hope that it's not very cold in St. Petersburg right now :)
At this point, my article comes to an end. I hope you enjoyed reading it, and you found something new for yourself.
If you are interested in PVS-Studio and would like to independently check a project using it, [download and try it](https://www.viva64.com/en/pvs-studio-download/). This will take no more than 15 minutes. | https://habr.com/ru/post/499984/ | null | null | 3,360 | 57.27 |
I am generating a PdfPTable and adding it to a Chapter, and then adding the Chapter to my Document. My table has several cells where RowSpan > 1, and sometimes those spans cross page boundaries, and when that happens I want the spanned cell to appear again. In other words, if my table looks like this:
+------------------+------------------+ | Cell 1 RowSpan=1 | Cell 2 RowSpan=3 | +------------------+------------------+ | Cell 3 RowSpan=1 | | +------------------+------------------+ | Cell 4 RowSpan=1 | | +------------------+------------------+
but when printed, there's a page break between rows 2 and 3, I want the table to look like this:
+--------+--------+ | Cell 1 | Cell 2 | +--------+ | | Cell 3 | | +--------+--------+ Page Break +--------+--------+ | Cell 4 | Cell 2 | +--------+--------+
This is working thanks to a trick I learned here, I have a class which implements IPdfPCellEvent which I instantiate and attach to cells that have RowSpan > 1:
public class CellEvent : IPdfPCellEvent { Phrase m_phrase; bool m_first = true; public CellEvent(Phrase phrase) { m_phrase = phrase; } void IPdfPCellEvent.CellLayout(PdfPCell cell, Rectangle r, PdfContentByte[] canvases) { if (m_first) m_first = false; else { ColumnText ct = cell.Column; ct.Canvases = canvases; m_phrase.Leading = m_phrase.Font.Size; ct.AddElement(m_phrase); ct.Go(); } } }
If the CellLayout() gets called more than once, the subsequent calls are happening because the RowSpan has spilled onto a new page (the exact situation I described above) and so I manually re-draw the cell text. This works great.
Except.
If my cell 2 is taller than my cell 1:
+------------------+--------------
The solution I came up with, is non-iterative (see @ChrisHaas' idea in the comments) but took a bit more code. It's more code than I want to upload here, but the basic idea is this: | http://www.devsplanet.com/question/35277371 | CC-MAIN-2017-04 | refinedweb | 266 | 60.58 |
Google Summer of Code 2007
This year Inkscape is going to participate, yet again, in Google's Summer of Code (SoC) 2007. Help us come up with some solid places to innovate and push forward.
Contents
- 1 Student Applications
- 2 Project Ideas
- 2.1 General
- 2.2 Import/export
- 2.3 SVG features
- 2.4 Raster Graphics
- 2.5 Your own original ideas
- 3 Past Years
Student Applications
- Google program information
- Summer of Code Application form
- Inkscape-specific information
- SOC Application Template
- Inkscape Roadmap - to see our overall objectives
- SOC Writing Project Proposals - some guidelines for proposals
- SOC Selection Criteria - how we rate applications
Project Ideas
General
3D Tool
Inkscape is a 2D drawing tool. However, very often it is used to draw 3D objects. It would be very cool to have more support from the program for doing that, instead of just drawing everything manually. Nothing too fancy - we're not going to compete with Blender; but even simple things can go a long way. What's listed below is just basic ideas; feel free to develop upon them or offer something entirely different in your proposal.
A 3D box tool would be able to:
- draw a 3D box;
- adjust any of its 3 dimensions by handles and numerically;
- freely move the perspective vanishing point for each dimension;
- switch any dimension from a vanishing point to direction (point in infinity, lines are parallel) and back;
- subdivide or multiply the box to create perspective grids;
- when more than one 3D box is selected and their perspective is compatible, drag their common vanishing points/directions updating all selected boxes;
- 3D-rotate the entire selected 3D box (or several selected 3D boxes if they have a compatible perspective), thus moving all 3 directions/vanishing points in a natural way;
- remember the last-set directions/vanishing points and create new objects in the same perspective, so you can quickly and easily draw an entire 3D scene with many boxes;
In SVG, a 3D box will be represented as a group (svg:g) with a special extension attribute (in inkscape namespace); the group would normally contain the 6 quadrilateral paths representing the sides of the box. Only the 3D box tool would treat this object as a whole; for all other tools it will be just a group, so you can select any of the paths, apply any style to it, delete it, etc. You can of course transform the group or any face in it using Selector or Node tools. At the same time, the 3D tool would still be able to 3D-rotate and 3D-tweak the box while preserving any changed style (but not necessarily preserving transforms or node edits of individual sides) and not restoring deleted sides (e.g. if you don't want to see the hidden sides, simply delete them as objects from the group). The tool must also be able to create "degenerate" boxes - planes and lines represented as boxes with one or two dimensions equal to zero.
In the UI, drawing with this tool creates a box with 4 handles on the box (3 for changing its dimensions and one in the center for dragging it in 3D) and 3 more perspective handles. If some dimension has a vanishing point, its perspective handle is (for example) diamond; if that dimension has infinity vanishing point, the corresponding handle is round (and can adjust only direction from the center). Dragging box handles without Shift moves them in X/Y plane, with Shift in Z. If multiple boxes selected and their perspectives are compatible, the corresponding handles snap together and dragging them affects everything selected.
3D guides can be a helpful addition to the 3D box tool. You would be able to create a new set of 3D guides from any 3D box and then use these guides for drawing with any tool that can snap to guides (e.g. the Pen tool). The guides would use different colors for the three dimensions. Ideally the guides should remember which object they were created from and update when that object's perspective (the set of 3 vanishing points or directions) is edited in the 3D tool.
Mini FAQ:
- Why not improve integration with Blender instead? Because even if Inkscape/Blender integration were much more seamless than now, and even if Blender's UI were much more like Inkscape's, (neither of which is true), it would still suck to have a separate program for such a basic aspect of your drawing as (essentially) objects' shapes.
- Besides, Blender has a different approach to 3D than what I want for Inkscape. In Blender, you shape your objects, position them in a 3D space, and position your point of view in the same space to get some picture. That's fine if what you are interested in is the 3D world. But traditional artists do not work like that. They don't need a 3D world; they need a 2D drawing that gives an impression of 3D. From the times of Leonardo, this means starting with placing your perspective vanishing points/directions and then drawing objects to conform to these. That's the most natural approach for a 2D artist. I don't know if Blender allows you to freely drag the vanishing points at all (and even if it does, it's hardly the default editing mode in it). In Inkscape, that will be the main mode of interaction, very similar to the way all other shapes are edited by dragging their control handles.
- Isn't it the same as Extrude or Perspective tools (e.g. in Corel Draw)? Not quite. Perspective distortion of an arbitrary path is something we very definitely need; extrude is also nice, especially for text headings. But they are both effects that, most often, just add a 3D eyecandy to existing objects. What I envision is a tool for a draftsman, a technical illustrator; something that lets you draw entire scenes in one common perspective easily. The main point of my proposal is, let's do the fundamentals right, before we do any eyecandy. And in the world of 3D, a basic 3D box is as fundamental as you can get. Everything else stems from it or can be defined by it; this tool can be used as a generic "definer" of the perspective. For example, you can:
- take one 3D box, copy its perspective, and paste on other boxes;
- project a path onto a side of the box ("perspective envelope");
- apply the box's perspective and bounds to any object to extrude it;
- tell it to inscribe other 3D primitives (cylinder, cone, pyramid) into a box;
- do "perspective clone tiling": cloning an object to each cell of a 3D grid defined by a box;
- even enable ellipse and other drawing tools to draw in one plane of the currently selected box's perspective.
This is a big and infinitely expandable area. We do not expect any single student to cover all of this in a single summer. You can propose a reasonably useful subset of this functionality as your 2007 GSoC project.
Mentor: Bulia Byak
Live Path Effects
As explained on this wiki page, Live Path Effects allow arbitrary path-changing effects to be applied to any path object..
To complete this project, a student must implement at least several simple effects, propose and create a basic user interface for applying them to paths (Path Effects tool?). Some of the effects that you could start with are:
- Patterned or "skeletal" strokes: Similar to the "Pattern along path" extension in 0.45, but fully interactive and auto-updating. You can edit the "skeleton" path and the pattern applied to it at any time.
- Filleting (corner rounding) is common in technical drawing. While this is a fairly basic drafting task, it's currently not particularly easy to do in Inkscape except for certain cases such as round cornered rectangles. This effect would apply rounding with a given radius to all or some sharp corners of a path. It should also permit creation of chamfers which are flattened edges at suitable angles.
- Fractalize is currently a Python effect but would make a great live path effect. It can be useful in mapmaking; maps involve lots of irregular shapes - coastlines, forest boundaries, rivers, etc. that could use fractalization with adjustable level. (As an added bonus, this could be implemented so that the level of fractalization depends on zoom, but preserving this behavior outside of Inkscape would require some smart scripting as explained in this paper: Adaptive Level of Detail in SVG.)
Mentor: Aaron Spike.
Requests in tracker:
- Perspective Grid: 2 and 3 point with sample Perl script.
- Perspective Grid: 1, 2, and 3 point.
- Hex Grid.
- Isometric Grid.
- Isometric Grid.
Mentor: TBD
Text Tool Improvements
Inkscape's text tool is handy, but still lacks many of the niceties that users would like. This project would seek to address this by implementing various improvements that users have requested.
Some ideas for improvements:
-.
- Support text-decoration (underline, overline, line-through)
- Better respect different faces of fonts (Light, Book, Normal, Black etc.)
- Support justified text - might be some subset of those proposed at; see also as a possible starting point.
- Paragraph styling - space before & after paragraphs, indent left & right.
- Spellchecking. Inkscape includes limited spellchecking support based on aspell but it is not enabled by default. Spellchecking based on enchant could use a much wider range of spellchecking engines and be made more widely available and be good enough to show prominently and enable by default.
- Search through the Inkscape Request for Enhancement (RFE) list for other text and font improvement ideas.
See also:
Mentor: TBD.
Note: in 0.45, we have a set of extension effects that do this. But they are clumsy and slow. We need this to be in the core of the program with a good interactive user interface.
Mentor: Bulia Byak
Import/export
Native Import of Encapsulated Poscript (EPS) or Adobe Portable Document Format (PDF)
While SVG is becoming a common format for exchanging data between graphics programs, EPS and PDF are still much more common. Inkscape's current EPS import is brittle, not as well maitained as we might like, and not available for all target platforms as it depends on 3rd party software. The goal is to give Inkscape native EPS or PDF import capability.
Where the code can be borrowed from:
- For EPS: Scribus' EPS Import Library
- For PDF: Poppler library
- For both: Ghostscript (though it may be too heavy for us)
The student needs to evaluate these (or other) possibilities, lay out a plan, and implement a native importer in Inkscape, either using an external lib to link to, or just importing the necessary code directly into Inkscape tree (as we did for Potrace). The end result will be Inkscape being able to correctly import a reasonable majority of EPS or PDF files in the wild (we can agree on a more formal conformance test if this idea interests anyone).
Mentor: ???
Native Import/Export of Corel Draw (CDR) files
Corel Draw was and still is a very popular drawing application and many files exist in the Corel Draw format. The user interface of Corel Draw is more similar in many ways to Inkscape than other graphics software making Inkscape more attractive to Corel Draw artists. We are getting a lot of requests from users to support this format.
While CDR is not an open format, several open source implementations exist, from which you can borrow code:
- sK1 is a Corel Draw lookalike vector editor, at early stages of development but claiming to be able to read CDR files.
- CDR files use RIFF metaformat, which means you can easily find an open source library for reading the top layer of the format (try any open source app that can read WAV or AVI, which are also RIFF-based).
A student for this project will need to plan the scope of the feature (we do not need to do all the fancy features, but basics need to be covered) and assemble, with the help of the mentor, a library of sample CDR files for testing.
Mentor: Bulia Byak
ccHost Import/Export
Allow exporting to, or importing from, a remote ccHost instance.
In particular, export to the OpenClipArtLibrary, and import from said library (with some search terms, tag words, and perhaps even browsing.)
LionKimbro can help someone spec out the capabilities, interfaces (both programmatic and GUI), and so on. He's written a little on OpenClipArtLibraryIntegration already. cell: 206.427.2545.
SVG features
SVG Font support
We need SVG Font support in order to be able to claim SVG Tiny support. While the occurrence of SVG fonts in the wild seems to be pretty low, we will benefit from this by being able to embed fonts and thus ensure rendering of text without converting it to paths.
Mentor: ???
External Cascading Stylesheet (CSS) Support
Inkscape currently has good support for inline CSS, and limited read-only support for an internal stylesheet in a <style> element, and no support for external stylesheets. Support for editing non-inline CSS would allow better expressiveness and adaptation, and smaller SVG files, and better support for SVG generated by other programs that use non-inline CSS.
Mentor: Peter Moulder
Multi-page Support
An often requested feature is for Inkscape to support multi-page editing. Currently, an Inkscape document is set to correspond to 1 printed page. However, the next version of SVG specification (1.2) includes support for multi-page documents, and lots of people would like to have this capability in Inkscape as well.
This project would involve several steps: 1) Add internal support for reading and writing SVG 1.2 <pageSet> and <page> elements. 2) When editing a pageSet, create the visual page frames for each <page>. 3) When exporting to Postscript, have it export each <page> as a separate page in the Postscript file.
(Another frequent request is support for a tabbed interface. To be clear a tabbed interface is quite a different request from this one and any such Tabbed interface would need to accomodate the requirement of single documents with multiple pages like those proposed in SVG and already existing in PDF, OpenDocument Draw, and many others.)
User Interface for SVG Filters
Filters are a very important SVG capability.
Inkscape has basic support for filters in general thanks to a couple GSoC students' work last year, and more or less complete support for Gaussian Blur. What is needed: (1) adding support for more filters and making sure they work well in combination; (2) designing a UI that will be able to create, view, and modify arbitrarily complex filter stacks.
Mentor: Bulia Byak
Raster Graphics
Inkscape / GIMP raster graphics and/or GeGL. Note that the code should be developed such that in theory it should work with any bitmap editor, but we would only require demonstration of working with GIMP.
Also see:
Mentor: TBD
Adding raster.
There are various requests in the tracker on this topic but they are difficult to identify since a mix of terminology is used, such as bitmap, raster, pixel and other graphics terms. Ask the developers on the mailing lists if in doubt. Gould
Your own original ideas
Original ideas are also welcome but students stand a better chance of getting selected by choosing from the suggested projects and where a mentor is available to supervise the work. If in doubt contact the developers on the mailing lists.
Past Years
- Googles Summer of Code 2006
- Googles Summer of Code 2005 | https://wiki.inkscape.org/wiki/index.php?title=Google_Summer_of_Code_2007&oldid=13991 | CC-MAIN-2020-34 | refinedweb | 2,595 | 58.52 |
I attended Joshua Davis’ Hype Workshop last month at the RMI space in Toronto.
I had a hard time figuring applicability in my daily work life.
So I sat on Hype, undecided what I could do with it. What I missed in Josh’s workshop was the fact that Hype is simply a collection of classes. Use what you want and ignore what you don’t. Hopefully, I’m not the only one with that misconception. If I am, I’m dumber than I thought.
Yesterday I had some downtime as I wait on my friend to get to .NET changes for TattooCapture and decided to manufacture something I’ve always wanted: A class to plot points equally around 360°. Why? Well… that will become clear in the future. In the meantime, that was my goal. Feed it 8 points and it comes back with how many degrees each would be to be equally dispersed around a circle.
It was a pretty simple solution; divide the number of elements by 360. Tada! Then use that degree number within the class to return what degree an element would be. Further, use it to return what radian (what flash uses to calculate degrees) that element would be.
I ended up with the Orbit class right-click and ‘save as’. Usage boils down to importing the class and an instantiation. Then using it’s public functions. Therefore;
import com.orbit.Orbit;
var orbit:Orbit = new Orbit;
orbit.increment = 15; //15 being the total number of elements
var degree:Number = orbit.getDegree(8); //8 being the 8th element
var radian:Number = orbit.getRadians(degree);
//returns the radian value for the 8th element out of 15;
//alternatively, you can piggyback the calculations
var radian:Number = orbit.getRadians(orbit.getDegree(8));
So yeah.
Here’s the first example. Each time you click the start button, the piece will pick a random number of elements, then run through that number and each element on stage in it’s prescribed location. Sweet.
So once I figured that out, I started monkeying around with it, as is my wont. Change the number to see the progress.
In comes Hype.
Eventually, in version 4, I decided to muck about a bit with Hype. I wanted to draw to Bitmap was being done and with Hype, I had a built-in class to do just that. BitmapCanvas. Worked like a charm.
Messed around for another couple of versions and in version 8, added in FilterRhythm and TimeType. So far so good.
In version 10, I added in colorPool. Honestly, it all starts to get a bit silly and really I’m just messing around with minor alterations.
In version 13, I dumped my Event.ENTER_FRAME for SimpleRhythm.
Finally, with some more tweaks, I have this (basically) where I want it. Version 19. I might spend some more time with it, but it’s in a place I like. I left it running while I wrote this post and this is what I got.
click the image to see it full-size
The moral of the story is; If you keep your eyes closed, you won’t see the path in front of you. How’s that for a fortune cookie? I oughta be a writer. | http://blog.wheniwas19.com/?cat=43&paged=2 | CC-MAIN-2014-15 | refinedweb | 544 | 76.52 |
:
1 + sin(3)
1.1411200080598671
500x500 Float64 Array: 162.603 127.476 125.076 118.914 … 121.913 119.346 123.416 118.659 127.476 173.211 132.191 125.419 131.765 126.816 131.182 126.373 125.076 132.191 165.643 122.073 123.358 119.285 127.365 127.132 118.914 125.419 122.073 161.962 124.197 116.947 125.176 119.248 119.912 127.888 125.779 119.243 124.572 120.879 124.785 123.494 113.774 118.241 121.404 118.418 … 121.256 118.652 120.242 117.505 125.258 128.183 125.683 123.607 122.044 120.701 127.675 123.064 123.856 128.797 127.62 126.731 125.854 121.413 130.059 129.455 119.448 123.88 122.982 117.524 119.345 119.598 121.751 120.35 121.084 132.255 125.685 126.087 125.765 122.052 134.187 124.131 ⋮ ⋱ 122.913 126.649 124.402 122.839 … 128.841 119.598 131.985 119.851 119.279 120.223 119.79 118.196 121.333 116.689 121.644 117.713 115.047 121.647 119.567 119.708 120.483 116.044 124.468 116.12 118.465 127.593 120.366 116.033 116.425 115.412 123.313 120.278 121.567 127.576 123.69 118.96 119.438 116.865 125.093 116.793 122.765 127.004 123.946 119.973 … 122.286 121.177 126.788 124.31 121.913 131.765 123.358 124.197 168.014 122.242 128.991 122.263 119.346 126.816 119.285 116.947 122.242 161.424 123.398 119.624 123.416 131.182 127.365 125.176 128.991 123.398 173.575 128.892 118.659 126.373 127.132 119.248 122.263 119.624 128.892 161.5");
We can define functions, of course, and use them in later input cells:
f(x) = x + 1
# methods for generic function f f(x) at In[6]:1
println(f(3)) f([1,1,2,3,5,8])
Hello from C!! 4
6-element Int64 Array:?")
no method +(ASCIIString,Int64) at In[8]:1 in f at In[6]")
PyObject <matplotlib.text.Text object at 0x1190c7b50>
Notice that, by default, the plots are displayed inline (just as for the
%pylab inline "magic" in IPython). This kind of multimedia display can be enabled for any Julia object, as explained in the next section.
Like most programming languages, Julia has a built-in
print(x) function for outputting an object
x as text, and you can override the resulting text representation of a user-defined type by overloading Julia's
show function. The next version of Julia, however, will extend this to a more general mechanism to display arbitrary multimedia representations of objects, as defined by standard MIME types. More specifically, the Julia multimedia I/O API provides:
display(x)function requests the richest available multimedia display of a Julia object x (with a
text/plainfallback).
writemimeallows one to indicate arbitrary multimedia representations (keyed by standard MIME types) of user-defined types.
Displaytype. IJulia provides one such backend which, thanks to the IPython notebook, is capable of displaying HTML, LaTeX, SVG, PNG, and JPEG media formats.
The last two points are critical, because they separate multimedia export (which is defined by functions associated with the originating Julia data) from multimedia display (defined by backends which know nothing about the source of the data).
Precisely these mechanism were used to create the inline PyPlot plots above. To start with, the simplest thing is to provide the MIME type of the data when you call
display, which allows you to pass "raw" data in the corresponding format:
display("text/html", """Hello <b>world</b> in <font color="red">HTML</font>!""")
However, it will be more common to attach this information to types, so that they display correctly automatically. For example, let's define a simple
HTML type in Julia that contains a string and automatically displays as HTML (given an HTML-capable backend such as IJulia):
type HTML s::String end import Base.writemime writemime(io::IO, ::@MIME("text/html"), x::HTML) = print(io, x.s)
# methods for generic function writemime writemime(io,::MIME{:text/plain},x) at multimedia.jl:31 writemime(io,m::String,x) at multimedia.jl:37 writemime(io::IO,m::MIME{:image/eps},f::PyPlotFigure) at /Users/stevenj/.julia/PyPlot/src/PyPlot.jl:67 writemime(io::IO,m::MIME{:application/pdf},f::PyPlotFigure) at /Users/stevenj/.julia/PyPlot/src/PyPlot.jl:67 writemime(io::IO,m::MIME{:image/png},f::PyPlotFigure) at /Users/stevenj/.julia/PyPlot/src/PyPlot.jl:67 ... 4 methods not shown (use methods(writemime) to see them all)
Here,
writemime is just a function that writes
x in the corresponding format (
text/html) to the I/O stream
io. The
@MIME is a bit of magic to allow Julia's multiple dispatch to automatically select the correct
writemime function for a given MIME type (here
"text/html") and object type (here
HTML). We also needed an
import statement in order to add new methods to an existing function from another module.
This
writemime definition is all that we need to make any object of type
HTML display automatically as HTML text in IJulia:
x = HTML("<ul> <li> Hello from a bulleted list! </ul>")
display(x) println(x)
HTML("<ul> <li> Hello from a bulleted list! </ul>")
Once this functionality becomes available in a Julia release, we expect that many Julia modules will provide rich representations of their objects for display in IJulia, and moreover that other backends will appear. Not only can other backends (such as Tim Holy's ImageView package) provide more full-featured display of images etcetera than IJulia's inline graphics, but they can also add support for displaying MIME types not handled by the IPython notebook (such as video or audio). | http://nbviewer.jupyter.org/url/jdj.mit.edu/~stevenj/IJulia%20Preview.ipynb | CC-MAIN-2018-39 | refinedweb | 1,006 | 55.27 |
Build and run a simple hello world program
Hi,
I'm trying to build a simple hello world program and trying to run it on qemu simulator for cortex-m4. i'm able to build successfully but not able to run. I think i'm missing something or doing it wrongly.
Can someone please provide me steps to build and run a simple hello world program on qemu for cortex-m4?
Thanks,
Vikram
Question information
- Language:
- English Edit question
- Status:
- Solved
- Assignee:
- No assignee Edit question
- Solved by:
- Jiangning Liu
- Solved:
- 2012-03-31
- Last query:
- 2012-03-31
- Last reply:
- 2012-03-30
Hi Jiangning,
Thanks a lot... It works.. Actually i was not using appropriate options. This is the 1st time i'm trying all these.. i did not work on cortex-m3 already.
Thanks once again..
Regards,
Vikram
Sorry to continue same thread...
Is it possible to change default memory map in above application (custom .text, .data etc.)? I am using codesourcery toolchain and it provides generic linker scripts (like generic-m-hosted.ld etc) which can be modified as per memory map of specific target device. It is really helpful to get semihosted application running on actual target device in early bringup phase.
[ref: http://
Thanks,
Mahavir
Hi Mahavir,
I am not linker script expert. In the readme.tex of our tool chain, there is a section which introduces an example linker scripts. Maybe it is helpful.
BR,
Terry
Sorry for the typo. It is readme.txt in which you also can find a URL. Here is its short cut http://
Hi Terry,
Thanks for your reply. I will take a look.
Thanks,
Mahavir
Vikram,
Did you work on cortex-m3 already? I'm not sure your question is cortex-m4 specific or you only want to know how to build helloworld to run it on qemu.
Anyway, refer to screen copy&paste for cortex-m3 as below. I didn't try cortex-m4 yet, but I guess it wouldn't be different.
$ cat helloworld.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
fprintf (stdout, "Hello World!\n");
return 0;
}
$ arm-none-eabi-gcc -Wl,-Map=output.map -mcpu=cortex-m3 -mthumb -specs=rdimon.specs -lrdimon -lc -lrdimon helloworld.c
$ qemu-system-arm -cpu cortex-m3 -nographic -serial null -monitor null -semihosting -kernel ./a.out
Hello World!
$
Thanks,
-Jiangning | https://answers.launchpad.net/gcc-arm-embedded/+question/192118 | CC-MAIN-2015-40 | refinedweb | 398 | 69.68 |
Python 3 program to test if a number is positive or negative :
In this tutorial, we will learn how to test if a number is positive or negative. We will also check if the number is zero. This is a beginner-friendly python tutorial. With this example, you will learn how to read a user input, how to put your code in a different method to organize it, and how to use an_ if, else-if, else _condition. The program will take the number as input from the user, it will check if it is zero, greater than zero or less than zero and print out the result to the user. You can also store the number in a variable and check its value. But in this program, we are reading the number as an input from the user.
Algorithm :
The algorithm of the program is like below :
- Take the number as an input from the user. You can create one separate variable to hold the number or you can directly test the number. In this example, we are using one separate variable to hold it.
- Check the number using one_ if-elseif-else_ condition. This condition will compare the number two times. The first one will check if it is equal to zero or not, the second one will check if it is greater than zero or not.
If both of these conditions fail, we will print that the number is less than zero or it is a negative number.
Example Program :
def check_number(n): if n == 0: print ("Zero") elif n > 0: print (n,"is greater than zero") else : print (n,"is less than zero") user_no = int(input("Enter a number : ")) check_number(user_no)
You can also download this program from here.
Explanation :
- check_number is a method to check if the number is zero, greater than zero or less than zero. This method takes one number as its argument. It doesn’t return anything.
- Inside the method, we are using one if-elif-else condition. This condition will test the number and print out the result accordingly.
- First, it will move inside the ‘if’ block. This block is used to check if the number is equal to zero or not. If the number is equal to zero, it will print one message “Zero” on the console and exit the if-elif-else block.
- If the ‘if’ block fails, it will move into the ‘elif’ block. ‘elif’ is checking if the number is greater than zero or not. If it is greater than zero or if it is a positive number, it will print one message on the console and exit from the if-elif-else block.
- If the ‘elif’ block fails, it will move to the last block. This is the ‘else’ block. Note that we are not verifying anything in this block. This block will run if the number is not equal to zero and if it is not greater than zero or this block will run only if the number is less than zero or if it is a negative number. We are sure about that. So, without checking any condition, just print to the user that the number is less than zero.
- For reading the user input, the input() method is used. This method returns the value in string form. We are wrapping it with int() to get the integer value of the user input.
Sample Outputs : | https://www.codevscolor.com/python-3-program-check-number-positive-negative-zero/ | CC-MAIN-2020-29 | refinedweb | 571 | 72.36 |
So, just for the fun of it, I refactored the function to get rid of the extra variable.
Here is the original code, as you can find it on the python.org tutorial page:
def fib2(n): result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return resultYou see the point. It is nice to initialize and modify a and b in the same line, since they are so strictly connected. However, just a single buffer integer is required, since we can refer to the list we are going to return. Well, at least if we can assume that the user won't pass as parameter a value less than one.
def fibonacci(n): result = [0] candidate = 1 while candidate < n: result.append(candidate) candidate += result[-2] return resultIn comparison with the original function, my version loose the example of comma-assignment functionality. However I use the increase-assign (+=) operator and the negative index support on list. I would say it is a tie. | http://thisthread.blogspot.com/2017/01/a-python-function.html | CC-MAIN-2018-43 | refinedweb | 171 | 65.22 |
Qt: Set size of QMainWindow
I'm new to Qt, so I wonder whether there is a way to set the size of a QMainWindow to (for example) 70% of the user's desktop.I tried the stretch factor but it didn't work. QWidget::setFixedSize worked but only with a pixel number, I think.
Answers
Thanks to Amir eas. The problem is solved. Here's the code for it:
#include <QDesktopWidget> #include <QMainWindow> ... QDesktopWidget dw; MainWindow w; ... int x=dw.width()*0.7; int y=dw.height()*0.7; w.setFixedSize(x,y);
Somewhere in your QMainWindow constructor, do this:
resize(QDesktopWidget().availableGeometry(this).size() * 0.7);
This will resize the window to 70% of the available screen space.
You can use the availableGeometry(QWidget*) method in QDesktopWidget, this will give you the geometry of the screen that this widget is currently on. For example:
QRect screenSize = desktop.availableGeometry(this); this->setFixedSize(QSize(screenSize.width * 0.7f, screenSize.height * 0.7f));
Where this is the MainWindow pointer. This will work when using multiple screens.
Need Your Help
Getting the current active UIWindow/appDelegate object without holding the apps objects
Visual Studio not finding my Azure subscriptions
visual-studio setup-deployment azure-worker-rolesI have a working Azure account with various services already running. I receive monthly bills for these. | http://www.brokencontrollers.com/faq/22370578.shtml | CC-MAIN-2019-51 | refinedweb | 220 | 51.44 |
This can be done using the following methods in Python.
#1:if(strict=True) in a
try block:
try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: # doesn't exist else: # exists
Answer #2:
You have the
os.path.exists function:
import os.path os.path.exists(file_path)
This returns
True for both files and directories but you can instead use
os.path.isfile(file_path)
to test if it’s a file specifically. It follows symlinks.
Answer #3:
Unlike
isfile(),
exists() will return
True for directories. So depending on if you want only plain files or also directories, you’ll use
isfile() or
exists(). Here is some simple REPL output:
>>> os.path.isfile("/etc/password.txt") True >>> os.path.isfile("/etc") False >>> os.path.isfile("/does/not/exist") False >>> os.path.exists("/etc/password.txt") True >>> os.path.exists("/etc") True >>> os.path.exists("/does/not/exist") False
Answer #4:
import os if os.path.isfile(filepath): print("File exists")
How to check whether a file exists in Python? Answer #5:
Use
os.path.isfile() with
os.access():
import os PATH = './file.txt' if os.path.isfile(PATH) and os.access(PATH, os.R_OK): print("File exists and is readable") else: print("Either the file is missing or not readable")
Answer #6:
import os os.path.exists(path) # Returns whether the path (directory or file) exists or not os.path.isfile(path) # Returns whether the file exists or not
Answer #7:
Python 3.4+ has an object-oriented path module: pathlib. Using this new module, you can check whether a file exists like this:
import pathlib p = pathlib.Path('path/to/file') if p.is_file(): # or p.is_dir() to see if it is a directory # do stuff
You can (and usually should) still use a
try/except block when opening files:
try: with p.open() as f: # do awesome stuff except OSError: print('Well darn.')
The pathlib module has lots of cool stuff in it: convenient globbing, checking file’s owner, easier path joining, etc. It’s worth checking out. If you’re on an older Python (version 2.6 or later), you can still install pathlib with pip:
# installs pathlib2 on older Python versions # the original third-party module, pathlib, is no longer maintained. pip install pathlib2
Then import it as follows:
# Older Python versions import pathlib2 as pathlib
Answer #8:
This is the simplest way to check if a file exists. Just because the file existed when you checked doesn’t guarantee that it will be there when you need to open it.
import os fname = "foo.txt" if os.path.isfile(fname): print("file does exist at this time") else: print("no such file exists at this time")
Answer #9:
How do I check whether a file exists, using Python, without using a try statement?
Now available since Python 3.4, import and instantiate a
Path object with the file name, and check the
is_file method (note that this returns True for symlinks pointing to regular files as well):
>>> from pathlib import Path >>> Path('/').is_file() False >>> Path('/initrd.img').is_file() True >>> Path('/doesnotexist').is_file() False
If you’re on Python 2, you can backport the pathlib module from pypi,
pathlib2, or otherwise check
isfile from the
os.path module:
>>> import os >>> os.path.isfile('/') False >>> os.path.isfile('/initrd.img') True >>> os.path.isfile('/doesnotexist') False
Now the above is probably the best pragmatic direct answer here, but there’s the possibility of a race condition (depending on what you’re trying to accomplish), and the fact that the underlying implementation uses a
try, but Python uses
try everywhere in its implementation.
Because Python uses
try everywhere, there’s really no reason to avoid an implementation that uses it.
But the rest of this answer attempts to consider these caveats.
Longer, much more pedantic answer
Available since Python 3.4, use the new
Path object in
pathlib. Note that
.exists is not quite right, because directories are not files (except in the unix sense that everything is a file).
>>> from pathlib import Path >>> root = Path('/') >>> root.exists() True
So we need to use
is_file:
>>> root.is_file() False
Here’s the help on
is_file:
is_file(self) Whether this path is a regular file (also True for symlinks pointing to regular files).
So let’s get a file that we know is a file:
>>> import tempfile >>> file = tempfile.NamedTemporaryFile() >>> filepathobj = Path(file.name) >>> filepathobj.is_file() True >>> filepathobj.exists() True
By default,
NamedTemporaryFile deletes the file when closed (and will automatically close when no more references exist to it).
>>> del file >>> filepathobj.exists() False >>> filepathobj.is_file() False
If you dig into the implementation, though, you’ll see that
is_file uses
try:
def is_file(self): """ Whether this path is a regular file (also True for symlinks pointing to regular files). """ try: return S_ISREG(self.stat().st_mode) except OSError as e: if e.errno not in (ENOENT, ENOTDIR): raise # Path doesn't exist or is a broken symlink # (see return False
Race Conditions: Why we like try
We like
try because it avoids race conditions. With
try, you simply attempt to read your file, expecting it to be there, and if not, you catch the exception and perform whatever fallback behavior makes sense.
If you want to check that a file exists before you attempt to read it, and you might be deleting it and then you might be using multiple threads or processes, or another program knows about that file and could delete it – you risk the chance of a race condition if you check it exists, because you are then racing to open it before its condition (its existence) changes.
Race conditions are very hard to debug because there’s a very small window in which they can cause your program to fail.
But if this is your motivation, you can get the value of a
try statement by using the
suppress context manager.
Avoiding race conditions without a try statement:
suppress
Python 3.4 gives us the
suppress context manager (previously the
ignore context manager), which does semantically exactly the same thing in fewer lines, while also (at least superficially) meeting the original ask to avoid a
try statement:
from contextlib import suppress from pathlib import Path
Usage:
>>> with suppress(OSError), Path('doesnotexist').open() as f: ... for line in f: ... print(line) ... >>> >>> with suppress(OSError): ... Path('doesnotexist').unlink() ... >>>
For earlier Pythons, you could roll your own
suppress, but without a
try will be more verbose than with. I do believe this actually is the only answer that doesn’t use
try at any level in the Python that can be applied to prior to Python 3.4 because it uses a context manager instead:
class suppress(object): def __init__(self, *exceptions): self.exceptions = exceptions def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if exc_type is not None: return issubclass(exc_type, self.exceptions)
Perhaps easier with a try:
from contextlib import contextmanager @contextmanager def suppress(*exceptions): try: yield except exceptions: pass
Other options that don’t meet the ask for “without try”:
isfile
import os os.path.isfile(path)
os.path.isfile(path)
Return True if path is an existing regular file. This follows symbolic links, so both
islink()and
isfile()can be true for the same path.
But if you examine the source of this function, you’ll see it actually does use a try statement:
# This follows symbolic links, so both islink() and isdir() can be true # for the same path on systems that support symlinks def isfile(path): """Test whether a path is a regular file""" try: st = os.stat(path) except os.error: return False return stat.S_ISREG(st.st_mode)
>>> OSError is os.error True
All it’s doing is using the given path to see if it can get stats on it, catching
OSError and then checking if it’s a file if it didn’t raise the exception.
If you intend to do something with the file, I would suggest directly attempting it with a try-except to avoid a race condition:
try: with open(path) as f: f.read() except OSError: pass
os.access
Available for Unix and Windows is
os.access, but to use you must pass flags, and it does not differentiate between files and directories. This is more used to test if the real invoking user has access in an elevated privilege environment:
import os os.access(path, os.F_OK)
It also suffers from the same race condition problems as
isfile. From the docs:
Note: Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:
if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read() return "some default data"
is better written as:
try: fp = open("myfile") except IOError as e: if e.errno == errno.EACCES: return "some default data" # Not a permission error. raise else: with fp: return fp.read()
Avoid using
os.access. It is a low level function that has more opportunities for user error than the higher level objects and functions discussed above.
Criticism of another answer:
Another answer says this about
os.access:
Personally, I prefer this one because under the hood, it calls native APIs (via “${PYTHON_SRC_DIR}/Modules/posixmodule.c”), but it also opens a gate for possible user errors, and it’s not as Pythonic as other variants:
This answer says it prefers a non-Pythonic, error-prone method, with no justification. It seems to encourage users to use low-level APIs without understanding them.
It also creates a context manager which, by unconditionally returning
True, allows all Exceptions (including
KeyboardInterrupt and
SystemExit!) to pass silently, which is a good way to hide bugs.
This seems to encourage users to adopt poor practices.
Answer #10:
import os #Your path here e.g. "C:\Program Files\text.txt" #For access purposes: "C:\\Program Files\\text.txt" if os.path.exists("C:\..."): print "File found!" else: print "File not found!"
Importing
os makes it easier to navigate and perform standard actions with your operating system.
Answer #11:
Testing for files and folders with
os.path.isfile(),
os.path.isdir() and
os.path.exists()
Assuming that the “path” is a valid path, this table shows what is returned by each function for files and folders:
You can also test if a file is a certain type of file using
os.path.splitext() to get the extension (if you don’t already know it)
>>> import os >>>>> os.path.isfile(path) True >>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx True
Hope you learned something from this post.
Follow Programming Articles for more! | https://programming-articles.com/how-to-check-if-a-file-exists-without-exceptions-in-python-answered/ | CC-MAIN-2022-40 | refinedweb | 1,807 | 58.48 |
Yes. I miss that very much
Edit:
Umm, I cant even trigger paragraph, p->tab gives me (v2032)
Jon, I cannot get what you wrote to work.
I created a Headers (C).sublime-completions with (shortened) the following contents:
{
is included I want fclose() to be available in autocompletion, but if #include is not present, I don't want to offer the possibility.
I think a plugin could be what you want here. Using Jon's example plugin as a starting point:
import sublime
import sublime_plugin
class C_Completions(sublime_plugin.EventListener):
all_completions = {"string.h":
("sl", "strlen($1)"),
],
"stdio.h":
("pf", "printf($1)"),
]}
def on_query_completions(self, view, prefix, locations):
if not view.match_selector(locations[0], "source.c"):
return ]
filenames = ]
regions = view.find_all(r"#include +\"<](.+)\">]", 0, "$1", filenames)
completions = ]
for f,r in zip(filenames, regions):
if (f in self.all_completions and
view.syntax_name(r.begin()).strip().endswith("preprocessor.c.include source.c")):
completions += self.all_completions[f]
return completions
Is there a way to get the scope name in a plugin
I tried
view.run_command('show_scope_name')
and theres view.scope_name() but I can't tell what args it takes or even if it does what i need (grab the the file source type eg: source.css.less) so i can check against it.
We really really need some api docs for ST2.
I believe view.syntax_name and view.scope_name are identical. They both take a text_point as an argument and return a string containing the name of the scope at the text point.If a function exists in both ST1 and ST2, it tends to take the same arguments and have the same effect, so the API docs for ST1 are actually pretty helpful.
adzenith thanks for the quick reply.
this seems to work
view.scope_name(view.text_point(0,0)).split(' ')-2]
view.text_point(0,0) will always just be 0, I believe.You can also call view.settings().get("syntax") in order to figure out which syntax file is being used.
I don't understand... "will always just be 0"Sorry.
Are you talking about the return value?I'm getting as the return value fwiw punctuation.definition...
view.text_point() returns a a text_point, which is really just an integer index of the indicated character in the buffer. Because the character at row 0, col 0 is always the character at buffer index 0, view.text_point(0,0) will always return 0.Let me know if I'm not making any sense.
Oh I understand now.So,
view.scope_name(0)
would work just the same.
Thanks again. | https://forum.sublimetext.com/t/dev-build-2030/1329/45 | CC-MAIN-2016-36 | refinedweb | 425 | 61.93 |
This is the ‘Python Functions’ tutorial offered by Simplilearn. This tutorial is part of the 'Data Science with Python course' and we will get detailed information on various Python Functions.
After completing this Python functions tutorial you'll be able to
A function is a block of organized, reasonable code used to perform a single and related action. The important benefits of functions are:
As we already know, Python gives us many built-in functions like print, but we can also create our own functions. These functions are called user-defined functions. To put it more formally, a function can be defined as a named sequence of statements that performs a computation. When we define a function, we specify the name and sequence of statements and later we can call the function by the given name. Let us look at the example below to understand how to call a function.
>>>type(10)
<type ‘int’>
This is an inbuilt function defined in the python library.
To understand how to create our own functions by using the Python programming language and how to use them later, refer to the syntax below
def func_name (arguments): statements
Arguments are optional. A function can have and cannot have arguments, and they can be in multiple numbers. Let us look at the example of a simple function below.
def hello_func():
Print “Hello from hello_func”
A simple function has been created with the name hello_func. No parameter has been passed to this function. Once this function is called, it will print “Hello from the given name”.
Defining a Python function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of a code. Once the basic structure of a function is finalized, we can execute it by calling it from
To call a function, we just need to type the name of that function, followed by round brackets. In the given example, the function: >>>hello_func(), will print the message ‘Hello’. If we have any list of arguments, it will be passed inside the brackets. The sequence of arguments passed while calling a function should be the same as it is in the function's definition. A function should be created before it's used in the program.
Look at the other elements of the Python Basic course here. Click to know more!
There can be situations when we want to pass some information to a function. We can pass arguments to the function and use the ‘return’ statement. To understand this better let us look at the example below:
def add_numbers(x,y):
return x+y
A Python function has been created, which can add two numbers. If we want the function to send out any two numbers, add those numbers and send the result back to the user, then we would need to mention that the two variables x and y will be passed by the caller of that function. These two variables are shown within curly brackets
Once we add these numbers using the plus operator, we can return the result to the caller of the function by using the keyword ‘return’ as shown in the function definition. The return statement will return that control to the caller, whenever called. If it's not followed by some value, it will still return the control to the caller, but will not return any value.
The return statement followed by some variable or value returns the value to the caller of the function. In case of the add function, we can return the addition of the result to the caller using the return statement. We can also set the default value of a variable in a function definition, by mentioning the variable name to be equal to the default value.
In the given example below:
def add_numbers(x,y=2):
return x+y
y=2 is set as the default value.
In any situation, if the caller calls this function with only one argument, then the default value of Y will be used.
We may need to process a function for more arguments than what we specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition.
An asterisk is placed before the variable name that holds the values of all non-keyword variable arguments. This remains empty if no additional arguments are specified during the function call. We can pass an arbitrary number of key-value pair arguments by using the asterix sign twice.
In the above example, the given keyword allows us to pass the variable-length of arguments to a function. We should use the given keyword if we want to handle the name arguments in a function.
Below is an example code to call this Python function.
Args is a list of unnamed of variables passed by a caller. The given function contains the list of arguments passed by a caller with the name.
Another example below shows how to create and call a function.
In the given example, a function has been created, named add. This function accepts to arguments x and y. In the function definition, x and y are added and have returned the result using the return keyword. We can also call this function, by passing different argument values.
In the above example, the add function has been called with values 1 and 2. This function will return 3 after addition.
Keen on learning more of Python Basics? Click to know more!
It is possible for one function to call another and it is also possible for a function to call itself. This is called Recursion. In literal terms, Recursion means defining something in terms of itself and is a very powerful feature. The given example below can help understand this better.
This demonstration below shows the steps to create a function in python.
Let's summarize the topics covered in this lesson.
With this, we come to the end of the ‘Functions’ tutorial. The next tutorial is ‘Classes.’
A Simplilearn representative will get back to you in one business day. | https://www.simplilearn.com/python-functions-tutorial | CC-MAIN-2020-50 | refinedweb | 1,021 | 63.8 |
Simple lockfree IPC using shared memory and C1104 Jun 2015
I have an interesting Linux application that requires a process with one or more real-time threads to communicate with other processes on the system. The use case is single producer with single consumer per IPC channel.
The real-time requirements of the application (this runs on a kernel with the PREEMPT RT patch set applied) requires that the IPC channel is lock-free and presents minimal overhead. That is, a real-time producer thread or process must be able to quickly write something and keep executing without locking or context switches.
I decided to prototype a simple IPC mechanism while looking at a few techniques like userspace RCU as well. This is very much a work in progress and I am not sure how useful it really is but I am posting it here in case it is interesting or even leads to some discussion.
Shared Memory
There are several ways of implementing IPC in Linux and I chose the simple POSIX shared memory approach to represent IPC “channels”:
- One process (the producer) creates a POSIX shared memory object and sizes it according to the IPC API contract.
- Another process (the consumer) opens this shared memory object.
Both processes use
mmap() to map a window into this shared memory and can now
communicate:
Stack Structure).
I chose a simple stack data structure and based my design on the C11 Lock free Stack written by Chris Wellons. This
does use the C11
stdatomic.h primitives so GCC 4.9 or newer is required to
compile and GCC should be told to be in C11 mode (for example with
-std=c11).
GCC switched to C11 by default in version 5.0 so that is now the default if you
do not specify
-std= otherwise.
This stack maintains two pointers: a
head and
free:
There is a one to one mapping of stack nodes to buffer pool locations (offsets) and, by knowing the starting address of the data structure, we can always calculate a pointer to some offset in the buffer pool.
Machine capabilities and limitations
This approach assumes that the machine in question is capable of compare and
swap (CAS) and most of them (modern ARM, PowerPC, x86, etc) are. The C11
generic function
atomic_compare_exchange_weak will generate suitable CAS instructions.
Machines do vary in the CAS size they support (among other things), that is how many bytes can be atomically compared and swapped. There is a set of Atomic lock-free constants that should be checked to determine what the machine is capable.
Data Structures
The machine I am targeting can CAS four bytes so this can represent a stack “head” pointer:
struct lfs_head { uint16_t inode; /* offset into the node pool */ uint16_t count; /* ABA counter */ };
The “nodes” themselves are nothing more than a next “pointer” which in turn is just a 16-bit value representing another offset into the node pool,
struct lfs_node { uint16_t inext; /* offset into the node pool */ };
An offset value of
0 corresponds to the 0th element so some kind of special
value is needed to describe a “null pointer”, I chose:
#define NULL_INDEX 0xFFFF
since I do not intend to support very deep stacks in this design. An index can
then be checked against
NULL_INDEX just like a check for
NULL.
The stack “descriptor” itself contains a number of elements including the stack
head and free “pointers”. It is set up at initialization and then modified as
needed by
push and
pop;
This descriptor implies that
- The node pool is located at the address of this descriptor plus the size of the descriptor.
- The Nth node is located at the address of the node pool plus the size of a node multiplied by
N
- The buffer pool is located at the address of the node pool plus the size of the node pool (which in turn is the size of a node multiplied by the
depth).
- The Nth buffer is located at the address of the buffer pool plus the size of one buffer,
data_nb, multiplied by
N.
API
The lock-free stack (LFS) itself must be initialized and this in turn needs to know where the descriptor is, the desired stack depth, and how big the buffers in the buffer pool are (the latter is used to calculate data pointers from the internally managed offsets).
void lfs_init(lfs_t *lfs, size_t depth, size_t data_nb);
From there, arbitrary data can be pushed to the stack as long as there are one or more free nodes. The data is copied into the corresponding buffer and the size is known from initialization time.
bool lfs_push(lfs_t *lfs, void *value);
Data can be popped off the stack as well:
void *lfs_pop(lfs_t *lfs);
And the number of nodes on the stack is tracked and available:
size_t lfs_size(lfs_t *lfs);
Implementation
The LFS internally must implement
push and
pop which in turn are called by
the
lfs_push and
lfs_pop routines.
lfs_pop will:
popa node from the stack
pushthat node to the free stack
- adjust the
sizebook keeping
return the buffer pool pointer corresponding to that node); } }
lfs_push will:
pulla node from the free stack
- copy data into the buffer pool location corresponding to that node
pushthat node into the stack
adjust the
sizebook keeping; } }
lfs_size simply loads and returns the
size field contents:
size_t lfs_size(lfs_t *lfs) { return atomic_load(&lfs->size); }
Initialization
The initialization routine sets up the
data_nb and
depth fields that we use
to calculate pointers at run time and also sets initial values for the stack
heads and nodes.
void lfs_init(lfs_t *lfs, size_t depth, size_t data_nb) { lfs->data_nb = data_nb; lfs->depth = depth;
The initial state for the stack head is to point to NULL (empty stack) and we
set the
size accordingly:
lfs->shead.count = ATOMIC_VAR_INIT(0); lfs->shead.inode = ATOMIC_VAR_INIT(NULL_INDEX); lfs->size = ATOMIC_VAR_INIT(0);
Each node in the node pool points to the next node while the last one points to NULL.
struct lfs_node *nodes = get_node_pool(lfs); /* Initialize the node pool like a linked list. */ for (size_t i = 0; i < depth - 1; i++) { nodes[i].inext = i + 1; } nodes[depth - 1].inext = NULL_INDEX; /* last node */
The entire stack is free. The free head therefore points to the 0th node in the node pool:
/* The free pool "points" to the first node in the node pool */ lfs->sfree.inode = ATOMIC_VAR_INIT(0); lfs->sfree.count = ATOMIC_VAR_INIT(0); }
Internal Implementation
The location of the node pool can be calculated at any time by knowing the location of the descriptor and the size of the descriptor:
static struct lfs_node *get_node_pool(lfs_t *lfs) { return (struct lfs_node *)((char *)lfs + sizeof(*lfs)); }
We can calculate the data pointer (into the buffer pool) for a given node by using an offset from the node pool location:
/*; } }
The internal implementation consists of
push and
pop methods that make use
of the stack represented by the LFS descriptor.
Lock-free
push
The lock-free
push:
- load the current head
- build the new head which in turn:
- has an ABA counter that is one greater than that of the original head (this is done to partially solve the ABA problem).
- points (by index) to the node we are pushing onto the stack
set up the new node with a
nextpointer corresponding to the original head)); }
Lock-free
pop
The lock-free
pop implementation also must know the head it is working with
(again so that we can use it for both the normal and free stack) and it in turn
returns the node that is removed, by index. This method must:
- load the current head
- build a new head that:
- has its
nextpointer set to that of the original head
- has its ABA counter set to one greater than that of the original head (again this is to partially solve the ABA problem).
return the removed original head; } | http://yurovsky.github.io/2015/06/04/lockfree-ipc/ | CC-MAIN-2017-26 | refinedweb | 1,311 | 59.87 |
Top Answers to Puppet Interview Questions
1. What is Puppet?
First let us compare Puppet with Ansible:
The Puppet is a configuration management tool that is extensively used for automating the administration tasks. Puppet tool helps you deploy, manage and configure your servers.
2. What is Manifests?
The Manifests are just files in Puppet wherein the client configuration is specified.
CTA
Watch this Puppet Tutorial for Beginners video
3. What is the difference between a Module and a Manifest?
The manifests that we define in modules can be included in the manifests. This makes it easier to manage the manifests. It is possible to push the chosen manifest on to the specific agent or node.
4. What is Facter?
The Facter is a system profiling library which is used to gather system information during a Puppet run. The Facter offers your information regarding the IP address, version of kernel, CPU and others.
5. What is Puppet Kick?
Puppet Kick lets you trigger the Puppet Agent from Puppet Master. During the run interval the Puppet Agent will send a request to Puppet Master.
6. What is MCollective?
The MCollective is a tool that is developed by the Puppet labs for server orchestration. MCollective helps to run thousands of jobs in parallel using your own or existing plugins.
7. is it possible to manage Workstations with Puppet?
You can use the Puppet tool for managing machines which are laptops, desktops and even workstations.
8. Does Puppet run on Windows?
Beginning with Puppet 2.7.6 it is possible to run on Windows and this ensures future compatibility.
9. What type of organizations can use Puppet?
There is no strict rule about the type of organizations that can benefit from Puppet. But an organization with only a few servers is less likely to benefit from Puppet. An organization with huge number of servers can benefit from Puppet as this eliminates the need to manually manage the servers.
10. Can Puppet run on servers that are unique?
Puppet can run on servers that are unique. Even though there might be very less chances of servers being unique since within an organization there are a lot of similarities that exist like the operating system that they are running on, and so on.
11. What is Puppet Labs?
Puppet Labs is the company that is interested in solving the Puppet automation problem.
12. How to upgrade Puppet and Facter?
You can upgrade Puppet and Facter through your operating system package management system. You can do this either through the vendor’s repository or through the Puppet Labs’ public repositories.
13. What are the characters permitted in a class and module name?
The characters that are permitted in a class and module name can be lowercase letters, underscores, numbers. It should being with a lowercase letter, you can use “::” as a namespace separator. The variable names can be including alphanumeric characters and underscore and can be case sensitive.
14. How are the variables like $ operating system set?
You can set the variables by Facter. It is possible to get the complete list of variables and the values if you run the facter in a shell by itself. | https://intellipaat.com/blog/interview-question/puppet-interview-questions-answers/ | CC-MAIN-2020-05 | refinedweb | 530 | 59.3 |
CST 206 Programming Problem 4 pg. 579
Design, implement, and test a class that represents an amount of time in minutes and seconds. The class should provide a constructor that sets the time to a specified number of minutes and seconds(1). The default constructor should create an object for a time of zero minutes and zero seconds(2). The class should provide observers that return the minutes and seconds separately(3), and an observer that returns the total time in seconds(4). Boolean comparison observers should be used that tell whether two times are equal(5), one is greater than the other(6), or one is lesser than the other(7). Transformers should be provided that add one time to another(8) or subtract one time from another(9). The class should not allow negative time (subtraction of more time than is currently stored should result in a time of 0:00)(10).
here's my pseudocode
I believe I have covered all the requirments. Two constructors, two observers, and two transformers??I believe I have covered all the requirments. Two constructors, two observers, and two transformers??Code:
#include <iostream>
using namespace std;
class Time
{
int mins, secs
public:
Time();
Time( int, int, int, int);
};
(1)Time::Time(){
mins=0;
secs=0;
};
(2)Time::Time(int mins, int secs) {
Time1(11, 30)
Time2(12, 14)
Time3(22, 54)
Time4(23, 19)
};
int Return() const // (3??)
//observer that returns the minutes and seconds seperately
Retun min;
Return Secs;
int Total() const //(4)
//observer that retuens the total time as seconds
Get total time
Return total time as seconds
bool Time::Equal( /* in */ Time otherTime ) const (5)
// Postcondition:
// Function value == true, if this time equals otherTime
// == false, otherwise
{
return (hrs == otherTime.hrs && mins == otherTime.mins &&
secs == otherTime.secs);
}
//******************************************************************
bool Time::LessThan( /* in */ Time otherTime ) const (6)
// Precondition:
// This time and otherTime represent times in the
// same day
// Postcondition:
// Function value == true, if this time is earlier
// in the day than otherTime
// == false, otherwise
{
return (hrs < otherTime.hrs ||
hrs == otherTime.hrs && mins < otherTime.mins ||
hrs == otherTime.hrs && mins == otherTime.mins
&& secs < otherTime.secs);
}
void Add Time() (7)
Add the times together
void Subtract() (8)
Subtract two times | https://cboard.cprogramming.com/cplusplus-programming/85203-help-assignment-printable-thread.html | CC-MAIN-2017-51 | refinedweb | 365 | 65.42 |
Odoo Help
This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.
7.0 orm.py raises exeption on write -> split_for_in_conditions has changed !
I installed latest 7 release from github. But were i had no problem with an older codebase of 7, i now ran into an exception raised in orm.py.
When i do a write in my custom module, orm.pay raises
It all comes down to this piece of code in the orm.py. The
cr.rowcount != len(sub_ids)
What could be a reason why the update would give a different rowcount vs the ids i need to update
if len(upd0): self.check_access_rule(cr, user, ids, 'write', context=context) for sub_ids in cr.split_for_in_conditions(ids): cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \ 'where id IN %s', upd1 + [sub_ids]) if cr.rowcount != len(sub_ids): raise except_orm(_('AccessError'), _('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
Debugging some more i found that my ids have doubles in the list of ids
That would explain why the result from cr.rowcount = 997 and i have 1000 ids. the 3 doubles.
This is because split_for_in_conditions in sql_db.py changed between versions
from
def split_for_in_conditions(self, ids):
"""Split a list of identifiers into one or more smaller tuples
safe for IN conditions, after uniquifying them."""
return tools.misc.split_every(self.IN_MAX, set(ids))
to:
def split_for_in_conditions(self, ids):
"""Split a list of identifiers into one or more smaller tuples
safe for IN conditions, after uniquifying them."""
return tools.misc.split_every(self.IN_MAX, ids)
They removed the set() !
But any idea when and why this feature got changed!
And do i need to change my code to handle doubles in a list of ids i want to update?
or is this a bug that odoo is going to fix lowlevel?
[FIX] orm: ordering on >1000 more about your scenario, like something of how to reproduce your bug | https://www.odoo.com/forum/help-1/question/7-0-orm-py-raises-exeption-on-write-split-for-in-conditions-has-changed-94864 | CC-MAIN-2016-50 | refinedweb | 348 | 65.62 |
Octopus Deploy Powershell Module
Get-OctopusVariableSet). Here's a gist of doing it for a variableset object, it's not complete but it will give you the idea: Whilst I could write a bunch of functions to do this, it just struck me that it would be way more efficient to write all the instantiation code in C#... unless I'm missing something and there is already an easier way?
This snippet should work
In your code I can see you are creating some objects from the
Octoposh namespace. You should never do that, as the
Octoposh objects are just translations of the actual
Octopus objects for the human eyes.
If you want to create/update/delete anything in Octopus, you need to use Octopus objects.
-resourceOnly? That tells the cmdlet to return the actual Octopus resource, instead of the
Octoposhobject. Later on I add the variable (again an Octopus object, this time of the type
Octopus.client.model.variableResource) to the Octopus resource, and finally I pass the variable set Octopus object ($variableSet) to
Update-OctopusResource
-resourceOnlyparameter is super importante and a bit obscure atm. I've been trying to write documentation about it for ages but I always forget. I'll try to get it done this week.
Get-OctopusResourceModelcmdlet which will simplify creating my mock objects if I change my script to use
-ResourceOnlythroughout. Many thanks for the pointer.
Get-OctopusResourceModelthat made life easier when using it to create the test data objects I was talking about above... see what you think.
BeginProcessingmethod is something I already did in my refactoring branch :)
As for the addition of
VariableSetResource: In Octopus a
VariableSetResource is a type of object that holds a collection of variables. This
VariableSetResource can belong to 2 other different kinds of objects:
1 - a
ProjectResource
2 - a
LibraryVariableSetResource
A
VariableSetResource object doesn't exist by itself, but only as a child object of these 2. Therefore the only organic way to create a
VariableSetResource must be through the creation of either a
ProjectResource or a
LibraryVariableSet resource.
For that reason in the snippet I gave you in line 10 I'm creating a
LibraryVariableSet, and then in line 13 I'm getting the
VariableSetResource that was associated with the
LibraryVariableSet that I previously created. I'm never directly creating a
VariableSetResource.
I'm afraid that if the module gives users the ability to create orphan an
VariableSetResource , It'll confuse more ppl than it would help. Advanced users such as yourself should be able to work around this by creating a
VariableSetResource using raw powershell like
new-object Octopus.Client.Model.VariableSet
That said, I'm curious of how are you setting up your tests in a way that you need to create an orphan
VariableSetResource like this.
/api/variables) so I don't see it has inherently wrong - presumably the API has consistency checks to ensure that the 'OwnerId' property is valid to avoid actual orphans?.
New-*cmdlets would be an effective way of leading them into the 'pit of success' of only creating the right types objects?.
@ConwayO
New-OctopusAPIKey - I simply didn't port this cmdlet after porting things to C#. I have #259 open for it. I'll do it this week as I've been asked about it quite enough :)
Environment question - Not sure Im following this one. Which cmdlet are you running and what you mean by "skip 10"
calling API directly - Yes you can run
$c = new-Octopusconnection. Then you could do
$c.repository.projects.findall() for example to get all the projects.
$c will be an object that holds an authenticated connection with your Octopus instance. Is this what you needed?
@jigneshjdesai about using
Octo.exe delete-releases, here's do documentation for it:
Remember that you can download
Octo.exe using
Octoposh as explained here:
Hello, I need some help with Get-OctopusDeployment. I am using Octopus 3.4.13 and Octoposh 0.6.11.
I have a project and environment that have 34 deployments listed in the DeploymentHistory table in the database. Get-OctopusDeployment throws this error when I try
PS C:\WINDOWS\system32> Get-OctopusDeployment -ProjectName Myproject -EnvironmentName Myproject_prod
Get-OctopusDeployment : Nullable object must have a value.
At line:1 char:1
Get-OctopusDeployment works fine for other projects with either more or fewer deployments. The project with errors has Successful, Failed and Cancelled deployments. That is also the case with projects that do not have errors. | https://gitter.im/Dalmirog/OctoPosh?at=5a09820286d308b755e0dc96 | CC-MAIN-2020-29 | refinedweb | 743 | 55.24 |
Update: The second edition of the XML Bible has been published. I'm keeping this page here to support readers who bought the first edition, as well as for readers of translations, since most of the translations are still based on the first edition. (A few actually use a manuscript from in-between the first and second editions.)
However, if you want the most current information, you should go to the second edition page or the Gold edition page instead. Both are much improved over the first edition with huge amounts of new and updated material. They're completely up-to-date with the state of the art in XML as of 2001. If you're buying a new copy, you'll want to make sure you get the second edition or the Gold edition. The second edition has a robot on the cover instead of the three-dimensional "XML" you see to the left. The Gold Edition is in hardcover.
The XML Bible is a comprehensive introduction to using XML for Web page design. It shows you how to write XML documents, validate them with DTDs, design CSS and XSL style sheets for those documents, convert them to HTML, and publish them on Web servers for the world to read. You'll also learn how to use XML technologies like RDF, XLinks, XHTML, and namespaces to add structure and organization to your document collections. And finally, you'll learn about the many uses of XML beyond the Web site, including genealogy, subscription services, mathematics, vector graphics, and more. After reading this book I hope you'll agree with me that XML is the most exciting development on the Internet since Java, and that it makes Web site development easier, more productive, and more fun.:
How semantic tagging makes XML documents easier to maintain and develop than their HTML equivalents
How to post XML documents on Web servers in a form everyone can read
How to make sure your XML is well-formed
How to format your documents with CSS and XSL style sheets
How to validate documents with DTDs
How to use entities to build large documents from smaller parts
How attributes describe data
How to connect documents with XLinks and XPointers
In the final section of this book, you'll see several practical examples of XML being used for real-world applications including:
Web Site Design
Push
Vector Graphics
Genealogy
The XML Bible is divided into five parts:
Introducing XML
Document Type Definitions and Validity
Style Languages
Supplemental Technologies
XML Applications
By the time you're finished, you'll be ready to use XML to create compelling Web pages.
Part 1, Introducing XML, elucidates the purpose, structure, and syntax of XML. It begins with the history and theory behind XML, the goals XML is trying to achieve, and shows you how the different pieces of the XML equation fit together to create and deliver documents to readers. You'll see several compelling examples of XML applications to give you some idea of the wide applicability of XML including the Vector Markup Language (VML), the Resource Description Framework (RDF), the Mathematical Markup Language (MathML), the Extensible Forms Description Language (XFDL), and many others. Then you'll learn by example how to write XML documents with tags you define that make sense for your document. You'll see how to edit them in a text editor, attach style sheets to them, and load them into a Web browser like Internet Explorer 5.0 or Mozilla. You'll even learn how you can write XML documents in languages other than English, even languages that aren't written remotely like English such as Chinese, Hebrew, and Russian.
An XML document may optionally contain a document type definition (DTD) that specifies which elements are and are not allowed in an XML document. The DTD specifies the exact context and structure of those elements that are allowed. A validating parser can read a document and compare it to its DTD, and report any mistakes it finds. This allows document authors to check that their work meets any necessary criteria.
In Part II you'll learn how to attach a DTD to a document, how to validate your documents against their DTDs, and how to write your own DTDs that solve your own problems. You'll learnt the syntax for declaring elements, attributes, entities, and notations. You'll see how you can use entity declarations and entity references to build both a document and its DTD from multiple, independent pieces. This allows you to make long, hard-to-follow documents much simpler by separating them into related modules and components. And you'll learn how to integrate other forms of data like raw text and GIF image files in your XML document.
XML markup only specifies what's in a document. Unlike HTML, it does not say anything about what that content should look like. Information about an XML document's appearance when printed, viewed in a Web browser, or otherwise displayed is stored in a style sheet. Indeed, different style sheets can be used for the same document. You might for instance, want to use a style sheet that specifies small fonts for printing, another one that uses larger fonts for on screen use, and a third with absolutely humongous fonts for projecting the document on a wall at a seminar. You can change the appearance of an XML document by choosing a different style sheet without touching the document itself.
Part III describes in detail about the two style sheet languages in broadest use on the Web, Cascading Style Sheets (CSS) and the Extensible Style Language (XSL). CSS is a simple style sheet language originally designed for use with HTML. CSS exists in two versions. CSS Level 1 provides simple information about fonts; color, positioning, and text properties. CSS Level 1 is reasonably well supported by current Web browsers for HTML and XML. CSS Level 2 is a more recent standard that builds on CSS Level 1 by adding support for tables, aural style sheets, international and bi-directional text, user interface styles, and much more. CSS level 2 is only beginning to be supported by current browsers.
CSS is a relatively simple standard that applies fixed style rules to the contents of particular elements. XSL, by contrast, is a more complicated and more powerful style language that can not only apply styles to the contents of elements but also rearrange elements, add boilerplate text, and transform documents in almost arbitrary ways. XSL is divided into two parts: a transformation language for converting XML trees to alternative trees, and a formatting language for specifying the appearance of the elements of an XML tree. Currently the transformation language is much better supported by most tools than the formatting language. XSL is still under active development and is not yet a standard. Nonetheless, it is beginning to firm up, and is supported by Microsoft Internet Explorer 5.0 and some third party formatting engines.
Part IV introduces some XML based languages and syntaxes that layer on top of basic XML. XLinks provide multi-directional hypertext links that are far more powerful than the simple HTML
<A> tag. XPointers introduce a new syntax you can attach to the end of URLs to link not only to particular documents, but to particular parts of particular documents. Namespaces use prefixes and URLs to disambiguate conflicting XML markup languages. The Resource Description Framework (RDF) is an XML application used to embed meta-data in XML and HTML documents. Meta-data is information about a document, such as the author, date, and title of a work, rather than the work itself. All of these can be added to your own XML-based markup languages to extend their power and utility.
Part V shows you four practical uses of XML in different domains. XHTML is a reformulation of HTML 4.0 as valid XML. Microsofts Channel Definition Format (CDF), is an XML-based markup language for defining channels that can push updated Web site content to subscribers. The Vector Markup Language, (VML) is an XML application for scalable graphics used by Microsoft Office 2000 and Internet Explorer 5.0. Finally a completely new application is developed for genealogical data to show you not just how to use XML tags, but why and when to choose them.
The appendixes focus on the formal specifications for XML, as opposed to the more informal description of it used throughout the rest of the book. Here you'll find both the official XML 1.0 specification published by the W3C as well as detailed explanations of the individual parts of that specification including the BNF grammar, well-formedness constraints, and validity constraints.
Glued to the inside back cover of this book you'll find a CD-ROM that holds all numbered code listings you'll find in the text. It also includes many longer examples that couldn't fit into this already overly large tome. Finally, you'll. Most files on the companion CD-ROM are not compressed, so you can access them directly from the CD.
To make the best use of this book and XML, you need:
A PC running Windows 95, Windows 98, or Windows NT
Internet Explorer 5.0
A Java 1.1 or later virtual machine
Any system that can run Windows will suffice. This book mostly assumes you're using Windows 95 or NT 4.0 or later. As a longtime Mac and Unix user, I do regret this. Like Java, XML is supposed to be platform independent. Also like Java, the reality is somewhat short of the hype. Although XML code is pure text that can be written with any editor, there are many tools that are currently available only on Windows.
However, although there aren't many (or even any) Unix or Macintosh native XML programs, there are an increasing number of XML programs written in Java. If you have a Java 1.1 or later virtual machine on your platform of choice, you should be able to make do. Even if you won't be able to load your XML documents directly into a Web browser, you can still convert them to XML documents and view those. Currently Mozilla is still pre-alpha. However, when it's released, it should provide the best XML browser yet across multiple platforms.
If I've succeeded in piqueing your interest, you'll be able to find The XML Bible at almost any bookstore that carries computer books including amazon.com. It's $49.99, published by IDG Books, and written by me, Elliotte Rusty Harold. | http://www.ibiblio.org/xml/books/bible/index.html | CC-MAIN-2014-15 | refinedweb | 1,776 | 59.94 |
How to simulate user input in console apps?
Started by
TheDcoder,
18 posts in this topic
You need to be a member in order to leave a comment
Sign up for a new account in our community. It's easy!
Register a new account
Already have an account? Sign in here.
Similar Content
- By dubi gui. The front end controls if the “focus” is available to do the “send” and “mouseclick” modifications. The central front end either allows a child to have the focus or prevents it to get the focus (in which case the child will wait and checks again). The code for the front end is included. Apologies for the lengthy explanation.
#RequireAdmin #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <EditConstants.au3> #include <GUIEdit.au3> #include <ScrollBarConstants.au3> #include <Array.au3> Global Const $APF_ALLOWMULTILINE = 1 Global Const $APF_RIGHTALIGN = 6 Global Const $APF_RIGHTALIGNCOL = 2 Global Const $APF_RIGHTALIGNDATA = 4 Global Const $APF_PRINTROWNUM = 8 Global Const $APF_DEFAULT = $APF_PRINTROWNUM Global $PID[9], $FocusAvailable = True, $previousEditMsg Global $PID_waiting[0][2], $logfile $ " & "CheckGuiMsg" & @CRLF) CheckClientMessages() FileWrite($logfile, @HOUR & ":" & @MIN & ":" & @SEC & "> " & "CheckClientMessages" & @CRLF) WEnd Func CheckGuiMsg() $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $btnStart01 AddTextToEdit("Starting Instance 1") $PID[0] = Run("D:\XVM05\Entwicklung_FilterTest_Multi_ToFileV001.exe 1", @ScriptDir, Default, 3) Case $btnStart02 AddTextToEdit("Starting Instance 2") $PID[1] = Run("D:\XVM05\Entwicklung_FilterTest_Multi_ToFileV001.exe 2", @ScriptDir, Default, 3) Case $btnStart03 AddTextToEdit("Starting Instance 3") $PID[2] = Run("D:\XVM05\Entwicklung_FilterTest_Multi_ToFileV001.exe 3", @ScriptDir, Default, 3) Case $btnStart04 AddTextToEdit("Starting Instance 4") $PID[3] = Run("D:\XVM05\Entwicklung_FilterTest_Multi_ToFileV001.exe 4", @ScriptDir, Default, 3) Case $btnPause01 AddTextToEdit("Send Pause to Instance 1") StdinWrite($PID[0], "Pause") Case $btnPause02 StdinWrite($PID[1], "Pause") Case $btnPause03 StdinWrite($PID[2], "Pause") Case $btnPause04 StdinWrite($PID[3], "Pause") Case $tbnStop01 StdinWrite($PID[0], "Stop") Case $tbnStop02 StdinWrite($PID[1], "Stop") Case $tbnStop03 StdinWrite($PID[2], "Stop") Case $tbnStop04 StdinWrite($PID[3], "Stop") Case $btnPauseAll AddTextToEdit(@CRLF & "************Pause All not yet implemented**************" & @CRLF) Case $btnStopAll AddTextToEdit(@CRLF & "************Stop All not yet implemented***************" & @CRLF) EndSwitch EndFunc ;==>CheckGuiMsg Func CheckClientMessages() For $i = 0 To 3 FileWrite($logfile, @HOUR & ":" & @MIN & ":" & @SEC & "> " & $i & @CRLF) Local $a = TimerInit() $p = $PID[$i] $streamRead = StdoutRead($p) If $streamRead <> "" Then Switch $streamRead Case StringInStr($streamRead, "Focus Needed") > 0 If $FocusAvailable Then $FocusAvailable = False StdinWrite($p, "Focus Granted") Else EndIf Case StringInStr($streamRead, "Release Focus") > 0 StdinWrite($p, "Release Focus Received") $FocusAvailable = True Case Else EndSwitch EndIf FileWrite($logfile, @HOUR & ":" & @MIN & ":" & @SEC & "> " & $i & " " & round(TimerDiff($a),2) & @CRLF) Next EndFunc ;==>CheckClientMessages Func AddTextToEdit($text) If $previousEditMsg <> $text Then $previousEditMsg = $text GUICtrlSetData($Edit1, GUICtrlRead($Edit1) & @YEAR & "." & @MON & "." & @MDAY & " - " & @HOUR & ":" & @MIN & ":" & @SEC & "> " & $text & @CRLF) _GUICtrlEdit_Scroll($Edit1, $SB_SCROLLCARET) EndIf EndFunc ;==>AddTextToEdit
My issue now is that the mechanism with with StdoutRead and StdinWrite is not efficient at all. The more instances I start the slower it gets. This is not just a bit slower (like a fraction of a second), but to the degree that the front end is not responding at all any longer (with 3 instances handling).
So my questions are:
1. Is there a flaw in my implementation with StdoutRead and StdinWrite? (note that all works fine with 1 and also (slower) with 2 instances running) but actually breaks down with 3 instances running.
2. Can I optimize the currently used implementation so that I can control 30+ instances?
3. What other implementation do you see suitable for this approach?
a. I have already tried it with communication through files but observed that this is not sufficiently reliable with multiple instances.
b. Is Named Pipes a more performant approach (I am a bit scared of the effort to learn and implement this)
c. Any other method?
Many thanks in advance
-dubi
- kcvinu
Hi all,
Last day i was tried some inter process communication code but not succeeded, as it is a big deal for me. Then i tried with ConsoleWriteError function. It worked for me. Here is my code. I am seeking suggestions to improve.
But my doubt is that; I can't understand the idea of StdinWrite function completely. This is what i think. Please correct me if i am wrong.
1. Make a child program for collect and send the data.
2. Make a parent program and run the child within it and receive data from the child program.
So, i made the sample program with this scenario. But, when i looked StdinWrite function, it needs a process ID as a parameter. I thought that StdinWrite is used in the child program to send data to parent program. Am i right ?.
My code
Child program for collecting and sending data.
Local $compName = @ComputerName ConsoleWriteError($compName) Exit Parent program for receiving data
#include <AutoItConstants.au3> Local $process = Run(@ScriptDir & "\stdWrite.exe","",Default, $STDERR_CHILD ) Local $Data While 1 $Data &= StderrRead($process) If $Data <> "" Then ExitLoop WEnd MsgBox(0, "Std Test Data", $Data)
- By mojomatt. | https://www.autoitscript.com/forum/topic/174590-how-to-simulate-user-input-in-console-apps/ | CC-MAIN-2017-39 | refinedweb | 805 | 56.76 |
This example will show you how to use Django MySQL library pymysql to connect Django application to MySQL database server in Django project. Then you can use MySQL server as the backend database server to store your Django web application data.
1. Set Django Project Use MySQL As Default Database Server.
- Install Django MySQL library pymysql in your PyCharm Django project ( refer PyCharm Project Add External Library (PyMySQL) Path Example ) or in your operating system use pip command as below.
pip3 install pymysql
- Create a Django project in PyCharm ( refer Hello World Django PyCharm Example ).
- Use MySQL databases settings to replace default SQLite3 database settings in Django project settings.py file like below. In below example, the settings.py file is located in DjangoHelloWorld / DjangoHelloWorld.
DATABASES = { 'default': { # Django MySQL database engine driver class. 'ENGINE': 'django.db.backends.mysql', # MySQL database host ip. 'HOST': '127.0.0.1', # port number. 'PORT': '3306', # database name. 'NAME': 'dev2qa', # user name. 'USER': 'jerry', # password 'PASSWORD': 'jerry', # connect options 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",}, } }
2. Migrate Django Project Apps Database Tables To MySQL.
- Now you can run python3 manage.py migrate command to migrate Django project app database tables to the MySQL database server. You have two methods to do it.
- Method 1: Click Tools —> Run manage.py Tasks menu item in PyCharm, then input migrate in the bottom console.
- Method 2: Open a terminal and cd into Django project root folder ( DjangoHelloWorld ), then run python3 manage.py migrate command.
- But both methods will throw ModuleNotFoundError: No module named ‘MySQLdb’ error.
- To resolve this error, add below code in DjangoHelloWorld / DjangoHelloWorld / __init__.py file.
import pymysql # install pymysql as mysql database driver. pymysql.install_as_MySQLdb()
- Now migrate Django project apps database again, then you can see below migrate output.
DjangoHelloWorld > python3 manage.py migrate ...... Applying user_register_login.0001_initial... OK Process finished with exit code 0
- When the migration process complete successfully, you can see below tables are created in MySQL.
3. Create Django Admin Site Superuser.
Now create the Django project admin site superuser.
- Open terminal and cd into DjangoHelloWorld root folder.
- Then run command python3 manage.py createsuperuser.
- Now start DjangoHelloWorld project web server with the command python3 manage.py runserver.
- Browse in a web browser.
- Login to the admin site uses the above user account.
4. How To Fix Error mysqlclient 1.2.13 or newer is required; you have 0.9.3.
- When you run the migration command python3 manage.py migrate you may encounter an error message
mysqlclient 1.2.13 or newer is required; you have 0.9.3.
- This is because the Django MySQL library PyMySQL used mysqlclient library (0.9.3) is outdated.
- You can run command pip install mysqlclient in a terminal to update it.
- Edit __init__.py file and remove all the source code in it.
- Now you can run command python3 manage.py migrate successfully.
5. How To Fix Django MySQL Error [email protected] access denied using password YES.
- When you run command such as pythons manage.py makemigrations or python3 manage.py runserver, you may encounter an error like
- To fix this error, you should first make sure your MySQL server user name and password are correct.
- You also need to make sure the user account has access privileges to the MySQL database server.
- You can open a terminal and run the command mysql -u root -p to login to MySQL manager console.
- Then run SQL statement select host, user from mysql.user; to show all user account.
- Run SQL statement show grants for ‘jerry’@’%’; to show the privileges granted to the user.
- Grant access privilege to the user if you find it has no access privilege, or for test only you can run below command to grant all privileges to the user.
GRANT ALL PRIVILEGES ON *.* TO 'jerry'@'%' WITH GRANT OPTION;
6. How To Fix Django MySQL Error 1049 (42000): Unknown Database.
- This error is because the MySQL database you used does not exist.
- So you should create the MySQL database manually.
- Remember that the Django app will not create the MySQL database, it will only create/migrate DB tables.
- Maybe it is because you input wrong database IP, name, or port number.
- Then you should correct them in Django project settings.py file.
1049 mysql db error in pycharm how to solve
This is because the MySQL DB which you used does not exist, I had written how to fix it at the end of this article.
Hi Jerry Zhao, thanks for hardwork
but, can you please tell me why my command
python manage.py makemigrations
shows the error stating that [email protected] access denied using password YES
I will be waiting for your reply regards,
and if anyone else is interested/they know the ans please give a reply your replies are most welcome…
This is because your MySQL database user account does not has access privilege, so you should check it in your MySQL server side, or maybe you input wrong MySQL username and password. You can see it in the last section of this article.
When I run the migrations I get the following error:
“mysqlclient 1.2.13 or newer is required; you have 0.9.3.”
The version 0.9.3. is the newest version of pymysql.
Am I doing anything wrong?
Hi Janik, the reason for this is that the version of mysqlclient (0.9.3) that comes with PyMySQL is outdated. Simply run “pip install mysqlclient” and delete the code in the __init__.py file. This will allow you to run “python3 manage.py migrate” without a problem.
Was helpful, thanks! | https://www.dev2qa.com/how-to-connect-mysql-database-in-django-project/ | CC-MAIN-2021-31 | refinedweb | 934 | 68.67 |
SQL macros
From Nemerle Homepage
Checking SQL queries
Our library provides special functions (macros) for executing SQL queries. They have similar functionality to methods of System.Data.SqlClient.SqlCommand class, but all the strings passed to them are verified at compile-time. They are being sent to database by compiler, so the database provider is used here as a verification program. If it returns an error, the compilation is stopped with a message pointing to an invalid SQL statement.
Avoiding modification of database
ExecuteNonQuery ("INSERT INTO employee VALUES ('John', 'Boo')", conn);
When the compiler executes any query, it adds a transaction around it and makes a rollback after the execution to avoid modification of the database. So, an SQL statement is executed here to verify if it is correct and then it is reverted.
Safe passing values of variables to queries
Most of the queries in application are parametrized with program variables. For example, we read an employee name from a form and then search for corresponding entries in the database. In such case we want to use some variable inside the query. We can obtain it in Nemerle functions by writing the $ character followed by the name of variable.
def myparm = "John"; def count = ExecuteScalar ("SELECT COUNT FROM employee WHERE firstname = $myparm", dbcon);
Note that passing the value of myparm is done safely using .NET database provider SqlParameter class. This prevents an often used technique of exploiting database applications using SQL code insertion (if a parameter is inserted as a string, one could set its value to some malicious SQL code)
Automatic loop and result variables creation
Because we run queries at compile-time, we can obtain additional information useful for compilation. For example, we know which columns of the table were returned by the query and what are their types. This way the compiler can automatically declare local variables and assign to them corresponding values from the result.
ExecuteReaderLoop ("SELECT * FROM employee WHERE firstname = $myparm", dbcon, { Nemerle.IO.printf ("Name: %s %s\n", firstname, lastname) });
The example above shows even more features. It creates a loop reading rows returned from selection one by one. For each of them, it declares variables containing values from all columns as mentioned before. Additionally, the entire query is created using a myparm variable from program scope.
You might want to see the full code of the above examples see. | http://nemerle.org/SQL_macros | crawl-002 | refinedweb | 397 | 53.51 |
How to bind DataGrid to a list of Hashtable objects
(or any IEnumerable of IDictionary)
Contents
Introduction
Are the traditional .NET languages, C# and Visual Basic, truly dynamic languages? Well, we all know the answer to that question: They are not. Ok, but if they can be used in the same way that we normally use dynamic languages then, perhaps, in a sense they are dynamic. So can we use those languages in some situations as if they were dynamic? My hope is that, after reading this article, you will agree that the answer to that question is a qualified “Yes”.
I believe that the best way to illustrate this is to demonstrate how it can solve a common programming problem. The DataGrid and many of the controls, developed by Microsoft are designed in a way so to expect a list of typed objects as a data source. There are many good reasons for that; but, if we assume for a moment that there might be also a benefit of binding a DataGrid to a list of Hashtables without having to change the controls, wouldn’t that be an example of the dynamic capabilities of .NET languages? If we can turn a list of key value pairs into a class with corresponding properties, then that would certainly be an example of crossing the barrier between dynamic data and static types: We have to be able to do that at run time, of course.
Why would you need to perform such a task? Well, you may need to do it if the number and type of the columns in your DataGrid is something that you can’t predict at design time. This would be the case if, for example, you require that the columns in the grid will display items previously chosen by the user. There are several alternative programming strategies you could use to handle this, and the approach I’m about to describe is among them. I will discuss the other ways later in this article.
How to use it
You would expect that the way to pass dynamic data to the control should be very similar to a traditional dynamic language. Adding a key to Hashtable or IDictionary of (string, object) is just like adding a dynamic property to a dynamic object. In a dynamic language you would use something like this:
In a .NET language you can do likewise, by using IDictionary. So our code, could look like that:
or in Visual Basic (without the yield return statement)
If we were allowed to bind IDictionary to a DataGrid we could just use this code:If we were allowed to bind IDictionary to a DataGrid we could just use this code:
But you cannot bind a list of Hashtables or Dictionaries to DataGrid. If you attempt this, you will actually bind the properties of the collection object and not the key because value pairs are treated as object properties.
There is just one more thing we have to do in order to make that work. We have to define an extension method ToDataSource() of the IEnumerable of IDictionary. The method will transform the list of dictionaries into a list of typed objects with each key turned into object property of the corresponding type. So our binding method will have to be modified just as:
There is no such method defined by the .NET framework for IEnumerable of IDictionary so we have to define it, and much of this article describes how that works. You can also see the attached source of that extension method for both C# and Visual Basic.
Here we see one of the amazing aspects of .NET 3.5: we have the means to define a method for an interface as an extension method. This is also one dynamic feature in the framework because we don’t have to modify the definition of IEnumerable of T – something we would not be able to do anyway because this is as interface and yet we can make that method a part of the IEnumerable of IDictionary, by a simple inclusion of the extension method class into the current code. One more using statement and your interface is enriched with a new method. I have to stress here that overusing this feature may result in an abundance of unneeded methods but I think we can safely assume that anytime you have IEnumerable of IDictionary you can expect that it may be designed for transformation into a collection of typed objects.
The extension method will use the first IDictionary entry as a template for a newly created typed object. If the next IDictionary contains more properties then they will be ignored, if it contains fewer then the properties will be assigned with the default values. Each key of IDictionary must be alphanumeric and start with character – because it will be transformed into an object property. If it is not alphanumeric then an exception will be thrown. If the keys of IDictionary are not strings they will be transformed to strings by calling ToString() method. If you end up with a key collision because of different dictionary key objects resulting in the same string then an exception will be thrown.
It all may look like a lot of rules, but if you always use strings as keys for the IDictionary as you would in a dynamic language, and make sure that all IDictionary entries have the same keys with the same types, it will just work.
If you want column headers in the grid even if your collection contains no data, you would have to define columns of the grid and set the AutoGenerateColumns property to false.
Despite all the reflection, the code works fine in a middle trust environment of a typical shared hosting. You could also use the same code not only for traditional .NET applications but for Silverlight projects as well. In fact I came to the idea of using this extension method while working on a Silverlight application. In Silverlight 2.0 you have no Hashtables, so there you would use Dictionary of string and object. I find it quite exciting that, within the limited range of Silverlight framework, you can use so powerful data transformation techniques based on reflection. You don’t need to change anything to make it work in Silverlight. Just use the same code.
Static vs. Dynamic – system architecture concerns
I am sure some developers would be convinced that we shouldn’t use the technique I’ve described, because there is a reason for a DataGrid not to accept dynamic data. The argument, in a nutshell, is that the dynamic data does not enforce the data constraints and therefore opens a potential risk of errors.
This isn’t the place for the endless discussion of the merits of Static vs. Dynamic languages, but I cannot pass this topic without even mentioning it. I agree that in general we have to try to restrict the data to the constraints it should follow. This is especially true when we talk about data operations within the business layer, where the application business logic resides. However in the user interface layer, we can be a little bit more liberal if that will make us more agile and if it will help to implement UI changes easier, quicker and with less code. I think that the area of user interface data binding is a perfect place for a more dynamic approach.
It has to be said as well, that if you want to add a data verification code just between the method generating IEnumerable of IDictionary and the call to ToDataSource extension method you are free to do so. There is nothing that prevents you from doing that.
I personally believe that both dynamic and static code have their place in the architecture of one enterprise system. The business layer should be more static and the user interface can be more dynamic. But whatever is your opinion on this topic I believe you will agree with me that having one additional tool in your arsenal will not be a bad idea. And the approach I describe here is just another tool to pass dynamic data into a UI control that expects a collection of statically typed objects.
Alternative ways to pass dynamic data to a DataGrid
Internally the grid will check for the first item in the collection if it is ICustomTypeDescriptor. If it is not, then the properties of the object will be used for column binding. If it is, then the TypeDescriptor.GetProperties static method will transform that object into a collection of PropertyDescriptors. So defining your collection, as ICustomTypeDescriptor would be the classical way of passing dynamic data into a .NET control. This is because many of the .NET controls will check for the type to see if it is ICustomTypeDescriptor.
Here is a reference to Windows Forms code send to me by Lionel WindowsApplicationDataBinding.cs
The code here achieves the same goal as the code I propose; the transformation of IDictionary into a collection that can be bound, but it is based on PropertyDescriptors and ICustomTypeDescriptor interface. I find it to be a very impressive code and would certainly advise you to check it. It has some significant advantages – it does not use reflection and it does not have the restriction that the property has to start with letter.
But despite all the advantages this approach also has some drawbacks. Even though the Windows Forms DataGridView works fine with it, web forms DataGrid could not auto generate columns based on that code, so there you’d have to define the columns by yourself. But the biggest problem is that the code would not work in Silverlight because there is no PropertyDescriptor object defined by the Silverlight framework.
Another way to apply dynamic data to a DataGrid would be to generate DataSet out of Hashtable or XML or anything dynamic. If you choose this way you would have to do some more work to generate the DataSet.
You could also populate DataGrid with many other techniques that are not direct data binding but I will not discuss them, as they are not pure techniques of data binding – passing a collection of data and attaching the data elements to the UI.
All those methods should be considered as valid choices with their advantages and disadvantages.
The reason that I prefer the dynamic solution I’ve described is that it will work without any changes for Windows Forms, Web Forms and Silverlight. It can also be used for a wider range of goals beyond data binding because the objects generated are valid .NET types. The method I propose offers very clean and simple interface – a single extension method transforms “dynamic” object into typed one.
The disadvantage of this idea is in the fact that using reflection will have some performance implications – each binding will result in a separate new dynamic assembly. For a web project where you have thousands of users viewing the grid simultaneously you would rather choose the solution proposed by Lionel, but for a single Windows Forms user you should not expect to notice any performance drawbacks and the same is true for a Silverlight project. As a matter of fact Silverlight is probably the best candidate for that solution because the more traditional ways are not available there and yet this is a single client executing on the client machine and not on the server.
If solving this task is all you are interested in, then you can get the Visual Basic DataSourceCreator.vb or C# DataSourceCreator.cs source, where the ToDataSource extension method is defined and just use it in your code the way it was described above, but if you want to understand how it actually works, please read the next part of this article.
What if you use .NET 2.0 and not 3.5?
I chose to develop this idea using C# 3.0 feature of extension methods as I find this to be a very elegant way to extend the functionality of common interfaces very similar to the idea of extending a dynamic object by simply adding a new method.
However if you use .NET 2.0 you could still use my code. You would only have to change method definition
by removing this keyword to be as
or in Visual Basic, change
To remove the attribute Extension and have the method just as
Then in your code simply use it as a static method:
How does it work?
Here is what happens inside the extension method. First of all I generate dynamic assembly and I call it “TempAssembly” plus the hash code of the IEnumerable collection. I then define the type of the object will be public class.
After that, I get the first IDictionary in the IEnumerable to be used as a template for the newly generated statically typed object. First I check with a regular expression that each key is alphanumeric and starts with letter so it can be transformed into property name. This is the regular expression I have used:
If the key does not follow this constraint, then I throw an application exception. Then for each key I generate a property. In .NET on a lower level getter property is transformed to get_<PropertyName>() method and setter property is transformed to set_<PropertyName>(value) method. So I generate both setter and getter and the private field lying underneath. The private field starts as usual with an underscore character. I get the type for the properties and private field from the current value in the IDictionary. If the value is NULL then the property is of type object.
Here is how the code generating properties looks:
After that, the process of object creation is completed, and you may think that we are done here – let’s just put it into an array of objects and this is all. Unfortunately this is not a good idea because UI controls may use the type of the collection for their internal functionality. Thus the Silverlight DataGrid has sorting functionality that is implemented based on a reflection of the bound collection. I assume that they do this because they want to be able to know what columns they have even if the collection is empty. But that means that we have to pass a collection not of general object type but of the dynamic type we have just generated. This is the way we do that:
As you can see, I generate a generic type List of our object type, then I instantiate it with the activator. After that I traverse each IDictionary DictionaryEntry, matching it with the corresponding property in order to set the value. Here we will get an exception if the type of the first IDictionary key is not the same as the type of the corresponding current IDictionary key.
You may ask here if all this reflection work will have significant performance implications, and I need to clarify that the length of the list of IDictionary objects will not have such performance implications because all the reflection work that I’ve described is being applied to the first IDictionary only. After that, the type is already created and everything is just as if you were binding a regular collection of predefined typed objects. In other words a slow down due to the reflection operations can be expected if you generate a huge number of columns / properties, but should not be expected because of a huge number of records. This is because all records except the first one are processed with a type defined in assembly that has already been loaded into the framework.
But still each binding will result in a creation of a dynamic assembly. This is not a problem for a single Windows or Silverlight application but might be a problem for multi-user server.
Summary
The solution that I’ve described here will be among your first choices for a Silverlight project where you have much more limited set of options. It is one of the many options in Windows Forms and can be applied in Web Forms, though it may not be the best choice in this case because each page visit results in a new assembly being generated on the server.
The ability to dynamically generate typed objects makes .NET a really powerful environment. We can retain the constraints of the statically typed objects and at the same time benefit from the agility of the dynamic data.
Data binding of the user interface is a critical point where the dynamic data has to be presented in a way that isn’t known at design time. Once we know how to transform IDictionary into a typed object we can just use Hashtables as if they were dynamic objects – and this is what has been demonstrated in this article. I hope that now you will agree with me in my conclusion that .NET languages C# and Visual Basic can be used just as regular dynamic language for data binding of user interface controls.
As always, the C# and VB code is downloadable from the bottom of the article.
Vladimir’s blog on is always well-worth reading. | https://www.red-gate.com/simple-talk/dotnet/net-framework/dynamically-generating-typed-objects-in-net/ | CC-MAIN-2018-26 | refinedweb | 2,877 | 58.42 |
Rendering be the best way to do it, but I'm obviously not understanding how the 'scene' module works.
For example: I want to display the intro text, so I've coded the following:
import console from scene import * import time class MyScene(Scene): def draw(self): pass def setup(self): global screen screen = self.size w, h = self.size.w, self.size.h self.graphicBlurb() def graphicBlurb(self): blurb = [] blurb.append("Space ... the final frontier.") blurb.append("These are the voyages of the starship Enterprise") blurb.append("Its five year mission ...") blurb.append("... to boldly go where no-one has gone before") blurb.append("You are Captain Kirk.") blurb.append("Your mission is to destroy all of the Klingons in the galaxy.") #font_size = 60 if self.size5.w > 700 else 40 yOffset = screen.h/(len(blurb)) yPos = screen.h for line in blurb: text(line,'GillSans',40,screen.w/2,yPos) print "Printing {0} {1}".format(line,time.localtime()) time.sleep(1.5) yPos -= yOffset trekGame = MyScene() run(trekGame)
but when I run this, instead of the lines of text appearing one at a time down the screen, I get a black screen for about 10.5 seconds, then all the text appears at once.
I'm guessing that it's running the 'setup' method but nothing is appearing on screen until the 'draw' method is called.
What's the best way to do this, or is 'scene' only for programs that need to 60fps gameloop and should I be using the 'ui' module instead?
Thanks,
Steve
setupis called once. Think of it more like compiling your scene.. Don't use wait here. All drawing should happen inside of
draw, and you can't use
waitthere either. Rather, you'd keep track of time, and update game state inside draw (say, as instance variables of your scene class).
For example, you'd have
MyScene.blurb, which could be updated inside draw based on a counter, or maybe in a function called from
scene.delaythe first time draw is called, or touch happens. (A scene.delay'd function could call scene.delay at the end, for example to append to blurb once a second for example.
If you want the user to type things, as opposed to just touch interaction, a SceneView might be a better fit, since you could have a textbox input field. You would still interact with the scene by use of your instance variables, and draw still does all of the drawing based on the game state encoded inside those instance variables
Thanks Jon. As this is a text-heavy game, I think that a 'ui' based interface will work better.
Take a look at stash. The stash terminal class probably does a lot of what you want, assuming you don't need colors -- it has a scrolling buffer and an input field that moves when the keyboard frame appears, along with history, and some autocompletion framework. Some formatting has been implemented in the ssh module, I believe, using the pyte terminal emulator library.
You can either subclass the appropriate classes, or you can actually write .py scripts that make use of the stash modules (i.e. called from within stash), for instance a script called from stash that uses raw_input will use stash's stdin replacement. You also have access to the global
_stashfor more complicated things like directly accessing the buffer.
If you do need color, then you'd probably be best using a WebView for display, along with a TextView or TextField for input. | https://forum.omz-software.com/topic/1768/rendering-text-for-classic-star-trek-game-using-scene | CC-MAIN-2021-10 | refinedweb | 591 | 75 |
The only features originally allowed into C++ were those which had efficient implementations. This sounds great, but the results were sometimes dubious. Consider the following program which uses multiple inheritance.
#include <cstdio> #include <inttypes.h> using namespace std; class Left { int32_t a, b; }; class Right { int32_t c, d; }; class Bottom : public Left, public Right { }; int main(int argc, char *argv[]) { Bottom *bottom = new Bottom(); Left *left = bottom; Right *right = bottom; printf("left -> %p\n", left); printf("bottom -> %p\n", bottom); printf("right -> %p\n", right); if (left == bottom && bottom == right) { printf("left == bottom == right\n"); } else { printf("!(left == bottom == right)\n"); } return 0; }
The first three lines of output are:
left -> 0x24dd010 bottom -> 0x24dd010 right -> 0x24dd018
Right off the bat, we see that something happened to
right. The statement
right = bottom did something special: instead of setting
right to
bottom, it actually set it to
bottom + 8. To understand why, we need to look at the memory representation for
*bottom.
0x24dd006 -> | ... | 0x24dd010 -> | int32_t a | <- bottom, left 0x24dd014 -> | int32_t b | 0x24dd018 -> | int32_t c | <- right 0x24dd022 -> | int32_t d | 0x24dd026 -> | ... |
A
Bottom object consists of a
Left object, followed by a
Right object. In turn,
Left and
Right objects consist of their own fields. So, a
Bottom consists of four
int32_ts.
One of the principles behind C++ was that access to object fields should be as fast as possible. In our case, it’s possible to avoid any indirection and make it as fast as normal variable access: since the compiler knows the memory layout, it replaces accesses to
bottom->a by
*bottom, accesses to
bottom->b by
*(bottom + 4), and so on. This works fine for
bottom, which actually points to a
Bottom object, and for
left because the first part of a
Bottom object is a
Left object.
What about
right? We want
right->d to be replaceable by
*(right+4), but it’s the second part of a
Bottom object that is a
Right object. For this to work, the statement
right = bottom cannot simply assign
bottom to
right; instead, it casts
Bottom* to
Right* by assigning
bottom + <offset of Right in Bottom> to
right.
Now that we understand what’s happening, we can ask the next question: what is the last line of output? Is it
left == bottom == right? Or
!(left == bottom == right)? It’s the former: the compiler somehow keeps track of what the pointers are supposed to be, and tries to hide the offsetting from the programmer.
I generally like C++, but this gives me mixed feelings. A part of me thinks that this is awesome, and another part screams in horror.
This article is a very good description of C++’s multiple and virtual inheritance with a focus on memory layouts. | https://scvalex.net/posts/30/ | CC-MAIN-2019-04 | refinedweb | 455 | 62.27 |
What is a cassette?¶
A cassette is a set of recorded interactions serialized to a specific format. Currently the only supported format is JSON. A cassette has a list (or array) of interactions and information about the library that recorded it. This means that the cassette’s structure (using JSON) is
{ "http_interactions": [ // ... ], "recorded_with": "betamax" }
Each interaction is the object representing the request and response as well as the date it was recorded. The structure of an interaction is
{ "request": { // ... }, "response": { // ... }, "recorded_at": "2013-09-28T01:25:38" }
Each request has the body, method, uri, and an object representing the headers. A serialized request looks like:
{ "body": { "string": "...", "encoding": "utf-8" }, "method": "GET", "uri": "", "headers": { // ... } }
A serialized response has the status_code, url, and objects representing the headers and the body. A serialized response looks like:
{ "body": { "encoding": "utf-8", "string": "..." }, "url": "", "status": { "code": 200, "message": "OK" }, "headers": { // ... } }
If you put everything together, you get:
{ "http_interactions": [ { "request": { { "body": { "string": "...", "encoding": "utf-8" }, "method": "GET", "uri": "", "headers": { // ... } } }, "response": { { "body": { "encoding": "utf-8", "string": "..." }, "url": "", "status": { "code": 200, "message": "OK" }, "headers": { // ... } } }, "recorded_at": "2013-09-28T01:25:38" } ], "recorded_with": "betamax" }
If you were to pretty-print a cassette, this is vaguely what you would see. Keep in mind that since Python does not keep dictionaries ordered, the items may not be in the same order as this example.
Note
Pro-tip You can pretty print a cassette like so:
python -m json.tool cassette.json.
What is a cassette library?¶
When configuring Betamax, you can choose your own cassette library directory. This is the directory available from the current directory in which you want to store your cassettes.
For example, let’s say that you set your cassette library to be
tests/cassettes/. In that case, when you record a cassette, it will be
saved there. To continue the example, let’s say you use the following code:
from requests import Session from betamax import Betamax s = Session() with Betamax(s, cassette_library_dir='tests/cassettes').use_cassette('example'): r = s.get('')
You would then have the following directory structure:
. `-- tests `-- cassettes `-- example.json | http://betamax.readthedocs.io/en/latest/cassettes.html | CC-MAIN-2018-05 | refinedweb | 345 | 60.31 |
Components and supplies
Apps and online services
About this project
In this simple example, we press a button in Unity repeatedly. Then Arduino turns on and off the built-in LED and also changes the button text and color.
Unity windows will looks like above, if you import MiniLab unity package. There are 8 Controls (UI parts) as prefabs in Assets folder. Here a Push button Control is dragged from there into the scene. The corresponding Arduino code is as shown above.
The overall codes were generated by a menu in the Inspector when Bench selected in the hierarchy window. In the MiniLab's Inspector we set Baud Rate and Port (COM) number.
Press the Play button in Unity, and click the Push button repeatedly. You will see the button text change between "Hello" and "World", with button color changes. You will also hear system sounds.
Code
HelloArduino
#include <MiniLab.h> String title = "Hello"; Push push(1); void setup () { Serial.begin(9600); pinMode(13, OUTPUT); } void loop () { delay(100); if (Serial.available() == 0) return; int id = MiniLab.readInt(); if (id == MiniLab.id_start) { if (!MiniLab.checkTitle(title)) return; return; } if (id == push.id) { int state = !digitalRead(13); digitalWrite(13, state); push.print(state ? "Hello" : "World"); push.set(state ? yellow : cyan); MiniLab.beepSound(); MiniLab.log("log() is useful for simple display or debugging"); } }
Author
Published onJune 27, 2018
Members who respect this project
you might like | https://create.arduino.cc/projecthub/minilab/using-unity-to-make-and-run-ui-to-arduino-4265c3 | CC-MAIN-2021-17 | refinedweb | 234 | 61.73 |
Related Reads
Upatre Continues to Evolve with new Anti-Analysis ...
July 13, 2018
150
Today, I will present a random MAC address generator tool written in Python. This code is for educational purposes and you can test this code and learn more about Python programming.
MAC is an acronym for Media Access Control address and is a unique identifier assigned to network interfaces (e.g: NIC cards) for communications at the data link layer of a network segment.
There is the source code of the generator:
`#!/usr/bin/python
# *-* coding:utf-8 *-*
import random
def randomMAC():
”’
generate random MAC address.
the first 24 bits are for OUI (Organizationally Unique Identifier).
”’
mac = [0x00, 0x8c, 0xfa,
random.randint(0x00, 0xff),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff)
] return ‘:’.join(map(lambda x: “%02x” % x, mac))
if __name__ == ‘__main__’:
print randomMAC()`
I hope this code will be helpful to you, if you have some questions then ask me in the comments.?
Hi Bmsr256, what is this the benefit for your script against macchanger ?
Hi, the purpose of this code is to help you understand in python how do you can change a MAC address via software, like macchanger, however macchanger is a very powerful tool and available in many Unix/Linux platforms. This code is to help you understand how things work.
Thank you for the response
Beautiful
testing…
thank you
How do you test it?
You have to run the following command: python name_of_file.py , for example, to test it. | https://www.cybrary.it/0p3n/mac-address-generator-code/ | CC-MAIN-2019-43 | refinedweb | 249 | 67.45 |
Add email to contacts
Hi,
I am new to both Python and Pythonista. I am trying to create code to deduplicate contacts on iPhone.
However, I am not able to add email to Contacts.
import contacts
people = contacts.get_all_people()
print people[0].full_name
people[0].email.append((u'$!<Other>!$', u'test@test.com'))
contacts.save()
Why is this email not showing up in iPad Contacts?
Regards,
Dejan
you have to re-assign the
Personobject. Modifying the list in-place has no effect, because the
Personobject cannot detect changes in that list (it's just a snapshot copy).
Try something like this:
import contacts people = contacts.get_all_people() print people[0].full_name emails = people[0].email emails.append((u'$!<Other>!$', u'test@test.com')) people[0].email = emails # !!! contacts.save()
wow really great coding email append thanks to shared this | https://forum.omz-software.com/topic/2496/add-email-to-contacts | CC-MAIN-2018-13 | refinedweb | 138 | 53.78 |
The GCC 6. This document is an effort to identify major issues and provide clear solutions in a quick and easily searched manner. Additions and suggestions for improvement are welcome.
GCC 6 defaults to
-std=gnu++14 instead of
-std=gnu++98:
the C++14 standard, plus GNU extensions.
This brings several changes that users should be aware of, some new with the C++14
standard, others that appeared with the C++11 standard. The following
paragraphs describe some of these changes and suggest how to deal with them.
Some users might prefer to stay with gnu++98, in which case we suggest to
use the
-std=gnu++98 command-line option, perhaps by putting it
in
CXXFLAGS or similar variables in Makefiles.
Alternatively, you might prefer to update to gnu++11, bringing in the C++11
changes but not the C++14 ones. If so, use the
-std=gnu++11
command-line option.
The C++11 standard does not allow "narrowing conversions" inside braced initialization lists, meaning conversions to a type with less precision or a smaller range, for example:
int i = 127; char s[] = { i, 256 };
In the above example the value 127 would fit in
char but
because it's not a constant it is still a narrowing conversion. If the value
256 is larger than
CHAR_MAX then that is also a narrowing
conversion. Narrowing conversions can be avoided by using an explicit cast,
e.g.
(char)i.
The C++11 "user-defined literals" feature allows custom suffixes to be added
to literals, so that for example
"Hello, world!"s creates a
std::string object. This means that code relying on string
concatenation of string literals and macros might fail to compile, for
example using
printf("%"PRIu64, uint64_value) is not valid in
C++11, because
PRIu64 is parsed as a literal suffix. To fix
the code to compile in C++11 add whitespace between the string literal and the
macro:
printf("%" PRIu64, uint64_value)..
As of C++11, iostream classes are no longer implicitly convertible to
void* so it is no longer valid to do something like:
bool valid(std::ostream& os) { return os; }
Such code must be changed to convert the iostream object to
bool
explicitly, e.g.
return (bool)os;
or
return static_cast<bool>(os);
The change to iostream classes also affects code that tries to check for stream
errors by comparing to
NULL or
0.
Such code should be changed to simply test the stream directly, instead of
comparing it to a null pointer:
if (file) { // not if (file != NULL), or if (file != 0) ... }
Since C++11 (as per DR#387) the member functions
real() and
imag() of
std::complex can no longer be used as
lvalues, thus the following code is rejected:
std::complex<double> f; f.real () = val;
To assign
val to the real component of
f, the
following should be used instead:
std::complex<double> f; f.real (val);
noexceptby"); }
The
<algorithm> header has been changed to reduce the
number of other headers it includes in C++11 mode or above.
As such, C++ programs that used components defined in
<random>,
<vector>, or
<memory> without explicitly including the right headers
will no longer compile.
<cmath>changes
Some C libraries declare obsolete
int isinf(double) or
int isnan(double) functions in the
<math.h>
header. These functions conflict with standard C++ functions with the same
name but a different return type (the C++ functions return
bool).
When the obsolete functions are declared by the C library the C++ library
will use them and import them into namespace
std
instead of defining the correct signatures.
<math.h>changes
The C++ library now provides its own
<math.h> header that
wraps the C library header of the same name. The C++ header defines
additional overloads of some functions and ensures that all standard
functions are defined as real functions and not as macros.
Code which assumes that
sin,
cos,
pow,
isfinite etc. are macros may no longer compile.
<stdlib.h>changes
The C++ library now provides its own
<stdlib.h> header that
wraps the C library header of the same name. The C++ header defines
additional overloads of some functions and ensures that all standard
functions are defined as real functions and not as macros.
Code which assumes that
abs,
malloc etc.
are macros may no longer compile.
Programs which provide their own wrappers for
<stdlib.h>
or other standard headers are operating outside the standard and so are
responsible for ensuring their headers work correctly with the headers in
the C++ standard library.
abs(unsigned int&)' is ambiguous
The additional overloads can cause the compiler to reject invalid code that was accepted before. An example of such code is the below:
#include <stdlib.h> int foo (unsigned x) { return abs (x); }
Since calling
abs() on an unsigned value doesn't make sense,
this code will become explicitly invalid as per discussion in the LWG.
this
When optimizing, GCC now assumes the
this pointer can never be
null, which is guaranteed by the language rules. Invalid programs which
assume it is OK to invoke a member function through a null pointer (possibly
relying on checks like
this != NULL) may crash or otherwise fail
at run time if null pointer checks are optimized away.
With the
-Wnull-dereference option the compiler tries to warn
when it detects such invalid code.
If the program cannot be fixed to remove the undefined behavior then the
option
-fno-delete-null-pointer-checks can be used to disable
this optimization. That option also disables other optimizations involving
pointers, not only those involving
this.
std::auto_ptr
The
std::auto_ptr class template was deprecated in C++11, so GCC
now warns about its usage. This warning can be suppressed with the
-Wno-deprecated-declarations command-line option, though we
advise to port the code to use C++11's
std::unique_ptr instead.
Since C++11, the
constexpr keyword is needed when initializing a
non-integral static data member in a class. As a GNU extension, the following
program is accepted in C++03 (albeit with a
-Wpedantic warning):
struct X { const static double i = 10; };
The C++11 standard supports that in-class initialization using
constexpr instead, so the GNU extension is no longer supported for
C++11 or later. Programs relying on the extension will be rejected with an
error. The fix is to use
constexpr instead of
const.
As of this release, the C++ compiler is now more strict about flexible array member rules. As a consequence, the following code is no longer accepted:
union U { int i; char a[]; };
Furthermore, the C++ compiler now rejects structures with a flexible array member as the only member:
struct S { char a[]; };
Finally, the type and mangling of flexible array members has changed
from previous releases. While in GCC 5 and prior the type of a flexible
array member is an array of zero elements (a GCC extension), in GCC 6 it
is that of an array of an unspecified bound (i.e.,
T[] as opposed
to
T[0]). This is a silent ABI change with no corresponding
-fabi-version or
-Wabi option to disable or warn
about.
-flifetime-dse
The C++ compiler (with
-flifetime-dse enabled)
is more aggressive about dead-store elimination in situations where
a memory store to a location precedes the construction of an object at
that memory location. Such situations are commonly found in programs
which zero memory in a custom
new operator:
#include <stdlib.h> #include <string.h> #include <assert.h> struct A { A() {} void* operator new(size_t s) { void* ptr = malloc(s); memset(ptr, 0xFF, s); return ptr; } void operator delete(void* ptr) { free(ptr); } int value; }; int main() { A* a = new A; assert(a->value == -1); // Use of uninitialized value delete a; }
An object's constructor begins the lifetime of a new object at the relevant memory location, so any stores to that memory location which happen before the constructor are considered "dead stores" and so can be optimized away. If the memory needs to be initialized to specific values then that should be done by the constructor, not by code that happens before the constructor.
If the program cannot be fixed to remove the undefined behavior then
the option
-flifetime-dse=1 can be used to disable
this optimization.
A new warning
-Wmisleading-indentation was added
to
-Wall, warning about places where the indentation of
the code might mislead a human reader about the control flow: has highlighted genuine bugs, often due to missing braces, but it
sometimes reports warnings for poorly-indented files, or on projects
with unusual indentation. This may cause build errors if you
have
-Wall -Werror in your project.
The best fix is usually to fix the indentation of the code to match
the block structure, or to fix the block structure by adding missing
braces. If changing the source is not practical or desirable (e.g. for
autogenerated code, or to avoid churn in the source history), the
warning can be disabled by adding
-Wno-misleading-indentation
to the build flags. Alternatively, you can disable it for just one part of
a source file or function using pragmas:
#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmisleading-indentation" /* (code for which the warning is to be disabled) */ #pragma GCC diagnostic pop
Source files with mixed tabs and spaces that don't use 8-space tabs may lead to warnings. A real-world example was for such a source file, which contained an Emacs directive to view tabs to be 4 spaces wide:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
The mixture of tabs and spaces did correctly reflect the block
structure when viewed in Emacs, but not in other editors, or in an
HTML view of the source repository.
By default,
-Wmisleading-indentation assumes tabs to
be 8 spaces wide. It would have been possible to avoid this warning
by adding
-ftabstop=4 to the build flags for this file,
but given that the code was confusing when viewed in other editors,
the indentation of the source was fixed instead.
A new warning
-Wnonnull-compare was added to
-Wall.
It warns about comparing parameters declared as
nonnull with
NULL. For example, the compiler will now warn about the following
code:
__attribute__((nonnull)) void foo (void *p) { if (p == NULL) abort (); // ... }
The internals of GCC have seen various improvements, and these may affect plugins. Some notes on porting GCC plugins to GCC 6 follow.
gimplebecame a struct, rather than a pointer
Prior to GCC 6,
gimple meant a pointer to a statement.
It was a typedef aliasing the type
struct gimple_statement_base *:
/* Excerpt from GCC 5's coretypes.h. */ typedef struct gimple_statement_base *gimple; typedef const struct gimple_statement_base *const_gimple; typedef gimple gimple_seq;
As of GCC 6, the code above became:
/* Excerpt from GCC 6's coretypes.h. */ struct gimple; typedef gimple *gimple_seq;
gimple is now the statement struct itself, not
a pointer. The
gimple struct is now the base class of the
gimple statement class hierarchy, and throughout gcc every
instance of
gimple was changed to a
gimple *
(revision
r227941
is the commit in question). The typedef
const_gimple is no more;
use
const gimple * if you need to represent a pointer
to a unmodifiable gimple statement.
Plugins that work with gimple will need to be updated to reflect this change. If you aim for compatibility between both GCC 6 and earlier releases of GCC, it may be cleanest to introduce a compatibility typedef in your plugin, such as:
#if (GCC_VERSION >= 6000) typedef gimple *gimple_stmt_ptr; #else typedef gimple gimple_stmt_ptr; #end
Marek Polacek Fedora mass rebuild 2016 on x86_64
Copyright (C) Free Software Foundation, Inc. Verbatim copying and distribution of this entire article is permitted in any medium, provided this notice is preserved.
These pages are maintained by the GCC team. Last modified 2016-08-18. | http://gcc.gnu.org/gcc-6/porting_to.html | CC-MAIN-2017-43 | refinedweb | 1,979 | 59.23 |
Why this thread prints out nothing
This is trivial code yet it doesn't function as expected. Why this code prints out nothing.
#include <QCoreApplication> #include <QDebug> #include <QThread> class TextThread : public QThread { public: TextThread(const QString &text); void run(); private: QString m_text; }; bool stopThreads = false; TextThread::TextThread(const QString &text) : QThread() { m_text = text; } void TextThread::run() { while(!stopThreads){ qDebug() << m_text; sleep(1); } } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); TextThread foo("Foo"), bar("Bar"); foo.start(); bar.start(); stopThreads = true; foo.wait(); bar.wait(); return app.exec(); }
@CroCo hi,friend,welcome.
maybe your thread had not to run when you to set
stopThreads = true. you can try it by below code snippet.
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); TextThread foo("Foo"), bar("Bar"); foo.start(); bar.start(); qDebug() << foo.isRunning() << ":" << bar.isRunning(); QThread::sleep(3); //< let the main thread sleep some seconds qDebug() << foo.isRunning() << ":" << bar.isRunning(); stopThreads = true; foo.wait(); bar.wait(); return app.exec(); }
Our good old friend: the race condition.
bool stopThreadsshould become
std::atomic_bool stopThreads
- no need to use
QThreadif you don't require signal/slot communication, just use
std::async([&stopThreads]()->void{while(!stopThreads){ qDebug() << m_text; sleep(1); }});
- If you really want to learn the correct way of using QThread, see
#include <QApplication> #include <thread> #include <future> #include <chrono> #include <iostream> #include <atomic> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); std::atomic_bool stopThreads; stopThreads=false; const auto printEverySecond = [&stopThreads](const QString& text)->void{ while(!stopThreads){ std::cerr<< qPrintable(text); std::this_thread::sleep_for(std::chrono::seconds(1)); } }; std::async(std::launch::async,printEverySecond,QStringLiteral("Foo")); std::async(std::launch::async,printEverySecond,QStringLiteral("Bar")); std::async(std::launch::async,[&stopThreads]()->void{ std::this_thread::sleep_for(std::chrono::seconds(5)); stopThreads=true;}); return app.exec(); }
@VRonin
How does your use of
std::async([&stopThreads]())ultimately avoid the issue of precisely when the main program chooses to set
stopThreads = trueversus how long/many times the thread is allowed to print out
m_text?
@JNBarchan Yep, that's why I added the full example in an edit. Also, must be noted, I don't think
qDebug()is thread safe so I switched to good old
std::cerr
- JKSH Moderators
@VRonin said in Why this thread prints out nothing:
I don't think
qDebug()is thread safe so I switched to good old
std::cerr
This was discussed in the Development mailing list recently, but it seems to be missing from the archives. The discussion led to
Basically, qDebug is thread safe, but stderr is unbuffered. Therefore, when 2 threads write long messages to qDebug at the same time, the output from the threads could become interleaved. However, if we install a custom message handler and make qDebug write to stdout instead of stderr, the problem disappears.
- kshegunov Qt Champions 2017
@VRonin said in Why this thread prints out nothing:
I don't think qDebug() is thread safe so I switched to good old std::cerr
It is and has been for ages, it's just not reflected in the docs (as @JKSH pointed out). It's intended for debug only, though, not for application logging.
@VRonin said in Why this thread prints out nothing:
atomic_bool
using atomic_bool didn't solve the problem.
- kshegunov Qt Champions 2017
- Where are you looking for the debug output?
- does it print from the main thread? (I imagine no)
@kshegunov from the command prompt. No it doesn't print from the main thread.
@CroCo
I'm interested in this, but lost as to just what your code now looks like? Is it exactly (more or less) as per your original post still, or have you done stuff as per either @joeQ or @VRonin 's code?
In particular, if you sleep after you have started your threads and before you set
stopThreads = true, you really should see output from threads'
run()?
And to eliminate any arguments about
qDebug/output, if you run under debugger and place breakpoint in
TextThread::run, what do you actually hit/not hit? (If you really can't use a debugger, at least put in a
qDebug() << "Got here";as the first statement in
TextThread::run, so we're not wondering about
stopThreadsvalue.) Even though your code is "simple", at this point given that you haven't found an answer there is still quite a bit of possible simplification to reduce the issue to its nub.
- JKSH Moderators
@CroCo said in Why this thread prints out nothing:
@kshegunov from the command prompt. No it doesn't print from the main thread.
Are you using Windows? Your debug output might be going to the system debug log instead of the command prompt. You can monitor the system debug log by running DebugView before you start your app:
If you still can't see your debug messages,
- Post your *.pro file
- Post your latest code
- Tell us: How are you building your app, and how are you running your app? | https://forum.qt.io/topic/84723/why-this-thread-prints-out-nothing | CC-MAIN-2018-51 | refinedweb | 825 | 63.09 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.