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 |
|---|---|---|---|---|---|
Hi, I have attached a second version to address the issues reported. On Thu, Jan 07, 2010, Diego Biurrun wrote: > On Wed, Jan 06, 2010 at 09:51:36PM +0100, Laurent Aimar wrote: > > > > The attached path allows VLD H264 decoding using DXVA2 (GPU assisted > > decoding API under VISTA and Windows 7). > > Get rid of all the tabs. Done, sorry for that one. > alphabetical order Done. > > --- libavcodec/dxva2_h264.c (revision 0) > > +++ libavcodec/dxva2_h264.c (revision 0) > > @@ -0,0 +1,559 @@ > > + > > +#ifdef HAVE_CONFIG_H > > +# include "config.h" > > +#endif > > We don't use this #ifdef. Removed. > > +/* */ > > +struct dxva2_picture_context > > +{ > > Place the { on the same line as the struct declaration. Done. > > + for (i = 0; i < ctx->surface_count; i++) { > > + if (ctx->surface[i] == surface) > > + return i; > > + } > > pointless {} Done, but I prefer to use {} when the code is on multiple lines (I find it safer and easier to read). > Align the =. Done. > empty comments everywhere.. Removed. Generaly, I use them to mark separation between subpart of a function. > Get rid of disabled code. Done. > Break this long line. Done. > > > +static int start_frame(AVCodecContext *avctx, > > + av_unused const uint8_t *buffer, av_unused uint32_t size) > > That's too long a line. But more importantly, I think you should drop > these unused parameters. I cannot, the start_function prototype comes from AVHWAccel (avcodec.h). I have also: - added an assert() in get_surface_index(). The code can trigger the assert if and only if the avcodec user does not respect the API. - and removed the useless cast in get_surface(). -- fenrir -------------- next part -------------- A non-text attachment was scrubbed... Name: ffmpeg-dxva2-v2.patch Type: text/x-diff Size: 28867 bytes Desc: not available URL: <> | http://ffmpeg.org/pipermail/ffmpeg-devel/2010-January/086400.html | CC-MAIN-2017-30 | refinedweb | 268 | 68.57 |
7 min read
In this ongoing series, I am putting together a Github Repository Template for my "Go To" front-end tech stack of Next.js, React, TypeScript etc. Between the 2nd and 3rd posts in the series, I set up ESLint and Jest Testing to work with TypeScript. In this post, I'm going to introduce path aliases to make our imports cleaner.
Just want the Code? View the full changeset covered in this post or check out the 0.0.4 release of the repository.
If you have ever spent more than 10 seconds trying to figure out where in your directory structure a module you want to import lives relative to the current file, you might need path aliases. If you have import statements that look like the following, path aliases might be for you.
import ('../../../../src/components/layout/CoolComponent')
While you can create lots of aliases, I tend to just want one to leverage absolute imports of things in my /src folder. As such, the above contrived import would become:
import ('~/components/layout/CoolComponent')
That feels nicer. Let's make it happen. Oh and I want to make sure ESLint and Jest testing continue to work as well.
If you are following along, please complete part 3 of the series. I am immediately picking up where that post left off. Note: I accidentally, left an easter egg in my Jest config in the 0.0.3 release that will make things smoother later. I'll call it out when I get to that step below to avoid confusion.
In the previous post, I introduced the /src directory. Remember, Next.js pages, MUST exist in the /pages directory of our project root and every file must export a page component. Because of this, I tend to keep my page components light and have the actual display components live as "screen" components of the /src folder. This also makes them more testable.
Within the /src directory, I'll create a directory called screens. Inside that directory, I'll create a file called IndexContent.tsx with the following content pulled from the existing IndexPage component.
/src/screens/IndexContent.tsx import React from 'react'; interface IndexProps { greeting: string } const IndexContent: React.FC<IndexProps> = (props) => { const { greeting } = props; return ( <div> <h1> {greeting} 👋 ! </h1> </div> ); }; export default IndexContent;
Now I can remove the display logic from the Next.js Index page and let it just be responsible for routing and props resolution, etc. The new /pages/index.tsx file looks like:
/pages/index.tsx import React from 'react'; import { GetStaticProps, NextPage, GetStaticPropsContext, GetStaticPropsResult, } from 'next'; import IndexContent from '../src/screens/IndexContent'; interface IndexProps { greeting: string } const IndexPage:NextPage<IndexProps> = (props: IndexProps) => { const { greeting } = props; return ( <IndexContent greeting={greeting} /> ); }; export const getStaticProps: GetStaticProps = async (context: GetStaticPropsContext): Promise<GetStaticPropsResult<IndexProps>> => ({ props: { greeting: 'Hello Next.js', }, }); export default IndexPage;
Note of the import in pages/index.tsx of the new IndexContent component.
import IndexContent from '../src/screens/IndexContent';
This might not seem terrible, but once I add more directory structure, it can get ugly pretty quick.
Again, I'm just going to create a simple alias for for the /src directory so I can have absolute imports. I will use the ~ (tilde) symbol to be an alias for the /src directory. To do this, I need to simply add the following to the compilerOptions in the tsconfig.json:
"compilerOptions": { ... "baseUrl": ".", "paths": { "~/*": ["./src/*"], } ...
At this point, the tsconfig.json should look like this.
Next I'll update the pages/index.tsx file to leverage the new import.
/pages/index.tsx import React from 'react'; ... import IndexContent from '~/screens/IndexContent'; ...
At this point, if when I restart your dev server via
npm run dev the page works as expected.
This works because Next.js plays well with TypeScript and tells the underlying Webpack setup to automagically obey directives in tsconfig.json. We are not so lucky with ESLint and Jest.
Even though the Next.js app runs fine with the introduction of aliases, ESLint errors on the aliased path resolution inside of VSCode and when running
npm run lint:
Even though ESLint knows how to deal with TypeScript files, it doesn't obey the paths and baseUrl directive added above to tsconfig.json. Annoyingly, I need one more ESLint plugin to make this happen.
Run the following in the terminal to install the plugin.
npm install --save-dev eslint-import-resolver-typescript
Finally, to use the plugin, I have to update the existing eslintrc.json settings directive specifically TypeScript.
... "settings": { "import/resolver": { "typescript": {}, // this loads <rootdir>/tsconfig.json to eslint "node": { "extensions": [".ts", ".tsx"] } } }, ...
At this point the eslintrc.json looks like this.
Running
npm run lint again, the path errors go away. Also, the errors in the IDE go away as well - although I had to restart the VSCode to have it pick up the changes.
At this point, I'm able to
npm run build and
npm start without any errors, as well. Almost done! One last thing... testing.
Why should the test suite not benefit from aliases as well? Next, I will ensure that Jest plays nicely with path aliases.
As a before comparison, here is the output from
npm run test for the tests introduced in part 3 of this series.
Next, I'll modify /src/utilities/add.test.ts to use our new alias.
import add from '~/utils/add'; ...
The test file should now look like this
When I run
npm run test I receive the following error:
The reason for this error is that Jest doesn't know how to deal with aliases.
Note if you didn't get that error, it is likely because you are following along with the repository. In the 3rd part of the series, I accidentally added the necessary Jest config option to make this work. Feel free to read the next step however, as it is important to understand.
To make Jest understand path aliases, I need to add the following directive to the Jest configuration, which I chose to include in the package.json file in Part 3 of the series.
"jest": { ... "moduleNameMapper": { "~/(.*)$": "<rootDir>/$1" }, ... }
At this point, my package.json looks like this
Now running
npm run test, the tests should pass. Note that coverage is maintained as well!
With the tests passing, I now have alias support for the app, ESLint, and Jest testing!
The Github Project Template is almost ready to be useful - I have a Next.js app written in TypeScript, with ESlint and Jest Testing ready to go, and the benefits of path aliases. View the full changeset covered in this post or check out the 0.0.4 release of the repository. In part 5 of the series, I'll introduce Next.js environment variables and runtime configuration.
Image Credit: "Peaches" by Robbin Gheesling is licensed under CC BY-NC-ND 2.0 | https://hashnode.blainegarrett.com/building-a-github-repo-template-part-4-typescript-path-aliases-ckcpaj01c00688vs1dxqc3kkl?guid=none&deviceId=1338e3b3-1f3f-4870-99a1-bd3aeda95963 | CC-MAIN-2020-34 | refinedweb | 1,145 | 67.55 |
More python commands🤓
The commands have to be
- fun
- interesting
- easy to understand
Got it? Don’t do
boring and not so fun looking not very interesting
So crossed those out.
if you get your answer checked congrats 🎊🎉 you can help on some more asks posts I make
import dis dis.dis(function)
It shows you the Python bytecode of a function, but in a human-readable format. It's really cool to see how Python works on a low level.
WAIT THIS COMMAND DOES NOT WORK maybe because of my spaces when I copy and paste it @ANDREWVOSS
printBlue('text') #print blue colored text or replace the blue
text_to_emoji('text') #convert text to emoji letters
install(name) #check if module installed, if not then pip install it
drawSquare(size) #use turtle to draw square
say('text') #slowtype/typewriter
rainbow('text') -change color of each char
clear() -clear terminal
add(var+var) -add str and number
search('whatever') -search google for result and get first title
take_html(link) -take html from a page and render it using flask
get_cycles(name) -use the replit module to get cycles of user
duplicate_var(name) -use code:
exec(f'{name}1 = name')
Hopefully some of these suggestions are good!
hey
wow did i just see
owoget printed to my terminal
so cool
so fun
so interesting
so easy to understand
Nope 👎 that’s for beginners it’s just trash 🗑 all it does is just prints the word @Coder100
@codermaster8 its a
j o k e
@Coder100 = f u n n y
no ur trash
ur for beginners @codermaster8
Wow how dare ima report this @Coder100
lmao @codermaster8 | https://replit.com/talk/ask/More-python-commands/138610 | CC-MAIN-2021-21 | refinedweb | 273 | 52.16 |
Latest revision as of 20:03, 11 May 2010
Contents
SSSD
System Security Services Daemon (SSSD)
Summary
This project.
Owner
- Name: Stephen Gallagher
- Name: Simo Sorce
Current status
Detailed Description communication to the ldap server will happen over a single persistent connection, reducing the overhead of opening a new socket for each request. The SSSD will also add support for multiple LDAP/NIS domains. It will be possible to connect to two or more LDAP/NIS servers acting as separate user namespaces.
An additional feature of the SSSD will be to provide a service on the system D-BUS called InfoPipe. This service will act as a central authority on extended user information such as face browser images, preferred language, etc. This will replace the existing system consisting predominately of hidden configuration files in the user's home directory, which may not be available if the home directory has not yet been mounted by autofs.
The SSSD is being developed alongside the FreeIPA project. Part of its purpose will be to act as an IPA client to enable features such as machine enrollment and machine policy management. SSSD will provide a back-end to the newly redesigned PolicyKit for central management of policy decisions.
Benefit to Fedora
- Laptop users will have offline access to their network logons, eliminating the need for local laptop accounts when traveling.
- Desktop developers will have access to the new InfoPipe, allowing them to migrate towards using a more consistent approach for storing and retrieving extended user information.
- The SSSD will simplify enrollment into FreeIPA network domains, as it will provide the FreeIPA client software.
- The design of the SSSD will allow other services such as LDAP, NIS and FreeIPA to take advantage of the caching and offline features.
User Experience
Users will be able to authenticate to their network logons while not connected to the network. Additionally, joining a machine to a FreeIPA domain should be markedly simpler.
Administrators will be able to configure a machine to authenticate against more than one LDAP server/domain.
Dependencies
Additional components of the FreeIPA client will be dependent on this feature, however they are being developed concurrently and should not be negatively impacted. The SSSD will have dependencies on glibc, D-BUS, libtalloc, libtevent, libtdb and libldb. At the time of this writing, we do not foresee any of these packages affecting our release.
Soft co-dependency on PolicyKit 1.0
Contingency Plan
We will complete the NSS and PAM portions of the SSSD first. If time does not permit completion of the additional components, they will be deferred to Fedora 12. In the unlikely event that the NSS and PAM portions of the SSSD are not ready for Fedora 11, they can be omitted with no harm to the release.
Documentation
Design Document on FreeIPA.org | https://fedoraproject.org/w/index.php?title=Features/SSSD&diff=173015&oldid=72247 | CC-MAIN-2018-26 | refinedweb | 469 | 52.9 |
NAME
shmat, shmdt -- attach or detach shared memory
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <machine/param.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> void * shmat(int shmid, const void *addr, int flag); int shmdt(const void *addr);
DESCRIPTION
The shmat() system call attaches the shared memory segment identified by shmid to the calling process's address space. The address where the segment is attached is determined as follows: +o If addr is 0, the segment is attached at an address selected by the kernel. +o If addr is nonzero and SHM_RND is not specified in flag, the segment is attached the specified address. +o If addr is specified and SHM_RND is specified, addr is rounded down to the nearest multiple of SHMLBA. The shmdt() system call detaches the shared memory segment at the address specified by addr from the calling process's address space.
RETURN VALUES
Upon success, shmat() returns the address where the segment is attached; otherwise, -1 is returned and errno is set to indicate the error. The shmdt() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.
ERRORS
The shmat() system call will fail if: [EINVAL] No shared memory segment was found corresponding to shmid. [EINVAL] The addr argument was not an acceptable address. The shmdt() system call will fail if: [EINVAL] The addr argument does not point to a shared memory segment.
SEE ALSO
shmctl(2), shmget(2) | http://manpages.ubuntu.com/manpages/precise/en/man2/shmdt.2freebsd.html | CC-MAIN-2015-14 | refinedweb | 255 | 55.13 |
Hello, Dmitriy. You write 23 мая 2008 г., 23:48:56: DSS> Hello, J.. DSS> You write 23 мая 2008 г., 0:18:11:
JS>> On Thu, May 22, 2008 at 10:05 AM, Dmitriy S. Sinyavskiy <[EMAIL PROTECTED]> wrote: >>> >>> People? what about my patch? I heven't got received any response. >>> I'll be glad to now some news. >>> Thanks. >>> JS>> Your mailserver is rejecting mail. I suggest fixing your mail server JS>> or viewing the list archives to make sure that you're not missing JS>> things. JS>> Thread: JS>> DSS> Test. Must be saved as UTF-8: DSS> ================================= DSS> use strict; DSS> use warnings; DSS> use Test::More 'no_plan'; DSS> use URI; DSS> use_ok('Catalyst'); DSS> my $request = Catalyst::Request->new( { base =>> URI->new('') DSS> } ); DSS> my $context = Catalyst->new( { request =>> $request, namespace =>> 'yada', DSS> } ); DSS> # test encode first argument with utf-8, DSS> { $request->>base( URI->new('') ); $context->>namespace(''); DSS> is( Catalyst::uri_for( $context, '/animal/ёж', 'чёт', { param1 => "щуп" })->as_string, DSS> '', DSS> 'URI for undef action with first param as string in unicode' DSS> ); DSS> } The previous test was wrong, sorry. I've found a mistake and correct it. Test case including check for special chars <?>. Tested today - it's working right with patch. Test ============= use strict; use warnings; use Test::More 'no_plan'; use URI; use_ok('Catalyst'); my $request = Catalyst::Request->new( { base => URI->new('') } ); my $context = Catalyst->new( { request => $request, namespace => 'yada', } ); # test encode first argument with utf-8, { $request->base( URI->new('') ); $context->namespace(''); is( Catalyst::uri_for( $context, '/animal/ёж', 'чёт', { param1 => "щуп" })->as_string, '', 'URI for with first param as string in unicode' ); is( Catalyst::uri_for( $context, '/??', '?', { param1 => "?" })->as_string, '', 'URI for with special char <?> in args and param' ); } --: | https://www.mail-archive.com/catalyst@lists.scsys.co.uk/msg03247.html | CC-MAIN-2022-27 | refinedweb | 284 | 74.39 |
Important: Please read the Qt Code of Conduct -
Standart keyboard on touch screen
I'v got some problem when using desktop app on touch screen (Windows 7). Problem is there is no pop-up virtual keyboard when focus reached any input widget (like QLineEdit, QSpinBox and etc).
I'm using Qt 5.8 and simple app with QWidgets.
This is all code i got now
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) {
ui->setupUi(this);
}
MainWindow::~MainWindow() {
delete ui;
}
and i get no pop-up keyboard!
But what i wanna see is smth like this (QFileDialog was called):
Question is : is there any easy way to configure widgets to get such standart keyboard behavior?
@Annili said in Standart keyboard on touch screen:
I'm using Qt 5.8 and simple app with QWidgets.
With QWidgets there is no "standard way". you can take a look at but if you even start thinking about internationalise it you realise it's just not feasible
See also:
@VRonin as far as i know, on windows 10 such system osk pops up automaticly when focus is on input widget. thats why im concern that is gotta be such easy way to show this keyboard. | https://forum.qt.io/topic/78113/standart-keyboard-on-touch-screen | CC-MAIN-2021-43 | refinedweb | 209 | 65.01 |
Ok so Im trying to create a constructor that reads input from a text file. Which I got it to do. Then adds the information to a LinkedList.
public class CourseCatalog<T> { private BufferedReader read; private LinkedList<Course> catalog; public CourseCatalog(String filename) throws FileNotFoundException { catalog = new LinkedList<Course>(); try { //Construct the BufferedReader object this.read = new BufferedReader(new FileReader(filename)); String line = null; while ((line = read.readLine()) != null) { if(line.contains("Course")){ //Process the data System.out.println(line); } } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the BufferedReader try { if (read != null) read.close(); } catch (IOException ex) { ex.printStackTrace(); } }
The text file contains a bunch of differnt courses like this.
Ex:
Course: MAT 1214
Title: Calculus I
Prerequisite: none
Course: MAT 1224
Title: Calculus II
Prerequisite: MAT 1214
So my code right now just reads the .txt file and outputs whats in it. Anybody have any suggestions or could point me in the right direction of how I would go about adding that information to a LinkedList<Course>. The constructor of my Course class looks like this.
public Course(String dep, int num, String title) { department = dep; coursenumber = num; coursetitle = title; prerequisites = new LinkedList<String>(); subsequents = new LinkedList<String>(); } | https://www.daniweb.com/programming/software-development/threads/323163/how-do-you-add-string-input-from-a-text-to-a-linked-list | CC-MAIN-2017-43 | refinedweb | 205 | 59.9 |
State!)
var million = 10000000; // no digit separators var million = 10_000_000; // digit separators added
ReSharper has a quick-fix which lets us add digit separators to any numeric literal:
Note that ReSharper adds digit separators at the expected location (thousands separator), but it’s perfectly possible to place them anywhere in a number:
var number = 17_15_1337;
Digit separators also are a language onramp for binary literals. It’s now possible to specify bit patterns directly instead of having to know hexadecimal notation by heart.
byte b = 0b1010_1011;:
public static int Factorial(int number) { int Multiply (int num) { return (num == 1) ? 1 : num * Multiply(num - 1); } return Multiply(number); }:
int number; if (int.TryParse("42", out number)) { // ... work with number ... }
C# 7 introduces output variables, making it possible to declare a variable right at the point where we’re making our method call:
if (int.TryParse("42", out int number)) { // ... work with number ... }or
while, this does not happen though.
while(int.TryParse(Console.ReadLine(), out int x)) { // ... } Console.WriteLine(x); // <-- x not available:
public (string, string) FindPersonName(int id) { // ... lookup data ... return (firstName, lastName); }
Or in VB.NET:
Public Function FindPersonName(Id As Integer) As (String, String) '... lookup data ... Return (FirstName, LastName) End Function
The calling code will get back a tuple with two string properties, which we can then work with:
var personNames = FindPersonName(123); var firstName = personNames.Item1; var lastName = personNames.Item2;
That’s… nice, but not very. We’re still using
Item1and
Item2here. Again, C# 7 and VB.NET 15 to the rescue! We can update our
FindPersonNamemethod and name our tuple elements:
public (string FirstName, string LastName) FindPersonName(int id) { // ... lookup data ... return (firstName, lastName); }
The consuming code could now look like this:
var personNames = FindPersonName(123); var firstName = personNames.FirstName; var lastName = personNames.LastName;directive,:
(string firstName, string lastName) = FindPersonName(123); // ... work with firstName and lastName ...
Deconstruction not only works for tuples. It works for any type, as long as that type implements the
Deconstructmethod, either directly or via an extension method. For example, we could write an extension method for
KeyValuePair<TKey, TValue>which lets us use the key and value directly – avoiding having to use
.Key/
.Valueexpressions.
// Extension method public static class KVPExtensions { public static void Deconstruct<TKey, TValue>( this KeyValuePair<TKey, TValue> kvp, out TKey key, out TValue value) { key = kvp.Key; value = kvp.Value; } } // Consuming a dictionary foreach (var (key, value) in dictionary) { var item = $"{key} => {value}"; }
We can add multiple overloads for the
Deconstructmethod,:
public void Dump(object data) { if (data is null) return; if (data is int i) Console.WriteLine($"Integer: {i}"); if (data is float f) Console.WriteLine($"Float: {f}"); }
In the above sample, we are doing several pattern matches. A constant pattern match checks whether
datais
null. The next two checks are type pattern matches, testing
datah:
if (data is int i || (data is string s && int.TryParse(s, out i)) { // ... use i here ... }
ReSharper 2016.3 already partially supports pattern matching for
isexpressions and
switchstatements, although we’re still working on supporting a really nice feature of pattern matching where we can write code that checks for type information as well as specific property values using the
whenkeyword:
switch (vehicle) { case Car lada when (lada.Make == "Lada"): Console.WriteLine("<Lada car>"); break; case Car car: Console.WriteLine("<generic car>"); break; case Van van: Console.WriteLine("<generic van>"); break; default: Console.WriteLine("<unknown vehicle>"); break; case null: throw new ArgumentNullException(nameof(vehicle)); }
ReSharper does not yet fully understand this syntax – we’re working on that and looking at making our existing code inspections and quick-fixes aware of new C# 7 syntax. We’ll have to recognize
x is nullas a null check, suggest using an
isexpression instead of an
as+
nullcheck, ….
class Employee { public string Name { get; } public Employee(string name) => Name = name ?? throw new ArgumentNullException(nameof(name)); }
In our code we could already pass variables by reference (using
ref/
ByRef). C# 7.0 and VB.NET 15 now also let us return from a method by reference.
public ref int Find(int number, int[] numbers); // return reference ref int index = ref Find(7, new[] { 1, 2, 3, 7, 9, 12 }); // use reference
Default Public ReadOnly Property Item(index As Integer) As ByRef Integer
Support for
ref/
ByRefreturns!
6 Responses to State of the union: ReSharper C# 7 and VB.NET 15 support
Marcel Bradea says:February 18, 2017!
Maarten Balliauw says:February 19, 2017
Thanks! 🙂:
smad says:February 20, 2017
2017.1 Eap 2 still have old logo from 2016.3.
Maarten Balliauw says:February 21, 2017
Good catch! Thanks 🙂
obe says:March 14, 2017
Any chance to get multi-caret support in ReSharper?
That would be awesome.
Kornel says:March 20, 2017) | https://blog.jetbrains.com/dotnet/2017/02/17/state-union-resharper-c-7-vb-net-15-support/ | CC-MAIN-2021-43 | refinedweb | 787 | 59.09 |
Contents tagged with WebService
Dynamic URL of asp.net web service with web reference.
Interview questions about ASP.NET Web services.
I have seen there are lots of myth’s about asp.net web services in fresher level asp.net developers. So I decided to write a blog post about asp.net web services interview questions. Because I think this is the best way to reach fresher asp.net developers. Followings are few.
4) Explain web method attributes in web services
Ans: Web method attributes are added to a public class method to indicate that this method is exposed as a part of XML web services. You can have multiple web methods in a class. But it should be having public attributes as it will be exposed as xml web service part. You can find more information about web method attributes from following link.
5) What is SOA?
Ans: SOA stands for “Services Oriented Architecture”. It is kind of service oriented architecture used to support different kind of computing platforms and applications. Web services in asp.net are one of the technologies that supports that kind of architecture. You can call asp.net web services from any computing platforms and applications.
6) What is SOAP,WDSL and UDDI?
Ans: SOAP stands “Simple Object Access protocol”. Web services will be interact with SOAP messages written in XML. SOAP is sometimes referred as “data wrapper” or “data envelope”.Its contains different xml tag that creates a whole SOAP message. WSDL stand for “Web services Description Language”. It is an xml document which is written according to standard specified by W3c. It is a kind of manual or document that describes how we can use and consume web service. Web services development software processes the WSDL document and generates SOAP messages that are needed for specific web service. UDDI stand for “Universal Discovery, Description and Integration”. Its is used for web services registries. You can find addresses of web services from UDDI.
Working with more then one web.config files in asp.net application.
Recently one of reader of my blog how we can work with more then one web.config files in asp.net application. So I decided to blog about that. Here is the my reply for that.
You can work with more then one web.config file in asp.net. But you can not put more then one web.config in each folder. Let’s first understand the hierarchy of web.config and other configuration file settings. On the top of the every configuration files you will have machine.config file which will have all system wide configuration settings.You can find this file in your OS drive like C: /windows/Microsoft.NET/vFrameworkNumber/Config folder. Here framework number with what ever framework you are using 1.1/2.0 or 4.0. You can override those settings in web.config file at the your application root folder. Same way you can add more web.config file in subfolder and can override the setting of parent folder web.config file. So we will hierarchy like below.
Now let’s Create Project for it. In that I have create two web.config and 2 pages. First I have putted the web.config in root folder and then I have putted web.config in subfolder. Same way I have created a sub folder and then I have putted the web.config in sub folder. I have also putted one asp.net page in root as well as subfolder to use respective web.config settings. Here are my folder structure like below.
Below is code for root folder web.config
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <appSettings> <add key="root" value="This is from root web.config"></add> <add key="MySetting" value="This my settings is from root web.config"></add> </appSettings> </configuration>
and following is code for sub folder web.config.
<?xml version="1.0"?> <configuration> <system.web> </system.web> <appSettings> <add key="sub" value="This is from sub web.config settings"></add> <add key="MySetting" value="This my settings is from sub folder web.config"></add> </appSettings> </configuration>
After that I have written a code in root asp.net page to print settings from web.config folder like this following.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MoreWebConfig { public partial class Root : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Root")); Response.Write("<BR>"); Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("MySetting")); } } }
Same way I have wrriten code in subfolder like following.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MoreWebConfig.SubFolder { public partial class SubFolderPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Sub")); Response.Write("<BR>"); Response.Write(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("MySetting")); } } }
Now let’s run the both pages in browser one by one and you can see root folder application page is fetching settings from root folder web.config while sub folder application page is fetching setting from subfolder web.config even if key ‘mysetting’ is same on both as expected. You can see out put in browser below.
Root.aspx
SubFolderPage.aspx
So it’s very easy to work with multiple web.config. The only limitation of this you can not access sub folder web.config settings from root folder page. Except all you can use anything. Hope you liked it. Stay tuned for more..Happy programming..Technorati Tags: web.config,ASP.NET
Converting a generic list into JSON string and then handling it in java script
We all know that JSON (JavaScript Object Notation) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script.
To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName
public class UserInfo
{
public int UserId { get; set; }
public string UserName { get; set; }
}
Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace Experiment.WebService
{
/// <summary>
/// Summary description for WsApplicationUser
/// < WsApplicationUser : System.Web.Services.WebService
{
[WebMethod]
public string GetUserList()
{
List<UserInfo> userList = new List<UserInfo>();
for (int i = 1; i <= 5; i++)
{
UserInfo userInfo = new UserInfo();
userInfo.UserId = i;
userInfo.UserName = string.Format("{0}{1}", "J", i.ToString());
userList.Add(userInfo);
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(userList);
}
}
}
Note: Here you must have this attribute here in web service class ‘[System.Web.Script.Services.ScriptService]’ as this attribute will enable web service to call from client side.
Now we have created a web service class let’s create a java script function ‘GetUserList’ which will call web service from JavaScript like following
function GetUserList() {
Experiment.WebService.WsApplicationUser.GetUserList(ReuqestCompleteCallback, RequestFailedCallback);
}
After as you can see we have inserted two call back function ReuqestCompleteCallback and RequestFailedCallback which handle errors and result from web service. ReuqestCompleteCallback will handle result of web service and if and error comes then RequestFailedCallback will print the error. Following is code for both function.
function ReuqestCompleteCallback(result) {
result = eval(result);
var divResult = document.getElementById("divUserList");
CreateUserListTable("divUserList");
divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" +
"Service Error: " + message + "<br/>" +
"Status Code: " + statusCode + "<br/>" +
"Exception Type: " + exceptionType + "<br/>" +
"Timedout: " + timedout;
}
Here in above there is a function called you can see that we have use ‘eval’ function which parse string in enumerable form. Then we are calling a function call ‘CreateUserListTable’ which will create a table string and paste string in the a div. Here is code for that function.
function CreateUserListTable(userList) {
var tablestring = '<table ><tr><td>UsreID</td><td>UserName</td></tr>';
for (var i = 0, len = userList.length; i < len; ++i)
{
tablestring=tablestring + "<tr>";
tablestring=tablestring + "<td>" + userList[i].UserId + "</td>";
tablestring=tablestring + "<td>" + userList[i].UserName + "</td>";
tablestring=tablestring + "</tr>";
}
tablestring = tablestring + "</table>";
var divResult = document.getElementById("divUserList");
divResult.innerHTML = tablestring;
}
Now let’s create div which will have all html that is generated from this function. Here is code of my web page. We also need to add a script reference to enable web service from client side. Here is all HTML code we have.
<form id="form1" runat="server">
<asp:ScriptManager
<Services>
<asp:ServiceReference
</Services>
</asp:ScriptManager>
<div id="divUserList">
</div>
</form>
Now as we have not defined where we are going to call ‘GetUserList’ function so let’s call this function on windows onload event of javascript like following.
window.onload=GetUserList();
That’s it. Now let’s run it on browser to see whether it’s work or not and here is the output in browser as expected.
That’s it. This was very basic example but you can crate your own JavaScript enabled grid from this and you can see possibilities are unlimited here. Stay tuned for more.. Happy programming..Technorati Tags: JSON,Javascript,ASP.NET,WebService
Request format is unrecognized for URL unexpectedly ending exception in web service.
Recently!!!Technorati Tags: WCF,WebService,ASP.NET
Calling an asp.net web service from jQueryMessage()
{
return "Hello World..This is from webservice";
}
}
Here please make sure that [System.Web.Script.Services.ScriptService] is un commented because this attribute is responsible for allowing web service to be called by Client side scripts.
Now to call this web service from jquery we have to include jQuery Js like following. I am already having in my project so i don’t need to include in project just need to add script tag like following.
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js">
</script>
Now let’s add some JavaScript code to call web service methods like following.
<script language="javascript" type="text/javascript">
function CallWebServiceFromJquery() {
$.ajax({
type: "POST",
url: "HelloWorld.asmx/PrintMessage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
});
}
function OnSuccess(data, status)
{
alert(data.d);
}
function OnError(request, status, error)
{
alert(request.statusText);
}
</script>
Here I have written three functions in JavaScript First one is CallWebserviceFromJquery which will call the web service. The another two functions are delegates of web service if Success is there then onSuccess Method will be called and If Error is there then OnError method will be called.
Inside the CallWebserviceFromJquery I have passed some parameter which will call web service with Ajax capabilities of $ jQuery object. Here are the description for each parameter.
Type: This can be GET or POST for web service we have to take POST as by default web service does not work with GET to prevent Cross site requests.
Url: Here will be url of the web service. You have insert fully qualified web service name here.
Data:Here it will be Empty as we not calling web service with parameters if you are calling web service with parameter then you have to pass that here.
contentType: here you have to specify what type of content is going to return by web service.
datatype:Json it will be result type
sucess:Here I have called the OnSuccess when the call is complete successfully. If you check the OnSuccess method you will see that I have set the returned result from the web service to the label. In the OnSuccess method body you see ‘data.d’. The ‘d’ here is the short form of data.
Error: Same as I have done with OnSuccess. If any error occurred while retrieving the data then the OnError method is invoked.
Now let’s add a asp.net button for on client click we will call the javascript function like following.
<asp:Button
Now Let’s run it and here is the output in browser.
Hope this will help you!!!.. Happy programming..Technorati Tags: jQuery,WEbService,ASP.NET,ClientScript
How to add service reference dynamically from user control? Microsoft Ajax
First,);
}
'-------------------------------------------------------------------------- | http://weblogs.asp.net/jalpeshpvadgama/Tags/WebService | CC-MAIN-2016-07 | refinedweb | 2,097 | 52.76 |
Opened 3 years ago
Closed 3 years ago
#20521 closed New feature (wontfix)
{% local_url %} to extend {% url %} with instrospection of the rendering app
Description
==Summary==
New feature: use app's directory tree to resolve urls on templates.
==Motivation==
Currently the {% url %} tag requires the full path of the view or a url name to reverse the correct url of the view. This is limited due to either url name collisions or app's name collision.
To avoid url collisions, django implements a URL namespace, which has to be applied on each app coded to be reusable. One of the biggest problems of the current implementation is the difficultly in using the URL namespace for practical proposes: it is mainly used and (limited to) the case where the same app is being deployed on the same site more than one time.
==Proposal==
I here propose a new templatetag, {% local_url %} and a shortcut to a render, "local_render", that solves the url resolving issue, and does not collide with the current django state.
It works as follows: the local_render passes the argument 'current_app' to the django's render (shortcuts.render) with the full path of the app (package.package.(...)). The {% local_url %} then resolves the url according to the current_app. It is basically a copy of the tag {% url %}, where the "render" of the node is slightly different:
# if the context does not have current_app (case where current_app is not used), render normally
# if the context has current_app (e.g. here 'main.main1.main2'):
try to render with view_name as main.main1.main2.view_name
if NoReverseMatch, try to render with self.view_name=main.main1.main2.view_name
if NoReverseMatch, try to render with self.view_name=main.main1.view_name
if NoReverseMatch, try to render with self.view_name=main.view_name
if NoReverseMatch, try to render with self.view_name=view_name
if NoReverseMatch, raise NoReverseMatch
where view_name is the argument passed in init to self.view_name.
I.e. this basically implements a resolver that works over the app's path.
==Discussion==
- Neither the render nor the tag collide with current implementation (as far as I understood, the current_app is never passed as argument to the url resolver in the {% url %} tag).
- This deprecate the need of URL namespaces for working with templates: the strategy to resolve URL in templates is with this approach according to the directory structure, and apps must have different names inside a directory.
- This agrees with django's spirit of using app's as reusable and modules that complement other app's.
- This allows for views "overload": Consider a child app that is installed on top of a parent which has a view (e.g. views.rules) and a template with {% local_url views.rules %}. The child decides to extend the template (for instance for using the same footers or headers. The child can define a view with the same name (rules) which overloads the parent's view: if the render is called from the child, it uses the view, if it is called from the parent, it is the parent's view. This is the same behavior one would obtain for python classes: the child can always overload a parent's method.
- This idea can be extended to URL resolvers in general, but that requires a major design decision that I don't want to enter for now.
I already have a code which reproduces the behavior I'm suggesting, which I use for a project of mine. I will wait for approach/criticisms to see if it deserves be written in django's standards.
I'm going to mark this wontfix, for two reasons:
I'm not claiming you don't (or shouldn't) have a problem in your own code. I'm just questioning whether the problem is so widespread that it warrants the introduction of a second parallel URL reversal scheme.
There might be some merit to your idea of using current_app inside the existing url reversal tools; however, the implementation and consequences of that change would need to be elaborated some more.
If this is an idea you're passionate about, I suggest taking it to django-developers for further discussion. We don't discuss new features on tickets because of the lack of visibility of the discussion. In that discussion, I suggest you spend a lot more time explaining the set of conditions that have led to you getting regular URL name collisions. | https://code.djangoproject.com/ticket/20521 | CC-MAIN-2016-40 | refinedweb | 733 | 59.53 |
#include <fcntl.h>
The flags for the F_GETFL and F_SETFL flags are as follows: */ int l_sysid; /* remote system id or zero for local */ };The commands available for advisory record locking are as follows:,..
The queuing for F_SETLKW requests on local files is fair; that is, while the thread is blocked, subsequent requests conflicting with its requests will not be granted, even if these requests do not conflict with existing locks.
This interface follows the completely stupid semantics of System V and IEEE Std 1003.1-88 ().
Otherwise, a value of -1 is returned and errno is set to indicate the error. reasons as stated in tcgetpgrp(3).
Per -susv4, a call with F_SETLKW should fail with [EINTR] after any caught signal and should continue waiting during thread suspension such as a stop signal. However, in this implementation a call with F_SETLKW is restarted after catching a signal with a SA_RESTART handler or a thread suspension such as a stop signal.
The F_DUP2FD constant first appeared in FreeBSD 7.1 .
Please direct any comments about this manual page service to Ben Bullock. | https://nxmnpg.lemoda.net/2/fcntl | CC-MAIN-2019-13 | refinedweb | 181 | 60.04 |
Type inference
From Nemerle Homepage
MSc thesis
The theoretical model of Nemerle is described in my MSc thesis. This page explains this from a more practical standpoint, though reading at least the first chapters of the thesis wouldn't hurt.
Bottom up type inference
Most languages, even plain good ol' C, support a form of bottom up type inference. It happens when you have an expression, let's say a function call f() and f's return type is int, then we know the type of f() is int. A more involved example would be Singleton of type T -> Set[T] (that is Singleton is a function taking element of type T and returning Set[T]). Then Singleton(f()) clearly has type Set[int]. This example is more interesting as the type of function call depends on types of arguments.
From this kind of reasoning there is only a single little step to allowing:
def s = Singleton (f ());
instead of:
Set<T> s = Singleton (f ());
That is omitting types of local variable declaration.
You can even do this in GCC compiling C++ (or C, but as it lacks templates it doesn't make much sense):
#define DEF(v,e) __typeof(e) v = e int main (void) { DEF(x, 21 + 21); return x; }
Free type variables
The situation becomes more involved when there are type parameters that are used in return type but not in type of function parameters. For example consider MakeSet function returning Set[T] and taking no arguments.
def s = MakeSet ();
And what type does s have? It is Set[T] for some T. We do not yet know what kind of set will it be. But after adding next line with s usage:
def s = MakeSet (); s.Add (42);
we know that T is int, because we have added element of type int to it. In fact we know this because Set[T].Add has type T -> void.
Such yet unknown types are called free type variables. They are free, that is yet-unbound, they are type variables so real types can be put in place of them later.
Nemerle type inference engine very often produces such type variables just to kill them a moment later by replacing them with a real type.
Note that type variables are not exactly type parameters used in method definition. The difference is that we need a fresh copy of all type parameters upon each call. And this copy is called free type variable. Otherwise we couldn't say:
def s1 = MakeSet (); def s2 = MakeSet (); s1.Add (42); s2.Add ("42");
But with fresh copies used each time we have s1 : Set[T1] and s2 : Set[T2] and everything is OK.
Constraints
Let's have a look at the following classes:
class BaseClass {} class Derived1 : BaseClass {} class Derived2 : BaseClass {}
Now we create a set and add an element:
def s = MakeSet (); s.Add (Derived1 ()); // add a new Derived1 instance
After this we should know, like in the int-example above, that s has type Set[Derived1]. But such conclusion would be premature, because we may want to:
s.Add (Derived2 ());
This is all OK, as long as we consider s to be of type Set[BaseClass]. Clearly if programmer adds Derived1 and later Derived2 then the intention was to have a set of BaseClass.
Therefore we cannot eagerly replace T with Derived1 upon first usage. Instead of this we just place a constrain that T have to be a supertype of Derived1. Next we place additional constrain that T is supertype of Derived2. Now because all supertypes of both Derived1 and Derived2 are also supertypes of BaseClass we can simplify these two constraints to a single one stating that T is a supertype of BaseClass.
Other sources of free type variables
There are other places where free type variables can be introduced. For example the null literal does it (in fact it additionally adds anti-value-type constraint), but probably the most interesting of such places are function parameters.
Nemerle supports type inference for parameters of local functions (that is functions defined and visible only inside some other function). We plan to extend this to private class members, there are no conceptual problems here, only implementation will be hard.
For example:
def foo (x) { x + 3 }
We first assign a free type variable as the type of x, and later infer, probably a bit too eagerly, that x has type int, because it is added to 3.
Deferral
There are some more problems with free type variables. For example:
def foo (x) { x + x }
After seeing such a definition we do not know what type should x have. Would it be an int? A double? A string? This is because the addition operator is overloaded, it has more than one signature.
So we cannot type such a definition alone. But hey, who defines a function not to use it at all [1]? If we have this definition and usage like foo ("42") we know that x is string, therefore the + overload to be chosen is string * string -> string and therefore the return type of foo is also string.
Now, because we can assign only one type to x in the generated code, if after foo ("42") user writes foo (42.0), then we report an error. This is however not a problem in most circumstances.
Similar reasoning can be applied to:
def get_length (x) { x.Length }
We cannot know what type does x.Length have, or even if it's valid at all until we know the type x. But we can tell it again by looking at the function usage get_length (array [1,2]).
What exactly compiler does?
Of course it is easy to say we look at, we can deduce, but the compiler requires somehow stricter algorithm. The basic idea here is that the compiler proceeds with type inference in the top-down, left-right order, until it sees something it cannot handle. Examples of such things include:
- a member reference on an expression with yet unknown type
- overloaded call, that still has more than one maximally specific solution
- call to operator on operands with unknown types (because resolution rules for operators depend on types of operands)
- a indexer reference on expression with unknown type
- a situation when a macro decides that it doesn't yet have enough information (this is macro-specific, for example the foreach macro needs to known the type of the collection it is iterating over)
When such a situation is found, a special place-holder is put into the resulting tree and appropriate action is put into FIFO queue of delayed typings. This placeholder has a yet-unknown type, which can lead to more delayed typings, when it is used.
Once the entire typing process for a method is over, we look into our FIFO queue. We try to ask each action in it, to resolve itself. When it succeeds, it is removed from the queue, otherwise it is added again. When we process each of the elements initially in the queue, we check if the queue is empty. If it is, we have succeeded.
Otherwise, we check if we did resolve something, and if so, we start the queue iteration process again (because resolution of an expression can make resolution of some other expression possible).
If we didn't resolve anything, we ask the first element in the queue to explain to the user why did it fail. This also happens to be the first failed expression in the source program order, so the error reported is the top-most one. | http://nemerle.org/Type_inference | crawl-002 | refinedweb | 1,268 | 69.82 |
(2012-03-18 01:55)hams1000 Wrote: This is awesome. Maybe it's my skin , but ShareSocial renders my timeline in all caps.
(2012-03-18 02:48)ruuk Wrote: (2012-03-18 01:55)hams1000 Wrote: This is awesome. Maybe it's my skin , but ShareSocial renders my timeline in all caps.
Yeah, that would be the skin. What skin btw?
While I don't have the time to make custom addon skins for every XBMC skin out there, I might be able to add some code that tries to modify the addon's font to match the fonts of the current skin. As it is, if the font name the addon uses is not a font name the skin uses (and this is often the case) then the skin's default font is used.
(2012-03-18 20:43)hams1000 Wrote: I can't believe no one has commented on this yet. I for one want to see more info gathering addons like this. Sadly I'm not much help because I only use the twitter part of if. For displaying my timeline it's fantastic. Wouldn't mind being able to fire off a non media related tweet, I never really post what I'm watching. I do wonder if you can get embed.ly to work for embedded images.
(2012-03-19 17:03)rflores2323 Wrote: is this on a repo anywhere so that it can autoupdate?
(2012-03-20 05:49)Bstrdsmkr Wrote: Looking pretty awesome. I'm having a little trouble deciphering the intent behind some of the functions though. Let's say I have one of my list items that points to.
What would I need to feed to RunScript() in order to let a user share that link on Twitter?
import ShareSocial
share = ShareSocial.getShare('add.on.id','video')
share.media = ''
share.thumbnail = ''
share.title = 'appropriate title'
share.page = 'link to page media is hosted on'
share.share()
data = share.toString()
share = ShareSocial.Share().fromString(data)
share.share() | http://forum.xbmc.org/showthread.php?tid=125837&pid=1048641 | CC-MAIN-2013-48 | refinedweb | 336 | 76.82 |
This section describes how to use system services to perform the
following tasks:
To add address space at the end of P0, P1, P2 or a user created region,
use the 64-bit Expand Region (SYS$EXPREG_64) system service.
SYS$EXPREG_64 returns the range of virtual addresses for the new pages.
To add address space in other portions of P0, P1, P2 or user created
virtual regions, use SYS$CRETVA_64.
The format for SYS$EXPREG_64 is as follows:
The following example illustrates the addition of 4 pagelets to the
64-bit program region of a process by writing a call to the
SYS$EXPREG_64 system service.
#define __NEW_STARTLET 1
#pragma pointer_size 64
#include <gen64def.h>
#include <stdio.h>
#include <ssdef.h>
#include <starlet.h>
#include <vadef.h>
int main (void) {
int status;
GENERIC_64 region_id = {VA$C_P2};
void * start_va;
unsigned __int64 length;
unsigned int pagcnt = 4;
/* Add 4 pagelets to P0 space */
status = sys$expreg_64 (®ion_id, pagcnt*512, 0, 0, &start_va, &length);
if (( status&1) != 1)
LIB$SIGNAL( status);
else
printf ("Starting address %016LX Length %016LX'n", start_va, length);
}
The value VA$C_P2 is passed in the region_id argument
to specify that the pages are to be added to the 64-bit program region.
To add the same number of pages to the 32-bit program region, you would
specify VA$C_P0. To add pages to the control region, you would specify
VA$C_P1. To add pages to a user created virtual region, you would
specify the region_id returned by the
SYS$CREATE_REGION_64 system service.
On Alpha and I64 systems the SYS$EXPREG_64 system service can add
pagelets only in the direction of the growth of a particular region.
12.3.2 Increasing and Decreasing Virtual Address Space with 32-bit System Services
pagelets to add to the end of the region. The Alpha and I64 systems
round the specified pagelet value to the next integral number of.5 mentions some other possible risks in using SYS$CRETVA
for allocating memory.
12.3.3 Input Address Arrays and Return Address Arrays for the 64-Bit System Services
When the SYS$EXPREG_64 system service adds pages to a region, it adds
them in the normal direction of growth for the region. The return
address always indicates the lowest-addressed byte in the added address
range. To calculate the highest-addressed byte in the added address
range, add the returned length to the returned address and subtract 1.
When the SYS$DELTVA_64 system service deletes pages from a region, it
deletes them in the opposite direction of growth for the region. The
return address always indicates the lowest-addressed byte in the
deleted address range. To calculate the highest-addressed byte in the
deleted address range, add the returned length to the returned address
and subtract 1. and I64-2 shows the page size and byte offset.
Table 12-3 shows some sample virtual addresses in hexadecimal that
may be specified as input to SYS$CRETVA or SYS$DELTVA and shows the
return address arrays if all pages are successfully added or deleted.
Table 12-3 assumes a page size of 8 KB = 2000 hex.
For SYS$CRETVA and SYS$DELTVA, note that if the input virtual addresses
are the same, as in the fourth and fifth items in Table 12-3, a
single page is added or deleted. The return address array indicates
that the page was added or deleted in the normal direction of growth
for the region.
Note that for SYS$CRMPSC and SYS$MGBLSC, which are discussed in
Section 12.3.9, the sample virtual address arrays in Table 12-3 and I64.6 Page Ownership and Protection
Each page in the virtual address space of a process is owned by the
access mode that created the page. For example, pages in the program
region that initially provided for the execution of an image are owned
by user mode. Pages that the image creates dynamically are also owned
by user mode. Pages in the control region, except for the pages
containing the user stack, are normally owned by more privileged access
modes.
Only the owner access mode or a more privileged access mode can delete
the page or otherwise affect it. The owner of a page can also indicate,
by means of a protection code, the type of access that each access mode
will be allowed.
The Set Protection on Pages (SYS$SETPRT or SYS$SETPRT_64) system
service changes the protection assigned to a page or group of pages.
The protection is expressed as a code that indicates the specific type
of access (none, read-only, read/write) for each of the four access
modes (kernel, executive, supervisor, user). Only the owner access mode
or a more privileged access mode can change the protection for a page.
When an image attempts to access a page that is protected against the
access attempted, a hardware exception called an access
violation occurs. When an image calls a memory management
system service, the service probes the pages to be used to determine
whether an access violation would occur if the image attempts to read
or write one of the pages. If an access violation occurs, the service
exits with the status code SS$_ACCVIO.
Because the memory management services add, delete, or modify a single
page at a time, one or more pages can be successfully changed before an
access violation is detected. If the retadr argument
is specified in the 32-bit service call, the service returns the
addresses of pages changed (added, deleted, or modified) before the
error. If no pages are affected, that is, if an access violation occurs
on the first page specified, the service returns a -1 in both longwords
of the return address array.
If the retadr argument is not specified, no
information is returned.
The 64-bit system services return the address range (return_va and
return_length) of the addresses of the pages changed (added, deleted,
or modified) before the error.
12.3.7 Working Set Paging
On Alpha and I64 systems, when a process is executing an image, a
subset of its pages resides in physical memory; these pages are called
the working set of the process. The working set
includes pages in both the program region and the control region. The
initial size of a process's working set is replacing an
existing page in the working set. If the page that is going to be
replaced is modified during the execution of the image, that page is
written into a paging file on disk. When this page is needed again, it
is brought back into memory, again replacing a current page from the
working set. This exchange of pages between physical memory and
secondary storage is called paging.
The paging of a process's working set is transparent to the process.
However, if a program is very large or if pages in the program image
that are used often are being paged in and out frequently, the overhead
required for paging may decrease the program's efficiency. The
SYS$ADJWSL, SYS$PURGWS, SYS$LKWSET, and SYS$LKWSET_64 system services
allow a process, within limits, to counteract these potential problems.
12.3.7.1 SYS$ADJWSL System Service
The Adjust Working Set Limit (SYS$ADJWSL) system service increases or
decreases the maximum number of pages that a process can have in its
working set. The format for this routine is as follows:
Use the pagcnt argument to specify the number of
pagelets to add or subtract from the current working set size. The
system rounds the specified number of pagelets to a multiple of the
system's page size. The new working set size is returned in
wsetlm in units of pagelets.
12.3.7.2 SYS$PURGWS System Service
The Purge Working Set (SYS$PURGWS) system service removes one or more
pages from the working set. The format is as follows:
On Alpha and I64 systems, SYS$PURGE_WS removes a specified range of
pages from the current working set of the calling process to make room
for pages required by a new program segment The format is as follows:
12.3.7.3 SYS$LKWSET and SYS$LKWSET_64 System Services
The Lock Pages in Working Set (SYS$LKWSET) system service makes one or
more pages in the working set ineligible for paging by locking them in
the working set. Once locked into the working set, those pages remain
in the working set until they are unlocked explicitly with the Unlock
Pages in Working Set (SYS$ULWSET) system service, or program execution
ends. The format is as follows:
On Alpha and I64 systems, SYS$LKWSET_64 locks a range of virtual
addresses in the working set. If the pages are not already in the
working set, the service brings them in and locks them. A page locked
in the working set does not become a candidate for replacement. | http://h71000.www7.hp.com/doc/82final/5841/5841pro_039.html | CC-MAIN-2015-40 | refinedweb | 1,483 | 59.13 |
Canada/Building Canada 2020
NEWS, March 2, 2019. All building footprints of Canada now available!
Happy International Open Data Day. To celebrate, Statistics Canada released the Open Database of Buildings (ODB), version 2.0. Additionally, a database of building footprints covering virtually all of Canada has been constructed by Microsoft (developed with Deep Neural Networks and version 1.0 of the ODB) and released with an open data license. For more information on the Microsoft database and to access the data, visit the Microsoft GitHub Repository.
Virtually all building footprints of Canada are now available with licenses compatible with OSM!
Happy International Open Data Day 2019!
Happy mapping!
NEWS, January 2019
OSM's Canada_Building_Import has been updated with specific steps to take with our Import process, in conjunction with OSM Canada's Tasking Manager. Please examine these data and steps now: Ontario, Québec, Alberta, British Columbia, New Brunswick and Nova Scotia are available! As these steps get fine-tuned (first draft was January 25) and consensus emerges that there are well-qualified OSM mappers to enter into OSM high-quality data, we will lift the "On Hold" or "Stopped" status on the Tasking Manager one province at a time. Ask around, post here by clicking on the Discussion tab (start a new section if you must, or indent with a: to add to a thread) and be a part of OSM's community of adding buildings in Canada!
Imports (this one included) are done by intermediate and advanced OSM volunteers; JOSM is the recommended editor and the steps can be technical, detailed and require a certain judgement of quality. If you are up for it, take a look at the documentation, data, ask questions, build community, roll up your sleeves and help us map from these federal data, vetted to be ODbL-compatible (OSM's data licensing agreement). Thank you!
NEWS, November 2018
November 1, 2018 - Statistics Canada released the Open Database of Buildings (ODB), a collection of open data on buildings, primarily building footprints, and is made available under the Open Government License - Canada which has been deemed compatible with OpenStreetMap by the Legal Working Group. The ODB brings together 61 datasets originating from various government sources of open data. The database aims to enhance access to a harmonized collection of building footprints across Canada. The current version of the database (version 1.0) contains approximately 4.3 million records and includes provinces and territories where open building footprints were found during the collection period from January to August 2018. The coverage of the ODB is expected to increase as more government sources of building information become available under an open data license and are integrated into the database.
How to assist.
If you are an experienced JOSM user please help us import the building outlines following the Canada_Building_Import using a dedicated import account.
If you are are not an experienced JOSM user or even if you are you can usefully contribute to the project by enriching the tags on the building outlines.
The tags of most interest are the type of building so building=detached, semi, commercial, terrace, hotel, school and others mentioned in Map Features
The house number if known is useful but only with the street as well. Postcode is useful. The city can be derived from the city boundaries and does not need to be added to each building.
The number of levels is of interest so a two storey home would be building:levels=2
Streetcomplete is a useful mobile app that can be used to fill in gaps. will take you to the iD editor if you click on edit.
Teachers may find the following link of use
The formal guidelines for organised edits are here:
OSM from a municipal point of view:
WikiProject Canada/Building Canada 2020/municipalities
The Idea
Building Canada 2020 initiative (BC2020i) is an OpenStreetMap (OSM) WikiProject. It is a community-led initiative that has a vision to map in OSM all buildings in Canada by the year 2020. This vision emerged from a combination of factors: the collaborations and discussions triggered from a related (now defunct) crowdsourcing project by Statistics Canada, the growing need to improve existing georeferenced data on buildings across all communities in Canada, and a genuine opportunity to explore new forms in co-production of open data. Creating a freely accessible, non-proprietary source of nationwide information on buildings will contribute to the development of new data infrastructures and workflows of the future, upon which a multitude of public and private projects could thrive.
Simple information on buildings (e.g. WGS84-based geolocation, building footprint, full address including street # and street name, postal code, city, province and "Type Of Use") is of major societal value. This information, however, is often lacking in some areas or is not completely accessible on a single open data platform. Creating a nationwide, freely accessible and non-proprietary source of building information will contribute to development of the data infrastructures of the future, upon which a multitude of public and private projects could thrive.
This WikiProject came as an outgrowth from the pilot project done in Ottawa/Gatineau. There, the building outlines were imported from the City of Ottawa under their Open Data license. Then, the missing buildings were added and tags were added to the buildings in OSM. The value of combining Open Data to ensure completeness and accurately map the buildings with local knowledge yields data resources useful for many purposes. Although the project title says Canada the same techniques can be used anywhere in the world. In Africa, mapping buildings accurately has been used to estimate population: how many schools are needed, etc. Note the Ottawa pilot specifically made an effort to incorporate tags useful for disabled persons.
Why a community-led initiative?
Many communities might be mobilized to achieve this vision; the figure at right sketches six, more might be identified. By joining OSM, we share a space where these perspectives intersect and resources are available: dialogue can occur, activities can be coordinated and goals can be achieved with efficiency in a single, open database.
As a community-led initiative, Building Canada 2020 can foster collaboration between a multitude of stakeholders (civic groups, private sector, academia, public sector...) to achieve a specific common goal benefiting each stakeholder, as well as society as a whole. This approach is inspired by principles of civic science, more specifically, civic data. A community-led approach enables stakeholders sharing a common vision to share ownership and accountability for its realization as well as the creation of its output: open, accurate and complete data on all buildings in Canada, accessible through OSM.
Launch of the initiative
A workshop was held on September 15, 2017, at Statistics Canada head office in Ottawa. Participants were invited to provide comments and suggestions about how this vision could benefit their organization or activity, the challenges they foresee, additional stakeholders that might be engaged, possible tools that could be used, possible forms of governance that could be adopted, milestones to monitor progress, etc. Ideas and perspectives from many different communities were brought together to enrich the vision and help ensure its sustainability. The workshop was attended by 52 people from 25 organizations intending to:
- Ascertain whether there was enough consensus among stakeholders to determine if it is possible and beneficial to move forward with this vision within the context of OSM.
- Outline a "high-level roadmap" that might be used to turn the vision into a reality that will benefit all.
Note that many of participants were interested in what could the data be used for rather than how to get the information into OSM.
Known benefits
For the Canadian economy and society, buildings are a major capital asset, the space in which a large part of economic and social activities are concentrated, an essential element of human safety and security, physical infrastructures that shape our relationship with the natural environment and contribute to energy efficiency and consumption, and are landmarks of cultural and historical identity. For these reasons, there is a constellation of information domains that relate to buildings, at municipal, provincial and federal levels.
As of today, however, there is no comprehensive, open database on buildings in Canada. Such an open database could have a multitude of uses by a multitude of stakeholders.
Governance / Project Management
This project will be managed like all other OSM projects in Canada: by the local community using this wiki, the talk-ca mailing list and the OSM Canada Task Manager to coordinate various efforts. If there are lots of volunteers and/or funding becomes available to do additional things, more elaborate coordination (a project steering committee, ongoing project management...) can be set up.
This wiki (the document you are reading) helps guide BC2020's development, consensus and progress. We make progress by implementing various sub-projects and activities at a "more local level." Each of these "more local" sub-projects and activities has its own governance structure, depending on the organization or entity that implements it.
Communication and coordination
Building Canada 2020 is an open and inclusive initiative. Anybody sharing its vision is invited to be part of it and connect with individuals or organizations who contribute to this vision. The following communication and coordination tools are used:
- OSM community at large: this OSM Wiki page
- OSM community in Canada: done through Talk-Ca
- Tactical how-to questions on Slack, see: (join the #buildings2020 channel)
- Tasks in a specific community: OSM Canada Task Manager (ask on talk-ca or the slack channel if you would like a new task to be created)
What is the end goal?
At the launch of the initiative, no precise count of the total number of buildings in Canada was known. We could only estimate: using the benchmark ratio of 2 to 3 people per building, the total count of buildings in Canada might range between 10 and 15 million. As of September 2017, there were approximately 2 million ways in Canada tagged building=* in OpenStreetMap. As of February 2019, there were nearly 4 million buildings. With the new release of openly licensed databases (Statistics Canada and Microsoft, March 2019), we now know that there are approximately 13 million building footprints.
The data that could be mapped
Target data types (specific tags) for this initiative might include:
- Building locations (OSM nodes) or footprints (OSM ways or relations), tagged building=* with their correct "Type Of Use" (see below),
- Address and postcode of building, using the addr=* namespace,
- Height of building in meters, tagged height=*,
- Number of floors (called "levels" in OSM), using building:levels=*, max_level=*, min_level=* and non_existent_levels=*,
- Name of building, if there is one, tagged name=*,
- Year of construction, tagged start_date=*,
- Entrance and/or exit location(s) of building, if they are known, as nodes tagged entrance=*,
- Any amenities the building may provide, as nodes tagged amenity=*,
- Other building attributes (e.g., web page links about well-known, landmark and famous buildings using the website=* tag, potentially more).
OSM key building=* currently has over 60 documented values ("Type Of Use"), including building=residential, building=commercial, technical infrastructure, whether private or public with building=industrial and/or man_made=*, educational buildings at schools, colleges and universities with a variety of values, civic and cultural buildings, etc. The man_made=* key now has over 50 documented values, some of which are not exactly buildings (adit, flagpole, snow_net, water_tap) and others which are (gasometer, observatory, silo, windmill). Amenity (Map Features#Amenity) is another useful tag. Please correctly and appropriately apply these key-value pairs as OSM documents them!
How to get buildings into OSM?
We use OSM as a data repository, so OSM tenets must be followed. If you are unfamiliar with OSM here is some starting documentation:
- Learn OSM is a good place to start to learn about OSM and is available in different languages.
- Read more on mapping techniques
- OSM user guides: Beginner, Intermediate, Advanced This one is dated, as Potlatch has been largely displaced by iD.
High level techniques
There are several methods to add buildings to OSM. And for any one area of country it is likely the various methods will need to be combined to generate a comprehensive set of building and building attributes. Some locations have existing data in other sources, some none. Some existing data have some subset of interesting attributes, others may only have the building outline. These methods require different data sources and sometimes newly-developing tools. Several approaches to entering data into OSM are discussed below.
Map it based on satellite images
A first and frequent method is by "manually" mapping building outlines. It is recommended you use JOSM and the building_Tool plugin for this. The more-beginner-friendly iD editor can be used, but it can be difficult for new mappers to accurately map buildings using iD. However, JOSM has a steeper learning curve than iD. If you are organising a group of new mappers, the OSM Canada Task Manager tiling system is recommended. It incorporates a facility for validation where someone else checks recently-entered work.
(see an example of how this was done in Nepal)
Import from Open Data sources
A second method is a formal Import of municipal and provincial data (often Open Data). As Imports are not the usual method by which data enter OSM, Imports require following OSM's Import procedures. Open Data imports need expert attention to ensure the data are high quality and meet OSM's standards for imported data. Data arising from automated image processing (e.g. Lidar data) to map buildings is currently frowned upon. This may change as potential imports move forward successfully following OSM's Import process (the steps of which should become incorporated as part of this wiki). Part of this is assuring that the licence for the data are aligned with OSM's licence (ODbL). Part is a technical alignment of the data about the buildings (which may include their height, number of floors, etc.) with OSM's data tags in a matching, harmonious, mathematical/logical mapping. (See "The data that could be mapped" above).
Local Knowledge
A third method is of greater importance and depends on local knowledge: what additional data can you add to a building which already exists in OSM? (See "The data that could be mapped" above, especially notes on the building=* and man_made=* tags). Certainly the address Map Features#Addresses, its use and other attributes. And Map Features contains other important attributes that might be added. For example, tags such as cafe and wlan are helpful to thirsty mappers wanting to check their email. There are many different (smartphone-based) apps and web-based approaches to enter into OSM these additional data, such as streetcomplete (an Android App) and Field Papers, but these involve some post-processing. Vespucci is an Android-based full editor and OSMand can be used to add POI (Point Of Interest) information. There are many other similar methods to add minor attribute data to buildings in OSM, please list your favorites here!
Details on importing
Note for properly licensed imports: A very important phase of any data importation in OSM is the logical mapping of existing data to be imported "onto" the correct OSM key-value pair tags. For example, a building dataset of an area with both a university and a city might distinguish between residential buildings which appear similar in the real world, but some are known to be dormitories (best tagged building=dormitory) while others are apartments (best tagged building=apartments). Careful consideration must preclude any effort or script to translate these data before they enter OSM. It is NOT satisfactory to simply import data in a quick, sloppy or unconsidered method hoping to then "improve them in place" with subsequent OSM edits: we must do our best to first get them right! Of course, if (building) data already exist in OSM in error, or updates are needed, such improvements are welcome.
Some building data to be imported into OSM will be sparse (perhaps only footprint and/or address data) and some will be rich (including all of the above-listed attributes and perhaps even more). The best practice is to logically map the source data onto OSM's key-value pair tags as carefully and accurately as possible. Specifying an exact list of this logical mapping from source data to target OSM tags is a critical component of any local Import Plan.
More target data types may be added to the list above. During this WikiProject's presently "open" phase, you are encouraged to add additional target data you believe might be useful. At some point, we will "close" our target data specification and no longer accept additional submissions of data types to consider. Note there is no restriction within OSM on keys or values.
Implementation tools and workflows
Import plans: examples, tools, best practices
Each data import needs to file an Import Plan with the Imports mail list within OSM.
Here are some examples, the first of which is local to this project:
- Ottawa Import Plan provides extensive documentation on how to implement a bulk import of building data from municipal open data source. This documentation includes a video tutorial, which explains the import process from A to Z (see link to video).
- Open Your City's Buildings and Addresses, and Help the Blind with OpenStreetMap is an amazing presentation from the city of Louisville (US), documenting the import process and how importing a city’s building footprint and address data into OSM can help the visually impaired with a mobile app.
- Another example from the city of Lexington KY
Getting organized: OSM Tasking Manager
WikiProject Building Canada 2020 is a massive undertaking of coordination. It benefits from organization and structure of the tasks being completed at any given time. The OSM Canada Task Manager (sometimes abbreviated TM or OSM-TM or OSM-CA-TM) is one organization tool that can be used to coordinate work.
Currently (2018-Q1), out of 42 tasks there, 33 have the word "building" in them, you can search for this to filter tasks.
Two OSM Tasking Manager projects are active around Ottawa: and.
Inventory of Current Building Data Sets
We are creating an inventory of existing building related datasets from municipal and provincial open data sources as well as other sources. The tables and the link below document these datasets in Canada -- openly licensed, proprietary, ODbL compatible for inclusion in OSM, or not. As some of these data source's licenses remain in a state of flux and/or negotiation with OSM's Legal Working Group (status should be indicated in the table), please pay particular attention to this before entering these data into OSM.
In addition, Canada's "Open Government" Programs website has a table of municipal open data portals that can be reviewed for building data sets:.
* See tables of municipal and provincial open data for possible import into OSM.
Creating building polygons with machine learning techniques
This is a new and emerging area of work that has not yet been accepted by OSM due to data quality issues. It appears particularly promising with areas in Canada that are not covered by municipal open data, or to maintain OSM as "up to date." Here are some resources:
- Open source learning tools for building extraction (github codes)
- Detect missing buildings using imagery (State of the Map US 2017)
- Use Machine Learning to Create Building Heights in OSM (State of the Map US 2017)
Community mapping projects and mapping parties: tools and best practices
This section provides information on how to implement community Mapping_projects and/or Mapping_parties, aimed at adding building information to OSM. Find links to existing toolkits, best practices and lessons learned. There are examples from Canada and examples and inspiration from around the world. Some of the tools in community mapping activities include:
CODAP - The Crowdsourced Open Data Acquisition Platform - beta version
Access a beta version of CODAP here. CODAP is distributed under the MIT Licence. Code files of CODAP are available online here.
Tools and toolkits: examples and inspiration
- Community mapping for disaster risk reduction and management. Provides examples and tools on how to integrate base maps from OSM, building data, and flood hazard information to develop impact scenarios for a municipality.
Mapathons: tools and best practices
A Mapathon is a coordinated mapping event, often held indoors (sometimes known as "armchair mapping") but it can also be an outdoor or combined activity. Mapathons should OSM tutors who are happy to share their knowledge, sometimes have GPS units available to loan for the duration. If you want to run one note that it is common to offer snacks and refreshments. Using new mappers can offer challenges for data quality. If you are running one have some mice available to help the accuracy.
Building Canada 2020 can be a theme during many sorts of related events (see: Events).
Stakeholders of Building Canada 2020 can work towards the development of a set of "How to" toolkits, to help various organizations and educational institutions to plan and implement successful Mapathons across Canada.
Some general tools
Do-it-Yourself (DIY) Open Data Toolkit (Treasury Board of Canada Secretariat and OpenNorth).
An instructional manual that provides a step-by-step guide on how to develop your open data initiative. It brings together training materials, best practices, tools and resources to help you prepare for and implement an open data project.
How to Monitor progress?
This WikiProject will greatly benefit by better methods to display/demonstrate regular progress towards the goal of mapping all the buildings. It might be good to break down the status by CSD.
Active Monitoring tools
The following projects are actively monitoring the state of the buildings in Canada:
OSM Canada Task Manager is used to measure progress for many building projects in Canada: in fact, over 75% of the tasks there have "building" in their title. However, a more tightly-coupled method of the "% complete" reported there and some mechanism to "capture and report status" (on a province- or city-at-a-time basis), BC2020-wide, here or in another wiki seems a useful milestone to achieve.
[Keep adding to this list here...]
Background
If you are looking for statistics and the location of a municipality you can search Census Profiles 2016. Here are some project-specific tables:
- Large municipalities (CSD) with population 100,000 and over. There are 54 of these. It is estimated they account for 51% of the buildings across Canada, about 7.7 million buildings.
- Medium sized municipalities (CSD) with population 50,000 to 100,000. There are 46 of these. It is estimated they account for 9% of the buildings across Canada, about 1.3 million buildings.
- Small municipalities (CSD)with population 10,000 to 50,000 There are 313 of these. It is estimated they account for 17% of the buildings across Canada, about 2.5 million buildings.
- Small municipalities (CSD) with population 1,000 to 10,000 There are 1144 of these. It is estimated they account for 12% of the buildings across Canada, about 1.8 million buildings.
The following tools can be used to generate insights on the mapping of buildings across Canada.
- OSM Cha
- osmbuildingcount a custom made C# program that counts buildings and tags and exports a CSV file to create graphics etc. It comes with source:
- R (), an open Source statistical tool that can be used for statistical purposes using the building tags if you can extract them from OSM.
Major Obstacles to Solve
The following obstacles make achieving the goal difficult.
Getting local participation
Local buy-in is needed both for support for imports and to add tags to existing buildings. Ottawa demonstrated the importance of this.
Licence compatibility
For data imports, the compatibility of municipal/provincial open data licences with OSM's licence (ODbL, Contributor Terms) needs to be verified. As it appears for documentation listed in this page, Canadian municipalities have generally used a limited set of licences types (OGL 2.0; OGL 1.0; OGL-BC 2.0, etc). What is believed to be a fairly current licence status page is under construction.
Important note: data for a number of major municipalities have already been entered into OSM; of course, their licence was cleared and accepted as compatible with OSM's ODbL. See the documentation on OSM Wiki page "Contributors".
This Building Canada 2020 OSM WikiProject is expected to facilitate a discussion of OSM's ODbL license compatibility on two fronts. First, with municipalities so that they will adopt a standard licence (a lot of work has been done on this already). (HOW? Document that here, please!) Second, the OSMF Licensing Working Group will be engaged in this discussion. (HOW? WHEN?) A necessary component of this WikiProject is to streamline a process of verification of these licences, documenting the different open data licences used by Canadian municipalities and clarify issues of compatibility with ODbL for each type of licence.
Background documentation on previous cases
Ottawa import plan. The OSMF Licensing Working group (LWG sometimes known as the Legal.
One of the difficulties to keep in mind is that OSM's LWG has limited resources to examine many licences: to approve "city after city after city..." is an unrealistic use of their time. A major goal of this project is to harmonize OD licenses in Canada so that as they might be used to enter building data into OSM, the LWG can be presented with a SINGLE licence (or very small number of licenses) to approve as harmonious with OSM's ODbL. This work is ongoing, progress should be documented here.
Funding
At this time, nobody is dedicated to this project, and it will only go as fast as there are people to do work on it. Organizations who stand to benefit from realizing the vision and achieving the goals of this project are encouraged to provide funding to allow people to spend more time on this project than they otherwise would. Currently (2018-Q!) the project would benefit from a Project Manager who can coordinate the many moving parts using "methods familiar to OSM." These include writing/updating this wiki to inform new and existing users and provide ongoing status as to what is going on in the project at all times, becoming a "one stop shop" to learn about and contribute to the project.
Tag Standardization / Data quality assurance
OSM building data can be assessed across the following (and more) dimensions: completeness, positional, temporal, semantic, attribute and shape/size accuracy as well as logical OSM tagging consistency. For example, some building data might include height=* or start_date=* (date built) tags, some may not, but the general OSM tagging guidelines (building tags, the Buildings wiki and the man_made=* tag) are being followed as best as possible so that data are consistent across the country. However, given the diversity that makes up Canada, 100% consistency throughout the country is a challenge. Canada-specific usage can be documented here as and when these challenges are identified.
Academic institutions involved in this initiative are welcome to provide leadership on research and best practices related to QA for building data in Canada.
Existing OSM tools show some of the QA challenges related to building data in Canada. Figure 1 is an example of OSM tagging logical consistency: in this case how consistently residential building polygons are tagged with existing tags.
Data maintenance and accessibility
As with OSM in general, the ongoing maintenance to keep buildings up-to-date must be discussed. A specific plan to update data and how that will occur in the future should be outlined here.
Stories, Examples and Inspiration
In order to provide motivation for volunteers to work on this project, it is important to understand success stories of how building data (or OSM in general) is used in Canada. OSM is used in multitude of ways: on the ground by humanitarian operators, online with amazing apps and data visualization tools.... Please add more success stories here.
- The Canadian Red Cross and the Gatineau floods 2017. "During spring 2017 when Ottawa and Gatineau experienced severe flooding, the Canadian Red Cross used building information within OpenStreetMap to validate the number of homes impacted by the high-water levels. They also used these data to produce base maps of the affected area for planning and delivering assistance." (Read more ...)
- Data visualization tool for building property assessment values (Vancouver, Edmonton). "Open data facilitates innovation. I couldn’t have created this visualization without that kind of access to data." says Eugene Chen, of Darkhorse Analytics, (read the full blog post)
Other Examples and Inspiration from in Canada
- Happy Valley-Goose Bay. Here is an example of how a small municipality makes a smart use of open source technology and data (QGIS2web and OSM) to create an interactive map.
- Interactive maps created by Vancouver-based data analytics company MountainMath, show the power of combining OSM and municipal open data to visualize building and housing statistics.
- City of Edmonton, Building age map. Map created by Yourtruhome.com. in partnership with BCYEG, which found a volunteer to redeploy the Chicago Building Age map in Edmonton.
- CBC/Radio-Canada. Montréal a 375 ans, mais quel âge ont ses bâtiments? Building Age map of Montreal.
- Simple 3D buildings is a OSM wiki page that describes tags for basic 3D attributes of buildings. There is a list of amazing Demos (for example, see these F4map versions of Edmonton, Toronto and Halifax)
- Vancouver Land Prices Heat Map. Heat Map is showing price per sq.ft for Vancouver parcels of land. All of the data displayed on the map are from the Open data Vancouver Catalogue (2014 BC Assessment data from tax reports and current parcels polygons).
- Housing Price Maps (Montreal and other international cities). These maps show overall city-wide trends in residential real estate prices. The source code is also provided.
Other Examples and Inspiration from Around the world
- La Base Adresses Nationale Ouverte (BANO) est une initiative d'OpenStreetMap France. Elle a pour objet la constitution d'une base la plus complète possible de points d'adresse à l'échelle de la France. Vous trouverez sur cette page les accès aux différentes problématiques soulevées par la constitution d'une base "Adresses". In France, there are approximately 46 million building polygons mapped in OSM.
- BAG import, how the Dutch community imported nearly 9 million building footprint data and dramatically improve the quality of the Dutch address and building data.
- Future City Glasgow Maps
- Bklynr. Block by Block, Brooklyn’s past and present, with a map of the 320,000 buildings in Brooklyn, plotted and shaded according to their year of construction.
- All 9,866,539 buildings in the Netherlands, shaded according to year of construction
- Los Angeles buildings and parcels maps building and parcel size. An example of how open data are used to learn about land use in Los Angeles.
- San Francisco Building Explorer (Demo). 3D building model and information realized with the release of new building footprints to the open data portal by DataSF. (Source code available here)
- Prix immobilier partout en France Mapping of housing prices in France.
- Building Heights in England. From EMU Analytics. Emu DataPacks (Open Data on buildings) are also available for download.
- Jersey City Building Census. Read the story on Sarah Michael Levine Blog, which also include the code and explanation on "how to". And the smart city thanks Sarah. (Also available in a 3D Zoning version).
- Berlin 3D - Downloadportal. Berlin’s digital 3D city model is a joint project of the Berlin Senate Department for Economics, Energy and Public Enterprises as well as Berlin Partner for Business and Technology (read more).
Events and Activities
Please add any relevant ongoing activities and upcoming events.
Ongoing Activities
- Statistics Canada Crowdsourcing Project: This project focuses on collaborating with local OSM groups and meeting with major municipalities to help them make open their data on building footprints (where available). Contact for this project: statcan.crowdsourceapprocheparticipative.statcan@canada.ca. The following municipalities are involved:
- City of Ottawa
- Ville de Gatineau
Upcoming events
- Spring 2018 mapathons
- July 28-30, 2018, State of the Map 2018, Milano (Italy)
Past events
- November 12-18, 2017, Mapathon Events for OSMGeoWeek at Canadian Universities, with events at Carleton University, McGill University, Selkirk College, University of Calgary, University of Waterloo, Ryerson University, University of Winnipeg, and Red River College
Contacts for Groups and Organizations
If your group or organization is or wants to be involved in this project, but not listed, please add it!
OpenStreetMap groups
- Local Ottawa OSM group
- Toronto OpenStreetMap Enthusiasts — “Mappy Hour”
- OSMCANADA - A Community around OpenStreetMap
Not-For-Profit
- Open North
- Canadian Red Cross
Academics
- McGill University - Geographic Information Centre
- Carleton University
- York University - Lassonde School of Engineering - Geomatics
- University of Calgary - Department of Geography
Private Sector
- MapBox
- OpenConcept
Municipal
- ...
Federal
- Statistics Canada - Data Exploration and Integration Lab (DEIL): jean.lemullec-at-canada.ca; alessandro.alasia-at-canada.ca
- Natural Resources Canada - Centre of Mapping and Earth Observation | https://wiki.openstreetmap.org/wiki/WikiProject_Canada/Building_Canada_2020 | CC-MAIN-2022-05 | refinedweb | 5,502 | 51.58 |
Flash games are very much the bread and butter of indie pop-nerd culture. If you consider the slices of bread the menu and the game itself, what is left? The butter - the very substance that makes the bread taste that much more delicious. And in terms of a Flash game, what comes in between menus and games are the transitions!
Final Result Preview
This is an example pattern of the transition effect that we will be working towards:
Step 1: Setting Up
Per usual we need to create a new Flash File (ActionScript 3.0). Set its width to 400px, its height to 200px, and the frame rate to 30fps. The background color can be left as the default. Save the file; it can be named whatever you please. I named mine Transitions.fla.
Next we need to create a document class. Go to your Flash file's properties and set its class to
Transitions. Then create the document class:
package { import flash.display.*; import flash.events.*; public class Transitions extends MovieClip { static public var val:Number = new Number(); static public var transitionAttached:Boolean = new Boolean(); public function Transitions() { val = 0; transitionAttached = false; } } }
The code just introduced two variables. The first will be used to select the effect's pattern, and the second will be used to check against having multiple instances of the effect on the stage.
Step 2: Creating the Square Sprite
Our next step is to create the sprite that will be used as each square for the transition. Create a new class and save it as Square.as:
package{ import flash.display.*; import flash.events.*; public class Square extends Sprite{ public var squareShape:Shape = new Shape(); public function Square(){ } } }
We use the
squareShape variable to draw our shape inside the Sprite. Draw a rectangle 40px by 40px (Which is the full size) and set its scale to
0.1, a tenth of its size - this will aid us in the effect later:
addChild(squareShape); squareShape.graphics.beginFill(0x000000,1); squareShape.graphics.drawRect(-20,-20,40,40); squareShape.graphics.endFill(); this.scaleX = 0.1; this.scaleY = 0.1;
Step 3: Creating the Effect
Create another new class for the effect itself. Once we are finished, adding the effect to the stage will be very simple:
package{ import flash.display.*; import flash.events.*; import flash.utils.*; public class FadeEffect extends Sprite{ public var currentFadeOut:int = 00; public var currentSquares:int = 01; public var pauseTime:int = 01; public var tempNum:int = 00; public var fading:String = "in"; public var fadeinTimer:Timer = new Timer(100); public var fadeoutTimer:Timer = new Timer(100); public var fadeArray:Array = [ /]]]; public var squaresArray:Array = new Array(); public function FadeEffect(){ } } }
You are probably thinking "that is a heck of a lot of variables, what all are they used for?":
currentFadeOut- used as a check for
tempNumto see how many squares are to be scaled
currentSquares- the current value indicating which squares should be attached and/or scaled
pauseTime- a simple integer to give a slight pause in between transitions and removing itself
tempNum- used to check what numbers in the array are to be scaled
fading- a string to check if the transition is fading in or out
fadeinTimer- a timer that is called to begin the fading in of the current value of currentSquares
fadeoutTimer- another timer that is called to begin the fading out of the current value of currentSquares
fadeArray- the 3D array that contains all the transition patterns
squaresArray- an array for the Square sprites
Our effect will begin by initiating an event listener for
fadeInTimer and starting it. We also need to add an event listener to continuously scale all of the sprites to their correct sizes. Use the following code inside the constructor:
fadeinTimer.addEventListener("timer", fadeSquaresInTimer); fadeinTimer.start(); addEventListener(Event.ENTER_FRAME, enterFrame);
The next step is to create those two event listeners. We will start with the easier of the two, the
enterFrame function:
public function enterFrame(e:Event){ for each(var s1 in squaresArray){ tempNum+=1; if(fading=="in"){ if(s1.scaleX<=1){ s1.scaleX+=0.05; s1.scaleY+=0.05; } }else if(fading=="out"){ if(tempNum<=currentFadeOut){ if(s1.scaleX>=0.1){ s1.scaleX-=0.05; s1.scaleY-=0.05; }else{ if(s1.visible == true){ s1.visible = false; } } } } } tempNum=00; }
It may not make total sense right now, but this should help shed some light.
s1is the instance name that will be given to the Squares when we create them in a later function.
- They are added to an array called
squaresArrayto keep track of the number of them and we perform the same operation for every object in the array.
- Next we increase
tempNum(used in the fading out if-statement) which is used to scale the sqaures in the order that they were added to the array. This means it is not pattern dependant and will work with any pattern.
After that...
- We check if
fadingis true or not.
- If true, it scales all the squares up until they reach their full size (they begin scaling immediately after currentSquares increases).
- Once it begins fading out things become a little trickier; we only scale down the squares that are lower than the current value of
currentFadeOut(these are the ones that should be scaling, all others should remain at full scale until the value increases).
- Once they have scaled down to a tenth of the size we make those squares invisible (they will be deleted with the whole effect).
It's time to add the event listener for the timer:
public function fadeSquaresInTimer(e:Event){ fadeSquaresIn(fadeArray[Transitions.val]); currentSquares+=1; }
At first glance it looks less complicated, but you should notice that we are calling a function with the
fadeArray as the parameter. Which pattern is selected from the array depends on what you set
val equal to in the Transitions class; right now it should use the first pattern because
val is set to 0.
The next step is to create the
fadeSquaresIn function that is called from the previous timer:
public function fadeSquaresIn(s:Array){ for (var row=0; row<s[0].length; row++) { for (var col=0; col<s.length; col++) { } } }
First thing that we accomplish is iterating through the selected pattern. We start at row 1, colomn 1 and cycle through every colomn until the end of the row has been reached. Then we move onto the next row and repeat the process.
The next thing to do is compare the current item in the array to the value of
currentSquares:
if(int(s[col][row]) == currentSquares){ }
If they are equivalent we add a square, position it accordingly, and push it onto the
squaresArray so that it can be scaled:
var s1:Sprite = new Square(); s1.x = 20+(row*40); s1.y = 20+(col*40); addChild(s1); squaresArray.push(s1);
We are almost done with this function, we just have to perform a check for when there are the same number of squares as there are items in the pattern. We do so by adding the following if-statement outside both for-loops:
if(squaresArray.length == (s[0].length * s.length)){ fadeinTimer.stop(); addEventListener(Event.ENTER_FRAME, pauseBetween); }
Self explanatory - we stopped the timer and called an event listener for the pause between fading in and fading out. That function is used to initiate the fading out and may also be used to cause change in your game:
public function pauseBetween(e:Event){ pauseTime+=1; if(pauseTime==60){ currentSquares=01; fading="out"; fadeoutTimer.addEventListener("timer", fadeSquaresOutTimer); fadeoutTimer.start(); removeEventListener(Event.ENTER_FRAME, pauseBetween); } }
We won't spend much time on this function due to its simplicity. Here we increase the value of
pauseTime, and once it equals 60 (meaning two seconds have passed) we set the value of
currentSquares back to 1, set
fading to
"out" so that the squares can scale backwards, remove the listener for
pauseBetween() itself, and add an event listener for this new function:
public function fadeSquaresOutTimer(e:Event){ fadeSquaresOut(fadeArray[Transitions.val]); currentSquares+=1; }
This works much like
fadeSquaresInTimer(), though this time we are calling the function
fadeSquaresOut():
public function fadeSquaresOut(s:Array){ for (var row=0; row<s[0].length; row++) { for (var col=0; col<s.length; col++) { if(int(s[col][row]) == currentSquares){ currentFadeOut+=1; } } } }
We cycle through, but this time when we find an equivalent item we increase the value of
currentFadeOut so that the next item in the
squaresArray can begin fading out.
Almost finished now; all that's left is to stop the timer and remove the effect. Add this if-statement outside of the two for-loops:
if(currentFadeOut == (s[0].length * s.length)){ fadeoutTimer.stop(); pauseTime=01; addEventListener(Event.ENTER_FRAME, delayedRemove); }
This checks whether all of the items have begun fading out. If so, it then stops the timer, sets
pauseTime back to 1 and adds an event listener for the function
delayedRemove():
public function delayedRemove(e:Event){ pauseTime+=1; if(pauseTime==30){ Transitions.transitionAttached = false; removeEventListener(Event.ENTER_FRAME, delayedRemove); stage.removeChild(this); } }
Like before we increase the value of
pauseTime, and once it equals 30 (1 second) we set the boolean back to
false so that the effect can be added once again. We remove this event listener and we remove this effect from the stage.
Step 4: Adding the Effect
Now comes the easy part. Add the following code inside the document class constructor to add the effect:
if(transitionAttached == false){ transitionAttached = true; var f1:Sprite=new FadeEffect; stage.addChild(f1); }
Step 5: Creating More Patterns
Feel free to create your own patterns! It's extremely simple, just create a new 2D array inside the 3D array. Here is the array that I have created (just replace your 3D array with it). It includes 8 different transitions:
[/]], //left [[01,02,03,04,05,06,07,08,09,10], [01,02,03,04,05,06,07,08,09,10], [01,02,03,04,05,06,07,08,09,10], [01,02,03,04,05,06,07,08,09,10], [01,02,03,04,05,06,07,08,09,10]], //right [[10,09,08,07,06,05,04,03,02,01], [10,09,08,07,06,05,04,03,02,01], [10,09,08,07,06,05,04,03,02,01], [10,09,08,07,06,05,04,03,02,01], [10,09,08,07,06,05,04,03,02,01]], //top-left [[01,02,03,04,05,06,07,08,09,10], [02,03,04,05,06,07,08,09,10,11], [03,04,05,06,07,08,09,10,11,12], [04,05,06,07,08,09,10,11,12,13], [05,06,07,08,09,10,11,12,13,14]], //top-right [[10,09,08,07,06,05,04,03,02,01], [11,10,09,08,07,06,05,04,03,02], [12,11,10,09,08,07,06,05,04,03], [13,12,11,10,09,08,07,06,05,04], [14,13,12,11,10,09,08,07,06,05]], //bottom-left [[05,06,07,08,09,10,11,12,13,14], [04,05,06,07,08,09,10,11,12,13], [03,04,05,06,07,08,09,10,11,12], [02,03,04,05,06,07,08,09,10,11], [01,02,03,04,05,06,07,08,09,10]], //bottom-right [[14,13,12,11,10,09,08,07,06,05], [13,12,11,10,09,08,07,06,05,04], [12,11,10,09,08,07,06,05,04,03], [11,10,09,08,07,06,05,03,03,02], [10,09,08,07,06,05,04,03,02,01]]];
You can change the value of
Transitions.val to choose another pattern - for example, if
val is
3, the transition will sweep in from the right.
Conclusion
Thanks for taking the time to read this tutorial. If you have any questions please leave a comment below. And if you would like a challenge, try making the effect fade in with one pattern and fade out with an opposing one.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/tutorials/create-flash-screen-transition-effects-entirely-with-code--active-10976 | CC-MAIN-2018-26 | refinedweb | 2,030 | 60.75 |
Rendering Multiple Nodes With Fragments
When rendering, React expects a component to only return a single node. The DOM hierarchy of most components will easily follow this rule, but what about those components that do have multiple inline nodes?
The two solutions have been to either wrap the inline nodes in an outer
div or to return them as a comma separated array of nodes. With React 16,
we can avoid the deficiencies of both of these approaches by using a
fragment.
Just wrap your inline nodes with a
React.Fragment node. React will
understand your JSX without wrapping the output DOM in a superfluous
div.
render() { // ... more code return ( <React.Fragment> <p>Name: {firstName} {lastName}</p> <p>Email: {email}</p> <p>Age: {age}</p> </React.Fragment> ); }
See the docs on fragments for more details.Tweet | https://til.hashrocket.com/posts/cideywpxi5-rendering-multiple-nodes-with-fragments | CC-MAIN-2020-16 | refinedweb | 136 | 57.27 |
We are excited today to introduce Next.js 9.5, featuring:
-
- Optional Trailing Slash in URLs: consistently enforce the absence or presence of a trailing slash
- Persistent Caching for Page Bundles: unchanged pages' JavaScript files now carry forward across builds
- Fast Refresh Enhancements: improved reliablility of the Next.js live-editing experience
- Production React Profiling: a new flag to measure your project's “cost” of rendering
- Optional Catch All Routes: dynamic routes now provide more flexibility for SEO-driven use-cases
- Webpack 5 Support (beta): optionally opt-into the next version of webpack 5 for improved build size and speed
Stable Incremental Static Regeneration
Next.js introduced Static Site Generation methods in 9.3 with a clear goal in mind: we should get the benefits of static (always fast, always online, globally replicated), but with excellent support for dynamic data, which Next.js is known for.
To get the best of both worlds, Next.js introduced Incremental Static
Generation, updating static content after you have already built your site. By
using the
fallback: true option in
getStaticPaths,
you can register new static pages at runtime.
Next.js can statically pre-render an infinite number of pages this way, on-demand, no matter how large your dataset is.
Today, we are announcing the general availability of Incremental Static Re-generation, which is a mechanism to update existing pages, by re-rendering them in the background as traffic comes in.
Inspired by stale-while-revalidate, background regeneration ensures traffic is served uninterruptedly, always from static storage, and the newly built page is pushed only after it's done generating.
export async function getStaticProps() { return { props: await getDataFromCMS(), // we will attempt to re-generate the page: // - when a request comes in // - at most once every second revalidate: 1, }; }
The revalidate flag is the number of seconds during which at most one generation will happen, to prevent a.
Unlike traditional SSR, Incremental Static Regeneration ensures you retain the benefits of static:
- No spikes in latency. Pages are served consistently fast.
- Pages never go offline. If the background page re-generation fails, the old page remains unaltered.
- Low database and backend load. Pages are re-computed at most once concurrently.
Both incremental features (adding pages and lazily updating them), as well as
preview mode, are now
stable and already fully supported by both
next start and the
Vercel edge platform out of the box.
To showcase this new feature we have created an example showing regenerating a static page that shows the count of various GitHub reactions of a specific issue:
Up next, we will be working on a supplemental RFC to address two additional incremental static generation capabilities:
- Re-generating and invalidating multiple pages at once (like your blog index and a certain blog post)
- Re-generating by listening to events (like CMS webhooks), ahead of user traffic
For more details, check out
the
getStaticProps documentation.
Customizable Base Path
Next.js projects are not always served from the root a domain. Sometimes you
might want to host your Next.js project under a subpath like
/docs so that the
Next.js project only covers that subsection of the domain.
While this has been possible so far, it was at the expense of quite a bit of
extra configuration. For example, adding the prefix to every single
<Link> and
making sure Next.js was serving the JavaScript bundles from the right path.
To address this pain point, we're introducing a new configuration option.
basePath allows you to easily host your Next.js project on a subpath of your
domain.
To get started using
basePath you can add it to
next.config.js:
// next.config.js module.exports = { basePath: '/docs', };
After configuring the
basePath your project will automatically be routed from
the provided path. In this case,
/docs.
When linking to other pages in the project with
next/link or
next/router the
basePath will be automatically prefixed. This allows you to change the
basePath without changing your project.
An example of this would be using
next/link to route to another page:
import Link from 'next/link'; export default function HomePage() { return ( <> <Link href="/documentation-page"> <a>Documentation page</a> </Link> </> ); }
Using
next/link in this way will result in the following HTML rendered to the
web browser:
<a href="/docs/documentation-page">Documentation page</a>
For more details, check out
the
basePath documentation.
Support for Rewrites, Redirects, and Headers
Rewrites
When building a Next.js project you might want to proxy certain routes to another URL. For example, if you want to incrementally adopt Next.js into your stack you would want to route pages that exist in your Next.js project and then everything that was not matched to the old project that you're migrating off of.
With Next.js 9.5 we're introducing a new configuration option named
rewrites,
which allows you to map an incoming request path to a different destination
path, including external URLs.
For example, you might want to rewrite a certain route to
example.com:
// next.config.js module.exports = { async rewrites() { return [ { source: '/backend/:path*', destination: '*' }, ]; }, };
In this case, all paths under
/backend would be routed to
example.com.
You can also check if your Next.js project routes matched and then rewrite to the previous project if there is no match. This is incredibly useful for incremental adoption of Next.js:
module.exports = { async rewrites() { return [ // check if Next.js project routes match before we attempt proxying { source: '/:path*', destination: '/:path*', }, { source: '/:path*', destination: `*`, }, ]; }, };
In this case, we first match all paths. If none match we proxy to
example.com which would be the previous project.
To learn more about
rewrites feature check out the
rewrites documentation.
Redirects
Most websites need at least some redirects. Especially when changing the
structure of your project routes. For example, when moving
/blog to
/news or
similar transitions.
Previously having a list of redirects in your Next.js project required setting
up a custom server or a custom
_error page to check if there are redirects set
for the route. However, this came at the expense of invalidating key static and
serverless optimizations (by having a server) or wasn't ergonomic enough.
Starting from Next.js 9.5 you are now able to create a list of redirects in
next.config.js under the
redirects key:
// next.config.js module.exports = { async redirects() { return [ { source: '/about', destination: '/', permanent: true, }, ]; }, };
To learn more about
redirects feature check out the
redirects documentation.
Headers
Next.js allows you to build hybrid projects that use both Static Generation and Server-Side Rendering. With Server-Side rendering, you can set headers for the incoming request. For static pages, setting headers was not possible until now.
We now have introduced a
headers property in
next.config.js that applies to
all Next.js routes:
// next.config.js module.exports = { async headers() { return [ { source: '/:path*', headers: [ { key: 'Feature-Policy', // Disable microphone and geolocation value: "microphone 'none'; geolocation 'none'", }, ], }, ]; }, };
The
headers option allows you to set commonly needed headers like
Feature-Policy
and
Content-Security-Policy.
To learn more about
headers feature check out the
headers documentation.
Optional Trailing Slash in URLs
When Next.js was introduced 3 years ago, its default behavior was for all URLs with a trailing slash to always return a 404 page.
While effective, some users have requested the ability to change this behavior. For example, when migrating an existing project to Next.js that previously always had trailing slashes enforced.
With Next.js 9.5 we have introduced a new option called
trailingSlash to
next.config.js.
This new option ensures Next.js is automatically handling the trailing slash behavior:
- Automatically redirect trailing slash URLs to the URL without the trailing slash, for example:
/about/to
/about
- When
trailingSlashis set to
truethe URL without trailing slash will be redirected to the URL with a trailing slash, for example:
/aboutto
/about/
- Ensures
next/linkhas the trailing slash automatically applied/removed to avoid needless redirects.
// next.config.js module.exports = { // Force a trailing slash, the default value is no trailing slash (false) trailingSlash: true, };
To learn more about the
trailingSlash feature check out the
trailingSlash documentation
Persistent Caching for Page Bundles
When writing Next.js pages, the creation of all script bundles, CSS stylesheets,
and HTML is fully automatic and abstracted away from you. If you inspect the
generated
<script> tags before Next.js 9.5, you'll notice their URLs follow a
pattern like this:
/_next/static/ovgxWYrvKyjnlM15qtz7h/pages/about.js
The path segment
ovgxWYrvKyjnlM15qtz7h above is what we called the build ID.
While these files were easily cacheable at the edge and on the user's machine,
after re-building your app, the build ID would change and all caches would be
busted.
For most projects this trade-off was fine, however, we wanted to optimize this behavior even further by no longer invalidating the browser cache for pages that had not been changed.
The introduction of the improved code-splitting strategy in Next.js 9.2 that was developed in collaboration with the Google Chrome team laid some groundwork for these improvements to the Next.js page bundle generation.
Starting with Next.js 9.5 all page JavaScript bundles will use content hashes instead of the build ID. This allows for pages that have not changed between deploys to remain in the browser and edge cache without needing to be downloaded again.
In contrast, the URL pattern after these changes looks something like:
/_next/static/chunks/pages/about.qzfS4o5gIEXRME6sTEahL.js
Instead of a global build ID, the
qzfS4o5gIEXRME6sTEahL portion is a
deterministic hash of the
about.js bundle, which will be stable insomuch the
code for that section of your site doesn't change. Further, it's now cached
long-term across re-deploys via
Cache-Control: public,max-age=31536000,immutable which Next.js automatically
sets for you.
Fast Refresh Enhancements
We introduced Fast Refresh in Next.js 9.4, a new hot reloading experience that gives you instantaneous feedback on edits made to your React components.
Next.js 9.5 further refines our Fast Refresh implementation and gives you the tools you need to succeed:
- Easy to understand errors: All compile and runtime errors were updated to only show relevant information, including a code frame of whatever code caused the error.
- Development-time tips to keep component state: Next.js now provides you with helpful tips to ensure Fast Refresh will keep your component state in as many scenarios as possible. Each tip Next.js provides is fully actionable and accompanied by a before and after example!
- Warnings when component state is reset: We'll now print a detailed warning when Next.js is unable to keep component state after a file is edited. This warning will help you diagnose why the project had to reset component state, allowing you to fix it and utilize Fast Refresh to its full potential.
- New documentation: We've added extensive documentation that explains what Fast Refresh is, how it works, and what to expect! The documentation will also teach you how to better leverage Fast Refresh by explaining how its error recovery works.
- User-code troubleshooting guide: The new documentation also includes common troubleshooting steps and tips on how to get the most out of Fast Refresh in development.
Production React Profiling
React introduced the Profiler API a while ago which allows you to track down performance issues in your React components. While this feature works automatically in development it requires a separate version of ReactDOM to be used to profile in production.
With Next.js 9.5, you can now enable production profiling for React with the
--profile flag in
next build:
next build --profile
After that, you can use the profiler in the same way as you would in development.
To learn more about profiling React you can read the post on the React Profiler by the React team. Special thanks to TODOrTotev and @darshkpatel for contributing this feature.
Optional Catch All Routes
Next.js 9.2 added support for catch-all dynamic routes which have been widely adopted by the community for various use cases. Catch-all routes give you the flexibility to create highly dynamic routing structures powered by Headless CMS, GraphQL APIs, filesystem, etc.
In listening to feedback, we heard users wanted to have even more flexibility to match the root-most level of a route. Today, we're happy to unveil optional catch-all dynamic routes for these advanced scenarios.
To create an optional catch-all route, you can create a page using the
[[...slug]] syntax.
For example,
pages/blog/[[...slug]].js will match
/blog, as well as any
route underneath it, such as:
/blog/a,
/blog/a/b/c, and so on.
Like catch-all routes,
slug will be provided in the
router query object
as an array of path parts. So, for the path
/blog/foo/bar, the query object
will be
{ slug: ['foo', 'bar'] }. For the path
/blog, the query object will
omit the slug key:
{ }.
You can learn more about optional catch all routes in our documentation.
Webpack 5 Support (beta)
Webpack 5 is currently in beta. It includes some major improvements:
- Improved Tree-Shaking: Nested exports, inner-module, and CommonJS are tree shaken
- Persistent Caching: Allows for reuse of work from previous builds
- Deterministic chunk and module ids: solves cases where webpack module ids would change between builds
We're excited today to announce the beta availability of webpack 5 for Next.js.
To try out webpack 5 you can use
Yarn resolutions
in your
package.json:
{ "resolutions": { "webpack": "^5.0.0-beta.30" } }
The Webpack 5 beta has already been rolled out to nextjs.org and vercel.com in production. We encourage you to try it out in a progressive manner and report back your findings on GitHub.
Compilation infrastructure improvements
To support webpack 5 we have rewritten a lot of the compilation pipeline to be more tailored to Next.js:
- Next.js no longer relies on
webpack-hot-middlewareand
webpack-dev-middleware, instead we now use webpack directly and optimize specifically for Next.js projects. This translates into a simpler architecture and faster development compilation.
- On-demand-entries, which is the system Next.js has to allow it to compile on the pages that you visit at a given time during development, has also been rewritten and is now even more reliable by leveraging new webpack behavior specifically tailored for our use case.
- React Fast Refresh and the Next.js Error Overlay are now fully compatible with webpack 5
- Disk caching will be enabled in a future beta release.
Backwards compatibility
We are always committed to ensuring that Next.js is backwards compatible with previous versions.
Webpack 4 will continue to be fully supported. We are working closely with the webpack team to ensure the migration from webpack 4 to 5 is as smooth as possible.
If your Next.js project has no custom webpack configuration, no project changes will be needed to fully leverage webpack 5.
Important: if your project has custom webpack configuration, some changes might be needed to transition to webpack 5. We recommend keeping an eye out for our migration instructions or minimize your usage of webpack extensions altogether for seamless future upgrades.
Improved file watching on macOS
We recently found an issue with webpack where file watching on macOS would stop after making a few changes to your code. You'd have to restart your project manually to see updates again. After a few changes, the cycle would repeat.
Furthermore, we found that this issue didn't just happen in Next.js projects but all projects and frameworks that build on top of webpack.
After several days of debugging the issue, we tracked down its root cause to the file watching implementation that webpack uses called chokidar, which is a file watching implementation widely used in the Node.js ecosystem.
We sent a patch to chokidar to fix the issue. After the patch was released we worked with Tobias Koppers to roll out this patch in a new webpack version.
This patched webpack version is automatically used when you upgrade to Next.js 9.5.
Conclusion
We're excited to see the continued growth in Next.js adoption:
- We have had over 1,200 independent contributors, with over 135 new contributors since the 9.4 release.
- On GitHub, the project has been starred over 51,100 times.
Join the Next.js community on GitHub Discussions. Discussions is a community space that allows you to connect with other Next.js users and freely ask questions or share your work.
For example, you might want to start by sharing your project URL with everyone.
If you want to give back but unsure how, we encourage you to try experimental features like our Webpack support and report back your findings!
Credits
We are thankful to our community, including all the external feedback and contributions that helped shape this release.
Special thanks to Jan Potoms, a long-time Next.js community member who contributed to multiple features in this release.
Special thanks to Tobias Koppers, the author of webpack, who helped land webpack 5 support in Next.js.
This release was brought to you by the contributions of: @chandan-reddy-k, @Timer, @aralroca, @artemisart, @sospedra, @prateekbh, @Prioe, @Janpot, @merceyz, @ijjk, @PavelK27, @marbiano, @MichelleLucero, @thorsten-stripe, TODOrTotev, @Skn0tt, @lfades, @timneutkens, @akhila-ariyachandra, @chibicode, @rafaelalmeidatk, @kirill-konshin, @jamesvidler, @JeffersonBledsoe, @tylev, @jamesmosier, @filipemarins, @Remeic, @vvo, @timothyis, @jazibsawar, @coetry, @adam-zacharski, @danwilliams, @tywmick, @matamatanot, @goldins, @mvllow, @its-tayo, @sshyam-gupta, @wilbert-abreu, @sebastianbenz, @jaydenseric, @developit, @dylanjha, @darshkpatel, @spinks, @stefanprobst, @moh12594, @jasonmerino, @cristiand391, @HyunSangHan, @mcsdevv, @M1ck0, @hydRAnger, @alexej-d, @valmassoi, TODOrtotev, @motleydev, @eKhattak, @jpedroschmitz, @JerryGoyal, @bowen31337, @phillip055, @balazsorban44, @chuabingquan, @youhosi, @andresz1, @bell-steven, @areai51, @Wssn, @ndom91, @anthonyshort, @zxzl, @jbowes, @IamLizu, @PascalPixel, @ralphilius, @ysun62, @muslax, @elsigh, @AsherFoster, @botv, @tomdohnal, @christianalfoni, @tomasztunik, @gsimone, @illuminist, @jplew, @OskarKaminski, @RickyAbell, @steph-query, @ericgoe, @MalvinJay, @cristianbote, @Ashikpaul, @jensmeindertsma, @amorriscode, @abhik-b, @awareness481, @LukasPolak, @arvigeus, @romMidnight, @jackyef, @drumm2k, @kuldeepkeshwar, @bogy0, @Belco90, @wawjr3d, @tanmaylaud, @SarKurd, @kevinsproles, @dstotijn, @styfle, @blackwright, @BrunoBernardino, @heyAyushh, @Necmttn, @TrySound, @obedparla, @NyashaNziramasanga, @tonyspiro, @kukicado, @ceorourke, @MehediH, @robintom, @karlhorky, and @tcK1! | https://nextjs.org/blog/next-9-5 | CC-MAIN-2022-40 | refinedweb | 3,025 | 55.13 |
When.
Atelier
Continue Reading Post by John Murray 8 February 2018
Last comment 29 May 2018
Is there a function in Atelier that's equivalent to Studio's "Find in Files"? Namely, to search for assets containing a given search pattern across an entire namespace -- not just across files that are currently in the local project.
I've been playing with the search functions in Eclipse, and so far haven't found a combination of options that will search against assets that are only on the server -- I can only get results for assets that are already in my workspace.
Continue Reading Post by Marc Mundt 12 May 2016
Last answer 25 May 2016 Last comment 24 April 2018
Hi,
I know you're doing a big effort to build a new IDE in Eclipse ecosystem but Visual Studio Code is a new an even better and faster tool for coding... did you have any plans to release any COS extension for it in the near future? There you can already find extensions for all current more common progrmaming languages and it would be great to have COS as one of them.
Thanks
Continue Reading Post by Sergio Martinez 16 October 2017
Last answer 16 October 2017 Last comment 31 October 2017
Hi, Community!
Here is yet another video on InterSystems Developers YouTube Channel:
Atelier: Create a New Project and Add to Source Control
Continue Reading Post by Anastasia Dyubaylo 28 September 2017
Hi Community!
This week we have three videos. Check all new videos on InterSystems Developers YouTube Channel:
1. Using Atelier and Git, Moving your code to a new Repository
Continue Reading Post by Anastasia Dyubaylo 17 August 2017
Last comment 20 August 2017
The Atelier beta update channel:
offers the latest features and bug fixes. It now updates your installation of Atelier to build 1.1.291 for Mac, Windows, Red Hat and SUSE. Here’s an account of what’s recently been improved:
New Features:
Continue Reading Post by Joyce Zhang 23 June 2017
Last comment 25 June 2017.
Continue Reading Post by Jean Millette 20 April 2017
Last answer 20 April 2017.
Continue Reading Post by John Murray 3 March 2017
Last comment 6 April 2017
This.
Continue Reading Post by Istvan Hahn 6 January 2017?
Continue Reading Post by John Murray 14 March 2016
Last answer 5 January 2017 Last comment 5 January 2017
It feels like a couple of months since the last update (1.0.255) to the Field Test version.
Continue Reading Post by John Murray 1 December 2016
Last answer 1 December 2016
If you spend a lot of time working with javascript, json and html and you are new to Eclipse / Atelier you may like this tip.
Continue Reading Post by Mario Sanchez-Macias 10 November 2016
Deltanji 6.1 - new release of the integrated native source code management tool for Caché, Ensemble, HealthShare
We at George James Software recently released a new version of Deltanji, the native source code management tool for Caché, Ensemble and HealthShare.
Version 6.1 includes several enhancements, including easy creation of labels. Bulk transfer of large codesets is also now available from the browser UI.
A perpetually free "install and go" Solo Edition of Deltanji is available. Licenses can be purchased for other editions that provide more advanced code management and deployment features.
Deltanji is compatible with Atelier. It can also manage external files.
Continue Reading Post by John Murray 25 October
error Unable to create source control class: %Studio.SourceControl.ISC opening %SYS classes or routines
I am having a problem when using atelier on my instance, which I just synched from perforce on latest and then did a built
I am getting the error
ERROR #5880: Unable to create source control class: %Studio.SourceControl.ISC [zSourceControlCreate+17^%Studio.SourceControl.Interface.1:%SYS]
every time I want to open any class or routine from %SYS namespace in the Server tab.
Did someone had the same issue?
Mario
Continue Reading Post by Mario Sanchez-Macias 8 June 2016
Last answer 8 June 2016 Last comment 8 June 2016
I'm pleased to see the new Source Control menu in the recent 1.0.165 build. This gives me access to the features of the same server-side source control class as Studio has always supported. It is particularly relevant for our Deltanji source control tool.
Our class makes use of CSP to serve up some dialogs through which the user controls the source control operation. Two observations so far:
1. In Atelier the window you display our CSPs isn't resizable. In Studio it is.
Continue Reading Post by John Murray 25 May 2016
Last comment 25 May 2016
This is handy when debugging errors with a line reference and complex macros.
Continue Reading Post by Mike Henderson 17 April 2016
Last answer 18 April 2016 Last comment 18 April 2016
When I check for updates from by 1.0.116 I get this:
Continue Reading Post by John Murray 18 March 2016
Last answer 11 April 2016 Last comment 22 March 2016"
Continue Reading Post by James Bourette 17 March 2016
Last answer 24 March 2016
I am trying to debug a class on Atelier and it is not stopping at the defined breakpoint.
Atelier IDE Version: 1.0.107 - Cloud Connection
I have already taken a look at the Community´s Atelier Debugging Video and followed the steps without success.
Can anybody help me on that?
Tks.
Continue Reading Post by Fabio Goncalves 17 March 2016
Last answer 18 March 2016 Last comment 18 March 2016
Currently when class is saved in Atelier it is automatically saved on disk and on server (if there is an active connection).
Is there any way to save file with class or routine just on disk, but not on server?
Continue Reading Post by Alexander Koblov 4 March 2016
Last comment 4 March 2016
Atelier needs Java 1.8 to run, but manage diferent versions of Java can be tricky in OSX
Continue Reading Post by David Reche 2 December 2015
Last comment 25 February 2016
Continue Reading Post by Dmitry Maslennikov 4 February 2016
Last comment 15 February 2016
Are there any plans to translate Atelier to other languages (e.g. Russian) ?
Continue Reading Post by Alexander Koblov 4 February 2016
Last comment 4 February 2016
Continue Reading Post by William Beetge 17 January 2018
Last answer 28 February 2018 Last comment 28 February 2019
The Atelier update site domain has changed from artifactoryonline.com to jfrog.io. JFrog Artifactory Cloud has deprecated the artifactoryonline.com domain in favor of jfrog.io. See their announcement for more details.
Continue Reading Post by Michelle Stolwyk 17 January 2019.
Continue Reading Post by Michal Tomek 21 June 2016
Last answer 6 December 2018
Hi Community!
Please welcome a new video on InterSystems Developers YouTube:
Development Workflow in Atelier
Continue Reading Post by Anastasia Dyubaylo 11 October 2018
Beginner, Development Environment, Atelier 1.2 (Atelier), Application Server (Atelier), Atelier (Atel
Continue Reading Post by Thembelani Mlalazi 9 August 2018
Last answer 10 August 2018 Last comment 13 August 2018
Development Environment, Atelier 1.1 (Atelier), JavaScript (Atelier), CSP (Atelier), Atelier (Atel:
Continue Reading Post by heng a 7 August 2018
Last answer 7 August 2018 Last comment 8 August 2018 | https://community.intersystems.com/tags/atelier?filter=most_votes&%3Bamp%3Bpage=1&%3Bpage=4&page=2 | CC-MAIN-2019-35 | refinedweb | 1,223 | 59.64 |
C++ First ProgramPritesh
In the previous chapters we have learnt the basic history and some of the reasons why C++ is not portable like C# and Java.
Sample C++ Program
/* This is a simple C++ program. Call this file Sample.cpp. */ #include <iostream> using namespace std; // A C++ program begins at main(). int main() { cout << "C++ is power programming."; return 0; }
Output :
C++ is power programming.
Explanation : First C++ Program
Consider the following line in the programs –
/* This is a simple C++ program. Call this file Sample.cpp. */
- It is Comment in C++ Language which is ignored by compiler
#include <iostream>
- C++ uses different header files like C.
- Include statement tells compiler to include Standard Input Output Stream inside C++ program.
- This header is provided to user along with the compiler.
int main()
- Each C++ program starts with the main function like C Programming.
- Return type of the C++ main function is integer, whenever main function returns 0 value to operating system then program termination can be considered as smooth or proper.
- Whenever some error or exception occurs in the program then main function will return the non zero value to operating system.
cout << "C++ is power programming.";
- C++ Insertion operator (<<) is used to display value to the user on the console screen.
return 0;
- return statement sends status report to the operating system about program execution whether program execution is proper or illegal. | http://www.c4learn.com/cplusplus/cpp-first-program/ | CC-MAIN-2019-39 | refinedweb | 234 | 57.67 |
I am working on a platform, which doesn't have the math library, but I need to use the logf function (natural log with floating point input). I tried to search the code for logf but in vain. Can somebody provide or give a link for logf function code.
If you don't have math library, you can go to libc to look for the code ->;a=blob;f=math/w_logf.c
And see how logf calls __ieee754_logf ->;a=blob;f=sysdeps/ieee754/flt-32/e_logf.c
I hope it helps you.
I've seen a few references to logf() functions which just use casting around log(), such as:
float logf(float _X) { return ((float)log((double)_X)); } is an implementation of log() (though I have no personal experience with the function there, I merely found it while googling). | http://m.dlxedu.com/m/askdetail/3/6c8cdf9b2fa464ea5a910b57297033bd.html | CC-MAIN-2019-13 | refinedweb | 139 | 79.6 |
Joab Jackson published an article in National Geographic that give a very basic introduction of GeoRSS and a couple examples of it's use. One of the examples was Where's Tim!!
GeoRSS is a way to add geographic information to an RSS feed. Most generically, it is used to add a latitude / longitude point to an item. To add GeoRSS to your existing feed, add the namespace to your rss element like this:
<rss version="2.0" xmlns:
Then add the lat / long string between your item element tags, like this:
<georss:point>38.1333 -75.674georss:point>
item>
I use GeoRSS on Where's Tim for a couple different things. I generate an RSS feed as my location changes. Each item in the RSS feed represents a place that I was, and each item has a GeoRSS:Point that defines the lat / long point.
I also syndicate the text messages people send me. You can send a message to my phone by clicking the google icon on the map. You then enter an email address (if you want me to respond) and a message and it will go directly to my phone. Using my class that wraps the hostip.info API, I collect location information based on the users IP. I then generate a RSS feed where each item is a text message and I add a GeoRSS:Point if I was able to resolve the user's IP to a city / state.
Fun stuff! For more information, check out the official GeoRSS website.
Print | posted on Thursday, October 19, 2006 5:54 PM |
Filed Under [
.NET
GPS
Mapping
Where's Tim
] | http://geekswithblogs.net/thibbard/archive/2006/10/19/NationalGeographicTalksAboutGeoRSS.aspx | crawl-002 | refinedweb | 274 | 73.88 |
Correct scoping is one of the keys to success when developing large-scale programs. Paying too little attention to scoping often leads to spaghetti code that is difficult to understand, extend, or maintain. Java provides four standard scopes to restrict access to the data and methods in a class. However, custom-tailored scoping is occasionally desired on large projects, usually to avoid a choice between speed and safety. I'll show you how you can create custom scoping to avoid this tradeoff. Following the techniques described here, you should be able to do so without a significant increase in complexity.
Why scoping?
Scoping controls the depth of access to data and methods, and is one of the tools used to control large software projects. In a program with hundreds of thousands of lines of code, allowing one piece of code to modify any piece of data it wants rapidly leads to chaos. More restrictive scoping of data and methods -- private versus public, for example -- makes programs easier to understand, extend, and maintain, because you don't need to examine as much code when making changes. For small projects, scoping is often not critical -- if a program is only 10,000 lines long, it's easier to keep track of everything. For large projects with many programmers, however, scoping can be the difference between long-term success and failure. Keep in mind, then, that the techniques I present to you work for programs of all sizes, but are most appropriate for large applications.
Some scenarios
When is standard scoping insufficient -- and when is it not? I know of three cases when tailoring a scope to do exactly what you want is more practical than using a standard Java scope. Custom scoping can help you out when you want to:
- Disallow certain scripting capabilities
- Control mutability across packages
- Boost performance
We will consider each use in turn.
Disallowing certain scripting capabilities
A scripting language can add value to applications by allowing users to extend and tailor applications themselves. Occasionally, your application will have functionality that must be used cautiously, such as the ability to reset remote systems. You can restrict access to the GUI by adding a password and warnings to prevent accidents. However, you may wish to prevent scripting from making use of this capability entirely. In such a case, you would place the GUI and the forbidden functionality in the same package, and then create a reset function-package scope.
Sometimes, however, this isn't acceptable. In such cases, you need an approach that doesn't require packaging the GUI and the functionality together. Custom scoping allows the two to be separate, and still protects the functionality from scripting.
Controlling mutability
Creating objects in Java is slower than creating stack objects in C++. Because the cost of object creation in Java is higher than in C++, well-designed Java programs pay close attention to object creation than well-designed C++ programs. One way to safely create fewer objects in Java is to make them
immutable
-- to not provide a way for the object's state to be changed, in other words. An example of this in the standard libraries is the
String
class. If an object's state cannot change, references can be safely passed to the object throughout the application.
However, this doesn't always work. A data-processing program might start with an object containing raw data and slowly add information to the object as it passes through the application. A good example of this would be a stock-screening application that starts with objects containing raw stock data, and then adds more information -- the performance of a single stock relative to the industry, say -- as the objects are processed.
In a small application, you can provide the
add methods with a javadoc saying, in effect, "Don't call this unless you are the relative performance comparator." As the application gets larger, and more engineers work on it, this approach becomes riskier. Hardcoding restrictions into the program, instead of using comments and hoping that everyone reads them, allows the application to detect access bugs automatically.
Boosting performance
You occasionally need raw access to the internals of an object for speed. As an example, you might have an object containing a large array. The large array is private, and contains getters but no setters because the object is immutable:
public class ImmutableIntArray { private int[] data;
public ImmutableIntArray (int[] data) { this.data = data; }
int getElementAt (int index) { return data[index]; } }
There is no method that returns the raw data element, because this would defeat the purpose of making the object immutable. Occasionally, however, client code may need to process the contents of data quickly. Although it may take too long to return a copy of the data, working on the raw data element might be fast enough. It would be a reasonable design decision to grant access to data only to those clients who need it, and not to the entire application.
The custom approach
There are two aspects to the idea of creating custom scoping. First, class names, which are always strings, are visible throughout an application. And second, objects of various classes can only be created by a restricted set of clients.
You can create objects whose class names are visible to the entire program, but which can only be constructed by very restricted clients. The objects of these classes can then be used as key objects. Callers are required to pass in these key objects to method calls, and the method being called can check them against a list of legal keys.
Here's a working example of this:
public class Main { static public void main (String[] args) { try { System.out.print ("This should work ..."); ValidExampleCaller.sampleMethod(); System.out.println (" and it did."); } catch (InvalidKeyException e1) { e1.printStackTrace(); }
try { System.out.println ("This should fail ..."); InValidExampleCaller.sampleMethod1(); } catch (InvalidKeyException e2) { e2.printStackTrace(); } } }
/** * */ class InvalidKeyException extends java.lang.Exception { public InvalidKeyException (String message) { super (message); } }
class ExampleCallee { /** * This method prints 'Hi!' to standard out, but can only * be called by the ExampleCaller class. * * @param key 'key' is an object restricting access to this * method. If 'key' is not an instance of * class ValidExampleCaller.Key, an InvalidKeyException * is thrown. */ public static void sampleMethod (Object key) throws InvalidKeyException { if (key.getClass().getName().equals ("ValidExampleCaller$Key") == false) throw new InvalidKeyException("Can't call sampleMethod() with key " + key);
System.out.println ("Hi!"); } }
class ValidExampleCaller { static private final class Key { }
static public void sampleMethod () throws InvalidKeyException { ExampleCallee.sampleMethod (new Key()); } }
class InValidExampleCaller { static private final class Key { }
static public void sampleMethod1 () throws InvalidKeyException { ExampleCallee.sampleMethod (new Key()); } }
The
ExampleCaller class can call the
sampleMethod in
ExampleCallee successfully, but no other class can.
Before using this approach, you should consider a number of its details and implications:
ExampleCalleedepends on
ValidCaller's cooperation: The
ExampleCalleeclass depends on
ValidCallercooperation in enforcing the scoping restrictions.
ValidCallercan cheat by making the
Keyclass public, or by handing out references to
Keyobjects. However, even with standard scoping, legal callers can cheat. Our approach assumes cooperation between the valid caller classes and the callee, just as standard Java scoping does.
The
Keyobject is a static inner class: This means that both static and nonstatic member functions in the
ValidCallerclass have access to
sampleMethod. To prevent static methods from calling
sampleMethod, make the
Keyobject nonstatic.
The
Keyobject is a private inner class: Making
Keyprivate means that subclasses of
ValidCallercannot construct
Keyobjects. Making
Keya protected inner class grants access to child classes as well.
Keyneed not be an inner class:
Keycould be a package-scope class if your intent is to grant any class in a package access to
sampleMethod().
Keymust not be anonymous: The Java language does not specify a naming convention for anonymous inner classes, and different compilers generate different names for anonymous inner classes. Because of this, you should name the
Keyclass.
- The compiler can't help you: The compiler detects violations of standard scoping, but not custom scoping. If you use the approach illustrated here, you will not detect an illegal access until runtime. Detecting mistakes at compile time is preferable, of course, so you should use standard scoping if possible.
Conclusion
Standard Java scoping is sufficient for most projects. For large projects, however, you occasionally need to construct very specific scoping relationships. The approach to doing so presented in this article uses only the standard JDK 1.1 language constructs, and does not require any extensions to the Java language. This approach does add some complexity, though, so you should use it with caution. If you find yourself using this technique often, you need to reconsider your design.
Learn more about this topic
- The Java Programming Language, Ken Arnold and James Gosling (Addison Wesley, 1997) -- the official description of Java's inner classes
- See Appendix D to the above book on Sun's homepage, with updates for JDK 1.1
- "A look at inner classes," Chuck McManis (JavaWorld, October 1997) -- Java In-Depth columnist Chuck McManis provides a more gentle introduction to the topic of inner classes
- The Java Tutorial chapter on inner classes
- The inner classes specification from Sun for JDK 1.1
- To submit your Java Tip, go to the Java Index | http://www.javaworld.com/article/2077587/learn-java/java-tip-84--customize-scoping-with-object-keys.html | CC-MAIN-2017-13 | refinedweb | 1,536 | 54.32 |
Unity 2019.3.0 Beta 11
Sortie : 14. Nove 2019.3.0b11
2D: On deleting sprite from Sprite Light 2D, Scene and Game view doesn't update (1192998)
2D: [2d] Missing .meta file errors are thrown constantly after installing 2d Path package (1197018)
AI: Crash in NavMeshManager on Mobile with IL2CPP when using NavMeshComponents (1175557)
AI: Performance of NavMeshBuilder.UpdateNavMeshData spike up to 10 times (1183826)
Android: 64 bit Build with Physics.Processing runs at a very low FPS on Huawei Mate 20 Pro (1186295)
Animation: Animator.Update CPU time spikes when multiple animations are playing (1184690)
Asset Import Pipeline: Loading Scene files with removed Unity components results in uninformative errors (1179905)
Asset Importers: Changing PlayerSettings.GraphicsAPI reimports all textures regardless of their compression settings (1182352))
HDRP: When installing or upgrading to package version 7.1.2 type or namespace 'SerializedScalableSetting' can not be found (1194975))
Serialization: Crash on TypeTreeQueries::ReadStringFromBuffer or freeze when you add a component with SerializeReference interface (1187296)
Shuriken: Semaphore.WaitForSignal causes a slow editor when entering Play mode (1178300))
Vulkan: Standalone Build crashes when the build is made with API Compatibility Level with .NET 4.x or .NET Standard 2.0 (1193567)
Vulkan: [AMD] Editor crashes with vkDestroyDescriptor Pool when changing API to Vulkan (1197292)
Windows: [Graphics General] Editor crashes on changing Graphics APIs to Direct3D12 with X86_64 Architecture (1186810)
XR: [Oculus GO] PostProcessing effects are not applied to built applications (1103954)11 Entries since 2019.3.0b10
Fixes
Animation: Ensure GetKeyLeftTangentMode and friends are thread safe. (1195048)
Asset Import: Fixed issue that caused infinite import at editor start. Initialization of script compilation is now done inside the asset db. (1191267)
This has been backported and will not be mentioned in final notes.
Asset Pipeline: Current scene changes are lost when the scene is reloaded after shuffling its hierarchy in project (1169971)
This has been backported and will not be mentioned in final notes.
Asset Pipeline: Fixed cache server address field so it can resolve hostnames (1195038)
This has been backported and will not be mentioned in final notes.
Asset Pipeline: Fixed cache server v1 vs v2 performance regression (1191356)
Asset Pipeline: Fixed editor crash when trying to input correct IP in cache server settings (1190451)
This has been backported and will not be mentioned in final notes.
DX12: The editor no longer crashes when selecting a text mesh pro asset while using the DirectX 12 rendering API. (1193972)
This has been backported and will not be mentioned in final notes.
Editor: Disallow touching graphics API settings during playmode. (1194003)
Editor: Fix OS domain reload contextual submenu rebuilding (1193537)
Editor: Fixed display issue in inspector through SerializedProperty with enum fields contained in polymorphic managed classes (1187893)
Editor: Fixed Recursive Serialization error when using a UI component in the PresetManager. (1190809)
This is a change to a 2019.3.0a3 change, not seen in any released version, and will not be mentioned in final notes.
Editor: Open by file extension gives Win32Exception (1193800)
This has already been backported to older releases and will not be mentioned in final notes.
Editor: Overridden
OnInspectorGUImethod is now called properly when using
[CustomEditor(typeof(DefaultAsset))]. (1175246)
GI: Disable Realtime GI in Sample Scene for 3D template
This has been backported and will not be mentioned in final notes.
GI: Fixed issue were on one camera CullingGroup.QueryIndices doesn't work. Cameras are in the same location and using two CullingGroups with the same settings. (1181967)
This has already been backported to older releases and will not be mentioned in final notes.
Graphics: Fix for GPU memory leak when deleting a texture while async upload in progress. (1174689)
This has already been backported to older releases and will not be mentioned in final notes.
Graphics: Fixed an issue in Universal Render Pipeline causing point lights to not render correctly when not using the SRP Batcher. (1179976)
This is a change to a 2019.3.0a12 change, not seen in any released version, and will not be mentioned in final notes.
Graphics: Radeon Pro denoiser does not work when there are spaces in the path (1190167)
This is a change to a 2019.3.0a10 change, not seen in any released version, and will not be mentioned in final notes.
iOS: Fixed Applicaiton.Unload and Application.Quit to behave same as UnityFramework.Unload and UnityFramework.Quit
This is a change to a 2019.3 change, not seen in any released version, and will not be mentioned in final notes.
Licenses: Fixes issue where Trial watermark displays for Pro/Plus users (1193635)
This has been backported and will not be mentioned in final notes.
macOS: Fixed case 1183011: "Default is Native Resolution" checkbox is ignored if custom resolution was set before (1183011)
This has already been backported to older releases and will not be mentioned in final notes.
macOS: Fixed command events being processed twice on MacOS. (1180090)
This has been backported and will not be mentioned in final notes.
macOS: Fixed inconsistency between Screen.currentResolution and actual screen resolution. (1185536)
This has been backported and will not be mentioned in final notes.
macOS: Mac Standalone build does not contain .meta files inside native plugin bundles. (1178777)
This has been backported and will not be mentioned in final notes.
Physics: Fix pre-baked at build-time meshes becoming undetectable for collision, caused by the unsupported midphase being picked for non-desktop players (1179800)
This is a change to a 2019.3.0b1 change, not seen in any released version, and will not be mentioned in final notes.
Prefabs: Duplicated child nested prefab is not created in the same position (1157320)
This has been backported and will not be mentioned in final notes.
Prefabs: Fixed removed component override was not transferred during Copy/Paste or Duplicate operations. (1190501)
This is a change to a 2020.1.0a7 change, not seen in any released version, and will not be mentioned in final notes.
Prefabs: Fixed that the Overrides popup window did not refresh after undo. (1112996)
Profiler: Added a minimum Scale for stacked charts so that the 0.1ms grid line stays visible (1175473)
Profiler: Fixed "Other" Category not shown in Charts and hiding VSync time (1165477)
This has already been backported to older releases and will not be mentioned in final notes.
Profiler: Fixed argument exception for CPU Profiler Module's thread selection drop down (1184866)
This is a change to a 2019.3 change, not seen in any released version, and will not be mentioned in final notes.
Profiler: Fixed Audio Profiler view state restoring (1183981)
Profiler: Fixed broken CPU Profiler Module's detail drop down selection not working in Play Mode (1179845)
Profiler: Fixed deselection of samples in Hierarchy view (1102802)
This has already been backported to older releases and will not be mentioned in final notes.
Profiler: Fixed framing of Timeline View samples with Native Object association such as Camera.Render (1187889)
This has already been backported to older releases and will not be mentioned in final notes.
Profiler: Fixed high frequenzy rescaling of frame count label in toolbar (1181367)
Profiler: Fixed Profiler loosing previously serialized window state on domain reload (1184019)
This is a change to a 2019.3 change, not seen in any released version, and will not be mentioned in final notes.
Profiler: Fixed Profiler Window reopening to CPU Profiler Module even though a different module was previously active (1185208)
This has already been backported to older releases and will not be mentioned in final notes.
Profiler: Fixed retention of splitter and viewtype state within session and across open/close cycles of the ProfilerWindow (1171353)
Profiler: Fixed Thread names getting clipped in Thread Selection dropdown (1183285)
This is a change to a 2019.3 change, not seen in any released version, and will not be mentioned in final notes.
Profiler: Fixed Thread sorting in CPU Profiler (Hierarchy and Timeline) to be SemiAlphaNumeric (1152723)
This has already been backported to older releases and will not be mentioned in final notes.
Profiler: Fixed threadselection drop-down showing up in GPU Profiler Module (1184584)
This is a change to a 2019.3 change, not seen in any released version, and will not be mentioned in final notes.
Profiler: Fixed Timeline View not using a ColorSafe Palette (1101387)
This has already been backported to older releases and will not be mentioned in final notes.
Profiler: Fixed view resetting when changing the displayed frame count or color blind mode (1186566)
This is a change to a 2019.3 change, not seen in any released version, and will not be mentioned in final notes.
Profiler: Fixed view scale constraining of Profiler Timeline view when scrolling (1138060)
This has already been backported to older releases and will not be mentioned in final notes.
Scripting: Fix an issue of serialization layout validation to fail every other build. (1169148)
This has been backported and will not be mentioned in final notes.
Scripting: No performance regression. We will actually get better startup time if the user had a player build before, since we then will not recompile all again. (1188509)
Serialization: Reject application of [SerializeReference] to value types. (1182817)
This is a change to a 2019.3.0?0 change, not seen in any released version, and will not be mentioned in final notes.
Terrain: Fixed terrain shader picking pass for SRP. (1176497)
Timeline: Fixed DSP Clock update. (1169966)
This has been backported and will not be mentioned in final notes.
UI Elements: Fixed boxing allocation with the StyleEnum struct (1196706)
This has been backported and will not be mentioned in final notes.
UI Elements: ToolbarSearchField style fix (1196662)
This has been backported and will not be mentioned in final notes.
Version Control: Fix VCS Context menu failing to appear after upgrading project. (1188186)
This has been backported and will not be mentioned in final notes.
Version Control: Prevent Revert Unchaged from reimporting assets. (1181354)
This has been backported and will not be mentioned in final notes.
Version Control: Show a save prompt when trying to Submit modified scenes. (1185137)
This has been backported and will not be mentioned in final notes.
Windows: Fixed Windows Standalone Visual Studio solution build creating a '_Data' folder with the wrong name. (1186751)
XR: Fix Hololens 2 camera snapshots not containing Unity app content.
This has been backported and will not be mentioned in final notes.
XR: Restore mirror view default and disable present to main when provider requests it (1189948)
API Changes
- Serialization: Added: Exposed API documentation for [SerializeReference]
Improvements
- Graphics: Added image readback support for R32F and R16G16F, used by Texture2D.ReadPixels
This has been backported and will not be mentioned in final notes.
Features
-.
Preview of Final 2019.3.0b)
Graphics: Fix SRP Batcher graphical artifacts with more accurate float to half conversion (1136206)) Meshes with Keep Quads enabled would not be rendered. (1179051)
Graphics: Fixed an issue where the Preview Camera had an incorrect type. (1163371)): Comparing the depth of nested Canvases now uses the depth value used for rendering. Depth values that are set but not used are ignored. (1176348)
UI: Composition string is now only updated if an
inputFieldis selected.:.: 1781308d0868 | https://unity3d.com/fr/unity/beta/2019.3.0b11 | CC-MAIN-2021-25 | refinedweb | 1,855 | 54.73 |
Item Transformers
Link to item-transformers
Item Transformers transform your crafting inputs upon crafting.
This can range from damaging the item up to returning a completely different item.
Importing the package
Link to importing-the-package
It might be required for you to import the package if you encounter any issues (like casting an Array), so better be safe than sorry and add the import.
import crafttweaker.item.IItemTransformer;);
Registering own item Transformers
Link to registering-own-item-transformers
Transform
Link to transform
The old itemTransformer that might cease to exist in 1.13.
Thisis a special function that accepts two parameters: The item itself and the player performing the crafting.
ZenScriptCopy
transformedItem = item.transform(function(item, player) {return item;});
The function needs to return an IItemStack.
This stack will replace what's in the crafting slot afterwards. Use
null to clear that slot.
TransformNew
Link to transformnew
With the new internal recipe system there was a need for a new ItemTransformer. This one only accepts one parameter, that is the item in the slot.
ZenScriptCopy
transformedItem = item.transformNew(function(item){return item;});
The function needs to return an IItemStack.
Unlike the other transformer however, this will not be the itemstack that replaces the one in the crafting slot, but the one that is returned for that crafting slot.
In other words if you return
null here, one item will be consumed, any other item that is returned will either be placed in the crafting slot, if possible, or given back to you, same as when dealing with buckets.
If you don't really need the player variable, this is the transformer to go for! | https://docs.blamejared.com/1.12/en/Vanilla/Items/Item_Transformers | CC-MAIN-2022-40 | refinedweb | 275 | 55.13 |
HelloI tryed to build kqemu on FC5 using 2.6.16-1.2080_FC5 and it fails because map_mem is undeclared. The attached patch fixes it for me (remove to defines) but its likly to break older kernels. So a better one is needed.
Anyway I decided to report it here. Patch is attached. PS: Please CC me as I am not suscribed to the list.
diff -ru kqemu-1.3.0pre5.org/kqemu-linux.c kqemu-1.3.0pre5/kqemu-linux.c --- kqemu-1.3.0pre5.org/kqemu-linux.c 2006-03-27 22:58:01.000000000 +0200 +++ kqemu-1.3.0pre5/kqemu-linux.c 2006-04-12 09:20:10.000000000 +0200 @@ -22,12 +22,12 @@ #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,19) #error "Linux 2.4.19 or above needed" #endif - +/* #ifndef page_to_pfn #define page_to_pfn(page) ((page) - mem_map) #define pfn_to_page(pfn) (mem_map + (pfn)) #endif - +*/ #ifdef PAGE_KERNEL_EXEC #if defined(__i386__) /* problem : i386 kernels usually don't export __PAGE_KERNEL_EXEC */ | http://lists.gnu.org/archive/html/qemu-devel/2006-08/msg00295.html | CC-MAIN-2014-52 | refinedweb | 158 | 63.15 |
Bindings for the wrecked terminal graphics library
Project description
wrecked_bindings
Python bindings for the wrecked terminal interface library.
Installation
Can be installed through pip
pip install wrecked
Usage
import wrecked # Instantiates the environment. Turns off input echo. top_rect = wrecked.init() # create a rectangle to put text in. new_rect = top_rect.new_rect(width=16, height=5) # Add a string to the center of the rectangle new_rect.set_string(2, 3, "Hello World!") # Make that rectangle blue new_rect.set_bg_color(wrecked.BLUE) # And finally underline the text of the rectangle new_rect.set_underline_flag() # Draw the environment top_rect.draw() # take down the environment, and turn echo back on. wrecked.kill()
Project details
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/wrecked/1.0.10/ | CC-MAIN-2021-49 | refinedweb | 126 | 62.04 |
Created attachment 652504 [details] [diff] [review]
copy it
Luke / cjones, do you mind if I review this in Waldo's absence?
Waldo is persnickety about style in mfbt, so please forgive me for even more
nits than I would usually give.
How would you feel about making this into a proper C++ class?
>diff --git a/mfbt/Sha1.cpp b/mfbt/Sha1.cpp
I'd prefer SHA1.{cpp,h}; that matches the API.
>+#include <memory.h>
Is this necessary?
>+#include <endian.h>
Does this actually work cross-platform?
>+#include "mozilla/Sha1.h"
>+#include "Assertions.h"
mozilla/Assertions.h, if only for consistency.
The rest of this file doesn't exactly follow MFBT style, but that doesn't
really bother me, since I don't expect anybody to be hacking on this code.
>diff --git a/mfbt/Sha1.h b/mfbt/Sha1.h
>+/* This Source Code Form is subject to the terms of the Mozilla Public
>+ * License, v. 2.0. If a copy of the MPL was not distributed with this
>+ * file, You can obtain one at. */
This file needs two separate comments at the top: A short, one-liner picked up
by MXR, and a longer comment explaining how to use the interface. See e.g.
HashFunctions.h.
>+#ifndef _SHA1_H_
>+#define _SHA1_H_
mozilla_SHA1_h_
>+#include <stdint.h>
mozilla/StandardInteger.h
>+namespace mozilla {
>+ struct SHA1Context {
>+ union {
>+ uint32_t w[16]; /* input buffer */
>+ uint8_t b[64];
>+ } u;
>+ uint64_t size; /* count of hashed bytes. */
>+ unsigned H[22]; /* 5 state variables, 16 tmp values, 1 extra */
>+ };
>+
>+ void SHA1_Begin(SHA1Context *ctx);
>+ void
>+ SHA1_Update(SHA1Context *ctx, const unsigned char *dataIn, unsigned int len);
No need to wrap this; you're allowed 100 chars per line in this module.
>+ void SHA1_End(SHA1Context *ctx, unsigned char hashout[20]);
>+}
} /* namespace mozilla */
Also, please don't indent inside namespace declarations.
>+#endif
#endif /* mozilla_SHA1_h */
?
>diff --git a/mfbt/tests/TestSha1.cpp b/mfbt/tests/TestSha1.cpp
>+int main() {
Newline before open brace. (Sorry.)
>+ SHA1Context Ctx;
>+ SHA1_Begin(&Ctx);
>+ unsigned char hash[20];
>+ SHA1_Update(&Ctx, (const unsigned char*) TestV, sizeof(TestV));
>+ SHA1_End(&Ctx, hash);
>+ const unsigned char expected[20] = {
>+ 0xc8, 0xf2, 0x09, 0x59, 0x4e, 0x64, 0x40, 0xaa, 0x7b, 0xf7, 0xb8, 0xe0,
>+ 0xfa, 0x44, 0xb2, 0x31, 0x95, 0xad, 0x94, 0x81};
>+
>+ for (unsigned int i = 0; i < 20; ++i) {
>+ if (hash[i] != expected[i])
>+ return 1;
Brace if.
>+ }
>+ return 0;
>+}
r=me with nits addressed, although if we want to make this into a C++ class
(which would be an improvement, I think), I'd like to have another look.
(In reply to Justin Lebar [:jlebar] from comment #3)
> Waldo is persnickety about style in mfbt, so please forgive me for even more
> nits than I would usually give.
thorough and fast reviews are nothing to apologize for :-)
> How would you feel about making this into a proper C++ class?
I think it is a good idea. I will upload a new patch in a sec.
> >+#include <memory.h>
>
> Is this necessary?
No, string.h is a better one. Replaced.
> >+#include <endian.h>
>
> Does this actually work cross-platform?
No, fixed :-(
> ?
I know we need to link mfbt library to the test (the existing tests work with just the headers). I am not completely sure if this is the canonical incantation. I will ask for feedback. On it.
Created attachment 652589 [details] [diff] [review]
create a c++ class
Asking for khuey's feedback on the change to mfbt/tests/Makefile.in.
Comment on attachment 652589 [details] [diff] [review]
create a c++ class
>+++ b/mfbt/SHA1.cpp
>@@ -0,0 +1,342 @@
>+/* This Source Code Form is subject to the terms of the Mozilla Public
>+ * License, v. 2.0. If a copy of the MPL was not distributed with this
>+ * file, You can obtain one at. */
>+
>+#include <string.h>
>+#include "mozilla/SHA1.h"
>+#include "mozilla/Assertions.h"
>+
>+// FIXME: We should probably create a more complete mfbt/Endian.h. This
>+// that any compiler that doesn't define these macros is little endian.
"This /assumes/ that"?
>diff --git a/mfbt/SHA1.h b/mfbt/SHA1.h
>new file mode 100644
>--- /dev/null
>+++ b/mfbt/SHA1.h
>@@ -0,0 +1,39 @@
>+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
>+/* This Source Code Form is subject to the terms of the Mozilla Public
>+ * License, v. 2.0. If a copy of the MPL was not distributed with this
>+ * file, You can obtain one at. */
>+
>+/* Simple class for computing SHA1. */
>+
>+/*
>+ * The constructor initializes the class, so the user only need to call the
>+ * update method on the data he wants the SHA1 of:
s/need/needs
But I'd rework this not to focus on the work the constructor does, and also to
provide a complete, working example of using the class. (That is, give types
for buf1/buf2.) Also, please approximate Gecko coding conventions in your code
sample -- don't user upper-case variable names.
Maybe "Example usage: {{your code}}" is sufficient.
>+#ifndef mozilla_SHA1_h_
>+#define mozilla_SHA1_h_
>+
>+#include <stdint.h>
>+namespace mozilla {
>+class SHA1Sum {
>+ union {
>+ uint32_t w[16]; /* input buffer */
>+ uint8_t b[64];
>+ } u;
>+ uint64_t size; /* count of hashed bytes. */
>+ unsigned H[22]; /* 5 state variables, 16 tmp values, 1 extra */
>+
>+public:
>+ SHA1Sum();
>+ void Update(const unsigned char *dataIn, unsigned int len);
>+ void End(unsigned char hashout[20]);
MFBT style is lowerCase method names (I know...), so s/Update/update/, s/End/end/.
Do you think "addBytes", "addData", or "addToHash" would be a better name for Update? And for "End", maybe "finish"?
The signature of End() makes it impossible to pass anything but a stack buffer, right? We should just make it take a const unsigned char*, in that case, and have a scary warning about how much memory must sit behind the pointer.
We should make 20 a public static const on the SHA1Sum class so people don't have to hardcode it.
It's an error to call End() twice, right? Can we assert that? We should also
assert that Update isn't called after End. And we should indicate these
restrictions in the header file.
Anyway, this is good. :)
> Do you think "addBytes", "addData", or "addToHash" would be a better name for Update?
Eh, it seems like most everybody uses "update".
Python and BouncyCastle both call "end" "digest()"; maybe that's better?
Created attachment 652628 [details] [diff] [review]
new version
I changed End to finish. I think that is a slightly better name as it suggests that it should be used after update.
I kept the signature with char[20]. I can be used with heap allocation. A struct can have a "char sha1[20]" member for example. The only thing that would require a cast is computing a sha1 in the middle of a plain char buffer. Do you expect that to be a common case?
> I kept the signature with char[20].
I just asked about this on IRC, because I was confused. I thought you couldn't do
void bar(char buf[20]);
void foo() {
char *buf;
bar(buf);
}
but you can, and it works fine. In fact, you can pass a char[19] without complaint as well.
So as far as we can tell on IRC, there's no difference between char buf[20] and char* buf.
...sorry, accidentally clicked the button.
There's no difference between |char buf[20]| and |char* buf| /as a function argument/.
So we might as well use char buf[20], since it tells us how much space you're expecting.
> + * Using this class a function to compute the SHA1 of a buffer can be written
> + * as:
Please move "using this class" after "buffer", and put an empty line between paragraphs (here and elsewhere in the comment).
+ * void SHA1(const unsigned char* buf, unsigned size, unsigned char hash[20])
I was actually thinking we might want to make this exact signature a static method on SHA1Sum. But, later. :)
+ * {
+ * SHA1Sum S;
+ * S.update(buf, size);
+ * S.finishnd(hash);
+ * }
finishnd
There's been a suggestion on IRC that we should use uint8_t instead of unsigned char. I do agree we should use uint32_t for the length; we try to avoid bare int types, in general, because they have different lengths. So if we use uint32_t, we might as well use stdint types everywhere. So if you don't mind, maybe that can be our last change here.
Comment on attachment 652628 [details] [diff] [review]
new version
Review of attachment 652628 [details] [diff] [review]:
-----------------------------------------------------------------
The build stuff looks ok, although I don't really understand the motivation for putting an SHA-1 hash in mfbt.
> I don't really understand the motivation for putting an SHA-1 hash in mfbt.
It's going to be used by write-poisoning code, which needs to compute hashes after XPCOM shutdown. | https://bugzilla.mozilla.org/show_bug.cgi?id=781627 | CC-MAIN-2016-22 | refinedweb | 1,448 | 74.69 |
Unity User Guide
For users who have used Unity3D before, they will find it extremely easy when starting to use Cocos Creator because many concepts are interlinked between the two. However, there still are some differences between Cocos Creator and Unity3D on some detailed concepts. This document will enumerate the differences between Cocos Creator and Unity3D to help Unity3D users learn to use Cocos Creator more quickly.
Abstract
- The API of Firball use camelCase. The first letter of the method and variable is in lowercase. The first letter of the category definition is in uppercase.
- The callback of Firball follows the style of Node.js, which means the first parameter of the callback is wrong information.
cc.Node vs GameObject
Node in Cocos Creator equals to GameObject + Transform in Unity3D. In Cocos Creator, the hierarchical relation of the parent and child nodes is maintained by Node. But in Unity3D, it's in the charge of Transform.
// change the parent-child relation this.node.parent = anotherNode; // rotate by 20 degrees this.node.rotation += 20; // shift by pixcels of (10,10) this.node.position.x += 10; this.node.position.y += 10; // zoom in/out for 1.5 times this.node.scale.x *= 1.5; this.node.scale.y *= 1.5;
Coordinate system
position,
rotation and
scale in cc.Node are both in the local coordinate system. As for Unity3D, its
Postion,
Rotation is in the world coordinate system.
In Cocos Creator, if you want to calculate the world coordinate of cc.Node, you can use the following method:
// set up the node to the position of (100,100) in world coordinate system this.node.position = this.node.convertToNodeSpaceAR(cc.v2(100,100)); // this.node.rotation = TODO
cc.Component vs MonoBehaviour
In Cocos Creator, the user defined script is written by extending the cc.Component category. But in Unity3D, it's written by extending MonoBehaviour. Let's compare a Cocos Creator script with a Unity3D script that has the same functions:
Unity3D:
public class Foobar : MonoBehaviour { public string text = 'Foobar'; void Start () { Debug.Log('Hello ' + text ); } void Update () {} }
Cocos Creator:
// Foobar.js cc.Class({ extends: cc.Component, properties: { text: 'Foobar', }, onLoad: function () { console.log('Hello ' + this.text); }, update: function (dt) {}, });
Property definition
In Cocos Creator, properties are defined in the
properties field. But in Unity3D, properties are defined as
member variables of MonoBehaviour. Apart from differences in the defining positions, Cocos Creator also imports the concept of the property parameter into the property. These parameters can be used to control
the display method of properties in Inspector, serialization, etc. For detailed parameters, please refer to: [/manual/scripting/attributes]
The following are defining methods of some commonly used properties in Cocos Creator:
var MyEnum = cc.Enum({ Foo: 1, Bar: 2, }); // MyScript.js var Foobar = require('Foobar'); cc.Class({ extends: cc.Component, properties: { // quote other cc.Node // in Unity3D, it is defined as: public GameObject otherGameObject; otherNode: { default: null, type: cc.Node }, // quote a concrete example of Foobar Component // in Unity3D, it is defined as: public Foobar foobar; foobar: { default: null, type: Foobar }, // do not serialize this property // in Unity3D, it is defined as: [System.NonSerialized] public int index = 0; index: { default: 0, type: cc.Integer, serializable: false }, // define an array // in Unity3D, it is defined as: public float[] idList; idList: { default: [], type: cc.Float }, // define an enumerated category // in Unity3D, it is defined as: public MyEnum myEnum = MyEnum.Foo; myEnum: { default: MyEnum.Foo, type: MyEnum }, } })
Life cycle
The life cycle of Cocos Creator is basically the same as Unity3D, having only slight differences in the naming:
- When you want to destroy a cc.Object concrete example (such as: node, component or asset), you can use obj.destroy() function.
- When you want to determine whether a cc.Object concrete example(such as: node, component or asset) is destroyed or not, you can use cc.isValid(node).
The message system of Cocos Creator uses the transmit&receive mode of dom, which can send a message upward, but you need to sign up for message in Node. But in Unity3D, messages are realized by going through SendMessage and directly responding to the member function defined in the script.
The following is the transmit&receive mode of message in Cocos Creator:
cc.Class({ extends: cc.Component, onLoad: function () { this.node.on('hello-foobar', function ( event ) { event.stopPropagation(); console.log('Hello Foobar'); }); }, start: function () { this.node.emit('hello-foobar'); }, })
Continue on to read about Project Structure. | http://cocos2d-x.org/docs/editors_and_tools/creator-chapters/getting-started/unity-guide/ | CC-MAIN-2017-22 | refinedweb | 737 | 51.24 |
.
The AdWords API Developer's Guide describes how to use the Google AdWords API to manage your AdWords accounts.
This guide is intended for developers who want to programmatically access AdWords accounts. It assumes that you are familiar with web services and with the programming language you will be using. It also assumes you are familiar with Google AdWords in general.
Documentation for each supported version of AdWords API is embedded into this single guide. To view documentation for a specific version of the API, select it from the drop-down list in the top-right corner. You can also use this drop-down menu to view differences between two versions. When viewing differences, added text will display underlined and green and removed text will display with
strikethrough.
Note: This guide uses a cookie to persist the version selection between pages. If you have cookies disabled, pages within this guide will always display the latest version upon loading.
Using the AdWords API, you can create and manage campaigns, ad groups, keywords, and ads. You can also generate keyword suggestions, get traffic estimates for predicted impressions, receive clicks and clickthrough rates, and retrieve reports on actual performance.
To access and manage your AdWords account using the AdWords API, you build a client application that connects to one or more of the provided web services. While each service can be used independently, most real-world scenarios (such as adding a new campaign that has ad groups, ads, and keywords) require a client application to use multiple services.
The core messaging technology for the AdWords API is Simple Object Access Protocol (SOAP), which is an XML- and HTTP-based protocol with wide support in the industry. The AdWords API uses document/literal style SOAP 1.1.
The AdWords API is composed of the following web services:
CampaignService
The Campaign Service lets you create, list, and modify campaigns. For instance, you can change the name, set the daily budget, and define the end date. It also lets you perform actions on a campaign, such as pausing the campaign.
AdGroupService
The AdGroup Service lets you create ad groups, list ad groups, associate ad groups with a campaign, and perform actions. For example, you can set the cost-per-click for all keywords in the ad group.
CriterionService
The Criterion Service lets you get information about targeting criteria. For example, you can get the keywords for a keyword-targeted campaign or the websites for placement-targeted campaigns. You can create and modify keyword and website targeting criteria.
AdService
The Ad Service lets you create and modify ads, and associate them with an ad group.
SiteSuggestionService
The Site Suggestion Service lets you estimate the performance of keywords, ad groups, and campaigns.
TrafficEstimatorService
The Traffic Estimator Service lets you estimate the performance of keywords, ad groups, and campaigns. You can estimate data, such as the cost-per-click, clickthrough rate, and average position of your ads.
KeywordToolService
The Keyword Tool Service lets you generate keywords based on a seed keyword or on the words found on a web page or web site that you provide.
ReportService
The Report Service lets you generate reports on the performance of your AdWords campaigns. For example, you can get reports on the daily number of impressions, clicks, and clickthrough rate. Advertisers who administer accounts on behalf of other people can get reports about their clients' AdWords accounts.
InfoService
The Info Service lets you get basic information about how much you have used the AdWords API.
AccountService
The Account Service lets you create and modify AdWords accounts.
For more information on each web service, see the Web Services Overview.
For more information about AdWords accounts, including campaigns, ad groups, keywords, and ads, see the Google AdWords website at.
Here are some quick links to more information:
Before using the AdWords API, you need to sign up at the AdWords API Developer Website. Following the sign-up process, your information will be reviewed and, upon approval, you will be issued two tokens: a Developer Token, which uniquely identifies the developer and tracks your API unit usage, and an Application Token, which uniquely identifies an application that makes requests to the AdWords API.
Both tokens are required to access the AdWords API. They must be included in the header of every request, as discussed in the section Request Header.
Calls to AdWords API web services are charged to your account in the form of API units. Charges accrue at a rate of US$0.25 (or local currency equivalent) per 1000 API units consumed, where an operation is the smallest unit of work, for example, setting the bid on a single keyword. A single SOAP call can contain many operations. See Usage & Fees for more details.
Although some advertisers may be eligible for free API units, all developers must provide billing information during the sign-up process. Advertisers will be informed if they are eligible for free API units when their tokens are approved.
Every time you send a request to the AdWords API web services, the header of the request must include your Developer Token, as discussed in the section Request Header, so that your usage can be tracked and billed accordingly. You must also include your Application Token so your application access may be tracked.
You can use
InfoService to see your current API usage, for example, to see how many operations you performed during a given date range.
To use the AdWords API, write a client program in a language of your choice (such as Java, Perl, Python, C, C++, PHP). Write your client program to send a request to one of the AdWords Web Services, such as
TrafficEstimatorService or
AdGroupService. The relevant service will process the request and send back a response, which your client program needs to parse.
Since the AdWords API is a set of web services, there is nothing that you need to install related to the AdWords API. The only software you need to install to use the AdWords API is the software for the language and toolkit that you will be using to write your client programs. For example, if you intend to write your client programs in Java, you will need to install Java and also a SOAP toolkit such as Axis. See the section SOAP Toolkits for a list of possible toolkits for various languages.
The operations provided by a web service are defined in a WSDL file. Before connecting to a web service, you need to know the URL that points to its WSDL file. Each AdWords API web service has its own WSDL. The URL for each WSDL has the following form, where
N is the version number and SERVICE_NAME is the service name:
For example, this is the URL for the v12 CampaignService WSDL:
The details of how your client application connects to the WSDL depends on the programming language and SOAP toolkit being used. SOAP toolkits typically provide a function for connecting to a service at a specified URL. For example, the following Perl code connects to the v12
CampaignService:
# Specify the WSDL $url = # Connect to the service using the SOAP::Lite toolkit my $service = SOAP::Lite->service($url);
After establishing a connection to the web service, your client application use the web service to perform any of the operations supported by the web service. For example, after connecting to
CampaignService, a client program could send an
addCampaign request to add a new campaign.
Uppercase types, such as
Campaign and
NetworkType, shown throughout this guide's API Reference are complex data structures or enumerations defined in the WSDL.
Lowercase types, such as
boolean and
string, shown throughout this guide are XML Schema datatypes in the following namespace:
A developer is issued a Developer Token and Application Token when they register to use the AdWords API. Each request to the AdWords API requires a valid Developer Token and Application Token as part of the request header — both are required to access the API.
Uniquely identifies the developer and is used to track your API unit usage. To safeguard your privacy and protect yourself from fraudulent charges by other users, you should not share your Developer Token with other users. You can find your Developer Token listed on your AdWords API Center, accessible from your My Client Center's "My Account" tab.
Uniquely identifies an application that makes requests to the AdWords API. If your application calls another application, use the Application Token corresponding to the one that actually sends the request. You will need a different Application Token for each application you develop that uses the AdWords API. To request additional tokens, simply click the "add" link in the "Your Application Tokens" section of your AdWords API Center.
For information on how to include these tokens with your requests, see Request Header below.
You should link your My Client Center (MCC) account to the client account you want to manage. Then, when making an API request, you must include in the request header the email and password of the MCC plus the login email or client customer identification (ID) of the client account.
Note that there are two ways to link your MCC to a client account: "User Interface and API" or "API only". While both give you API access, only one will fully credit the client account's spend towards your API unit usage. For more information, read our FAQ about My Client Center and API-Only access levels.
For instructions on linking your MCC to client accounts, see How to link an account. For frequently asked questions about MCC, see MCC Help Center.
Note: Security features are designed to prevent unauthorized account access by detecting suspicious login attempts and then blocking access to that account. This happens, for example, if a program attempts to login with an incorrect password too many times. If you attempt to access a blocked account, it will return error code 86, account blocked. To unblock the account, see Error Code 86.
The following header elements are required for requests sent to the AdWords API web services:
Password for the AdWords account being accessed.
An arbitrary string that identifies the customer sending the request.
Note: In other contexts, a
useragent header element identifies the browser or client application that is sending a request. In the AdWords API, the
useragent element instead identifies the customer making the request and optionally describes the purpose of the request.
A string that uniquely identifies an AdWords API developer. An example developer token string is
ABcdeFGH93KL-NOPQ_STUv. Developer tokens are 22 characters long.
A string that uniquely identifies an application that's authorized to access the AdWords API web services. Always use the applicationToken corresponding to the application that directly calls AdWords API. An example token string is
ZYXwvu-TSR123_456ABCDE. Application tokens are 22 characters long.
The following header elements are optional. You can set either
clientEmail or
clientCustomerId, but not both:
An email address that uniquely identifies a client of an MCC. This header element is only applicable if you have an account with My Client Center (MCC). Provide the
clientEmail header element when you want to edit a client's account rather than your own MCC account. If this element is provided, the AdWords API assumes that the account being accessed is the one belonging to the user specified in the
clientEmail element. The client named in
clientEmail must be managed by the MCC master named in
Note: You are still required to pass the
<password/> header elements that specify your own email and password for authentication purposes.
A number, such as
123-456-7890, that uniquely identifies a client of an MCC. You can provide this header element in place of the
clientEmail.
The exact details of how the client program specifies a header depends on the language and the toolkit being used, but usually the toolkit has a function for setting a header value. For examples of setting header requests in various toolkits, see the code samples.
For an example of XML code for setting a request header, see the section SOAP Request Example further down this page.
All responses returned from the AdWords API web services include the following header elements. As a best practice, we recommend that you log these values.
Uniquely identifies this request. If you have any support issues, sending us this ID will enable us to find your request more easily.
Number of operations in the request.
Number of API units the request used.
Elapsed time between the web service receiving the request and sending the response.
For an example of XML code for a response header, see the section SOAP Response Example below.
The AdWords API supports multiple recent versions of the WSDL to allow developers time to migrate to the most recent version. Once an earlier version of the WSDL has been replaced by an updated version, the older version will be supported for four months after the launch of the newer version.
During this period, the AdWords API will continue to provide developer access to and documentation support for any version dating back two months.
You can tell which version of the WSDL you are accessing based on its URL, which includes the version number. Version names are of the form vN.
The Release Notes summarizes changes between versions. In addition, new versions and shutdowns of older version are announced via the AdWords API Blog.
The term "deprecated" is a warning to the developer that an API feature will probably be removed from a later version — notice that the feature will not normally be removed from the version where it is documented as deprecated, so you can continue using it in that version. The text in the deprecation note should explain which API feature replaces the deprecated one, if any. When you modify your code to support a later version, you should plan accordingly. Deprecated can apply to a service, data object, request or field.
The AdWords API Web Services use document.
For the AdWords API, all API messages are sent via HTTPS requests. The XML for the SOAP request is sent as an HTTP POST request with a special
SOAPAction header; the response is sent back as the response to the POST. All AdWords API calls are encrypted with SSL (that is, as HTTPS) to protect the privacy of your data.
The requests that a web service can process are defined in a web services definition language (WSDL) file in XML. The WSDL file describes the operations that the web service can perform, the required parameters for each operation, and the response for each operation.
Typically, to use the AdWords API Web Services, you would download a toolkit that knows how to interpret WSDL files and how to encode and decode XML request and response messages. When an web service receives a request, it sends back the response as an XML message. The web service toolkits know how to parse the response and return a data structure or object back to the caller.
The SOAP toolkit you use depends on the programming language your client is written in. For information on the toolkits we have tested, see SOAP Toolkits.
If you use a SOAP toolkit, you should rarely have to write XML code to use the AdWords API Web Services, since the toolkits handle the XML generation. Some toolkits, however, may require you to hand-code some of the XML yourself. For example,
nusoap.php, requires you to write the XML code for input parameters.
Note: The AdWords API uses document/literal style SOAP, not RPC/encoded style. Some toolkits work differently for document-style web services than for RPC-style.
It can sometimes be helpful to capture the XML request and response messages for debugging purposes. See How do I view the XML code generated by the request and response?.
To learn more about SOAP, see the SOAP Tutorial at W3Schools.
This section provides examples of WSDL files and XML request messages.
The following code is an example of a SOAP request. The header sets the login email and password along with a
useragent string. The body of the message requests a traffic estimate for the keyword
flowers at a maximum cost-per-click (maxCPC) of 50000 micros, which in US currency is 5 cents. (Micros are millionths of the fundamental currency unit.)
<soap:Envelope xmlns: <soap:Header> <email>loginemail@youraccount.com</email> <password>secretpassword</password> <useragent>Your User Agent description</useragent> <developerToken>_developer_token_here_</developertoken> <applicationToken>_application_token_here_</applicationtoken> </soap:Header> <soap:Body> <estimateKeywordList> <keywordRequests> <type>Broad</type> <text>flowers</text> <maxCpc>50000</maxCpc> </keywordRequests> </estimateKeywordList> </soap:Body> </soap:Envelope>
The following code shows an example of a SOAP response that has the information about the traffic estimates for the previous request.
<soapenv:Envelope xmlns: <soapenv:Header> <responseTime soapenv: 10636 </responseTime> <operations soapenv: 1 </operations> <units soapenv: 1 </units> <requestId soapenv: eb21e6667abb131c117b58086f75abbd </requestId> </soapenv:Header> <soapenv:Body> <estimateKeywordListResponse xmlns=""> <estimateKeywordListReturn> <avgPosition>2.9376502</avgPosition> <cpc>50000</cpc> <ctr>0.01992803</ctr> <id>-1</id> <impressions>62823</impressions> <notShownPerDay>139255</notShownPerDay> </estimateKeywordListReturn> </estimateKeywordListResponse> </soapenv:Body> </soapenv:Envelope>
The requests that a web service can process are described in XML in a web services definition language (WSDL) file. The WSDL file describes the operations that the web service can perform, the required parameters for each operation, and the response for each operation. The complete definition of a single operation can be fairly complex. For example, the definition in the AdGroup Service WSDL for the
getName operation, which gets the name of an ad group, given its id, is:
<element name="getName"> <complexType> <sequence> <element name="adgroupID" type="xsd:int" /> </sequence> </complexType> </element> <element name="getNameResponse"> <complexType> <sequence> <element name="getNameReturn" type="xsd:string" /> </sequence> </complexType> </element> <wsdl:message <wsdl:part </wsdl:message> <wsdl:message <wsdl:part </wsdl:message> | http://code.google.com/apis/adwords/docs/developer/index.html | crawl-002 | refinedweb | 2,969 | 53.31 |
This action might not be possible to undo. Are you sure you want to continue?
8884
New York Liberty Zone Business Employee Credit
Attach to your tax return.
OMB No. 1545-1785
Department of the Treasury Internal Revenue Service
Attachment Sequence No. Identifying number
2002
132
Name(s) shown on return
Part I
1
Current Year Credit (Members of a controlled group, see instructions.)
Enter the total qualified wages paid or incurred during the tax year to New York (NY) Liberty Zone business employees for work performed during 2002 or 2003 who have:
1a 1b 2
$ 25% (.25) = a Worked for you at least 120 hours but fewer than 400 hours b Worked for you at least 400 hours $ 40% (.40) = 2 Add lines 1a and 1b. You must subtract this amount from your deduction for salaries and wages 3 NY Liberty Zone business employee credits from pass-through entities:
If you are a— a Shareholder b Partner c Beneficiary d Patron Then enter the NY Liberty Zone business employee credits from— Schedule K-1 (Form 1120S), lines 12d, 12e, or 13 Schedule K-1 (Form 1065), lines 12c, 12d, or 13 Schedule K-1 (Form 1041), line 14 Written statement from cooperative
3 4 5 6 7 8 9 10
4 5 6 7 8 9
10
Add lines 2 and 3 NY Liberty Zone business employee credit included on line 4 from passive activities (see instructions) Subtract line 5 from line 4 NY Liberty Zone business employee passive activity credit allowed for 2002 (see instructions) Carryforward of NY Liberty Zone business employee credit to 2002 Carryback of NY Liberty Zone business employee credit from 2003 (see instructions) Current year credit. Add lines 6 through 9. (S corporations, partnerships, estates, trusts, cooperatives, regulated investment companies, and real estate investment trusts, see instructions.)
Part II
11
● ● ●
Allowable Credit
12
● ● ●
13 14a b c d e f g h i j k l m 15 16 17 18 19 20 21
Regular tax before credits: Individuals. Enter the amount from Form 1040, line 42 15 Estates and trusts. Enter the amount from Form 1041, Schedule I, line 56 Add lines 11 and 12 14a Foreign tax credit 14b Credit for child and dependent care expenses (Form 2441, line 11) 14c Credit for the elderly or the disabled (Schedule R (Form 1040), line 24) 14d Education credits (Form 8863, line 18) 14e Credit for qualified retirement savings contributions (Form 8880, line 14) 14f Child tax credit (Form 1040, line 50) 14g Mortgage interest credit (Form 8396, line 11) 14h Adoption credit (Form 8839, line 18) 14i District of Columbia first-time homebuyer credit (Form 8859, line 11) 14j Possessions tax credit (Form 5735, line 17 or 27) 14k Credit for fuel from a nonconventional source 14l Qualified electric vehicle credit (Form 8834, line 20) Add lines 14a through 14l Net income tax. Subtract line 14m from line 13. If zero, skip lines 16 through 19 and enter -0- on line 20 16 Net regular tax. Subtract line 14m from line 11. If zero or less, enter -0Enter 25% (.25) of the excess, if any, of line 16 over $25,000 (see instructions) Subtract line 17 from line 15. If zero or less, enter -0General business credit (see instructions) Subtract line 19 from line 18. If zero or less, enter -0Credit allowed for the current year. Enter the smaller of line 10 or line 20 here and on Form 1040, line 53; Form 1120, Schedule J, line 6d; Form 1120-A, Part I, line 2a; Form 1041, Schedule G, line 2c; or the applicable line of your return. If line 20 is smaller than line 10, see instructions
Cat. No. 33946Z
11
12 13
14m 15 17 18 19 20
21
Form
For Paperwork Reduction Act Notice, see page 4.
8884
(2002)
Form 8884 (2002)
Page
2
General Instructions
Section references are to the Internal Revenue Code unless otherwise noted.
Purpose of Form
A New York Liberty Zone business uses Form 8884 to claim the New York Liberty Zone business employee credit. The credit is 40% (25% for employees who worked for you fewer than 400 hours) of the qualified wages (up to $6,000) paid or incurred during the tax year, for work performed after December 31, 2001, to each New York Liberty Zone business employee. You may claim or elect not to claim the credit any time within 3 years from the due date of your tax return (excluding extensions) on either your original or an amended return. The New York Liberty Zone business employee credit is treated as a part of the work opportunity credit, and New York Liberty Zone business employees are considered members of a targeted group under the work opportunity credit. However, unlike the other targeted groups, New York Liberty Zone business employees do not require certification for their wages to qualify for the credit. Also, because of the special tax liability limit that applies to the credit for these employees, use only Form 8884 to figure the credit. Do not use Form 3800, General Business Credit, or Form 5884, Work Opportunity Credit, for this credit. For more details, see Notice 2002-42. You can find Notice 2002-42 on page 36 of Internal Revenue Bulletin 2002-27 at.
New York Liberty Zone Business Employee A New York Liberty Zone business employee is, for any period, any employee of a New York Liberty Zone business if 80% or more of the services of the employee during the period are performed for the business: 1. In the New York Liberty Zone or 2. In the city of New York, New York, outside the New York Liberty Zone, for a New York Liberty Zone business located outside the New York Liberty Zone as a result of the physical destruction or damage of its place of business by the September 11, 2001, terrorist attack.
Limit on Number of Employees Located Outside the New York Liberty Zone
Definitions
New York Liberty Zone Business A New York Liberty Zone business is any business that is located: ● In the New York Liberty Zone (see below) or ● In the city of New York, New York, outside the New York Liberty Zone, as a result of the physical destruction or damage of its place of business by the September 11, 2001, terrorist attack. Exception. A business is not considered a New York Liberty Zone business for any tax year for which it employed an average of more than 200 employees on business days during the tax year. A business day is any day on which your business is open to the public or you regularly conduct business. You can use any reasonable method of calculating the average number of employees on business days during the tax year. For example, you may count employees on each business day and average the numbers, or count employees on the last day of each pay period and average those numbers. If you use different pay periods for different groups of employees, you may calculate the average number of employees in the groups separately, and then add the averages. You may count each part-time employee as one employee, or as a fraction of an employee, using any reasonable method of determining full-time equivalents. New York Liberty Zone The New York Liberty Zone is the area located on or south of Canal Street, East Broadway (east of its intersection with Canal Street), or Grand Street (east of its intersection with East Broadway) in the borough of Manhattan in the city of New York, New York.
The number of employees described in 2 above that are treated as New York Liberty Zone business employees on any day is limited to the excess of: ● The number of employees of the business on September 11, 2001, in the New York Liberty Zone over ● The number of New York Liberty Zone business employees (determined without regard to employees described in 2 above) of the business on the day to which the limit is being applied. Example 1. Elm is a cash-basis, calendar-year New York Liberty Zone business that had two places of business and 60 employees in the New York Liberty Zone on September 11, 2001. One place of business remained in the New York Liberty Zone. Due to damage incurred on September 11, 2001, Elm relocated the other place of business to Brooklyn. On each business day during 2002, 40 employees performed services at the place of business in New York City inside the New York Liberty Zone, and 30 employees performed services at the place of business in New York City outside the New York Liberty Zone. Elm did not exceed the 200-employee limit. Elm can claim the credit on the basis of the qualified wages it paid during its tax year to 60 employees (the 40 employees inside the New York Liberty Zone and 20 of the 30 employees in Brooklyn). Example 2. The facts are the same as in Example 1, except that on each business day, 70 employees performed services at the place of business inside the New York Liberty Zone, and 20 employees performed services at the Brooklyn place of business in New York City outside the New York Liberty Zone. Elm can claim the credit on the basis of the qualified wages it paid to all 70 employees inside the New York Liberty Zone. Elm cannot claim the credit on the basis of the qualified wages it paid to any of the employees outside the New York Liberty Zone. Members of a controlled group, see sections 52 and 1400L(a)(2)(D)(ii).
Qualified Wages Qualified wages are wages paid or incurred by the employer during the tax year to New York Liberty Zone business employees for work performed in calendar year 2002 or 2003. The amount of qualified wages that may be taken into account for any employee is limited to $6,000 per calendar year. Wages qualifying for the credit generally have the same meaning as wages subject to the Federal Unemployment Tax Act (FUTA) (for a special rule that applies to railroad employees, see section 51(h)(1)(B)). Qualified wages for any employee must be reduced by the amount of any work supplementation payments you received under the Social Security Act.
Form 8884 (2002)
Page
3
The amount of qualified wages for any employee is zero if: ● The employee worked for you fewer than 120 hours, ● The employee is your dependent, ● The employee is related to you (see section 51(i)(1)), ● 50% or less of the wages the employee received from you were for working in your trade or business, or ● You use any of the employee’s wages to figure the welfare-to-work credit. Qualified wages do not include: ● Wages paid to any employee during any period for which you received payment for the employee from a federally funded on-the-job training program, ● Wages used to figure the credit on Form 5884, and ● Wages for services of replacement workers during a strike or lockout. Example. XYZ Company, a cash-basis New York Liberty Zone business, pays all its employees on the last day of each month for work performed during that month. XYZ had 90 employees from January 1, 2002, through June 30, 2002, the end of its 2001 fiscal year. During that time, 89 of those employees were paid more than $6,000. The other employee, Kathy Birch, was paid $5,000. For XYZ’s 2002 fiscal year beginning July 1, 2002, and ending June 30, 2003, XYZ paid wages as follows: ● After June 30, 2002, and before January 1, 2003, more than $1,000 to Kathy Birch and more than $6,000 to 10 employees hired after June 30, 2002; ● After December 31, 2002, and before July 1, 2003, more than $6,000 to the 90 original employees and 9 of the 10 new employees, and $2,000 to the other new employee, Frank Ash. The amount of XYZ’s qualified wages for its fiscal year beginning on July 1, 2002, and ending on June 30, 2003, is $657,000 ($1,000 for Kathy Birch and $60,000 for the 10 new employees in calendar year 2002, and $6,000 x 99, plus $2,000 for Frank Ash, for 2003). For its fiscal year beginning July 1, 2003, the first $4,000 of wages paid to Frank Ash for 2003 will be qualified wages. No amounts paid to the other employees for 2003 will be qualified wages. Controlled group members. The group member proportionately contributing the most qualified wages figures the group credit in Part I and skips Part II. See sections 52(a) and 1563. On separate Forms 8884, that member and every other member of the group should skip lines 1a and 1b and enter its share of the group credit on line 2. Each member then completes the rest of its separate form. Each member must attach to its Form 8884 a schedule showing how the group credit was allocated among the members. The members share the credit in the same proportion that they contributed qualified wages.
year 2002 or 2003. Multiply the wages you enter by the percentage shown.
Line 2 In general, you must reduce your deduction for salaries and wages by the amount on line 2. This is required even if you cannot take the full credit this year and must carry part of it back or forward. However, the following exceptions to this rule apply. ● You capitalized any salaries and wages on which you figured the credit. In this case, reduce your depreciable basis by the amount of the credit on those salaries and wages. ● You used the full absorption method of inventory costing, which required you to reduce your basis in inventory for the credit. If either of the above exceptions applies, attach a statement explaining why the amount on line 2 differs from the amount by which you reduced your deduction.). Line 7 Enter the passive activity credit allowed for the 2002 New York Liberty Zone business employee credit from Form 8582-CR or Form 8810. Line 9 Use only if you amend your 2002 return to carry back an unused New York Liberty Zone business employee credit from 2003. Line 10 If line 10 is zero, skip Part II. S corporations and partnerships. Allocate the credit among the shareholders or partners. Attach Form 8884 to the return and on Schedule K-1 show the credit for each shareholder or partner. Electing large partnerships include this credit in “general credits.” Estates and trusts. The credit is allocated between the estate or trust and the beneficiaries in proportion to the income allocable to each. Next to line 10, the estate or trust should enter its part of the total credit. Label it “1041 Portion” and use this amount in Part II to figure the allowable). Line 17 See section 38(c)(4) for special rules that apply to married couples filing separate returns, controlled corporate groups, regulated investment companies, real estate investment trusts, and estates and trusts.
Specific Instructions
Note: If you only have a credit allocated to you from a pass-through entity, skip lines 1 and 2 and go to line 3.
Lines 1a and 1b For employees who have worked for you at least 120 hours but fewer than 400 hours, the credit rate is 25%. For employees who have worked for you at least 400 hours, the credit rate is 40%. Enter on the applicable line the total qualified wages paid (or incurred) to employees during the tax year for work performed during calendar
Form 8884 (2002)
Page
4
Line 19 Enter the amount of all other allowed credits for the current year included in the general business credit. If you are filing a single separate general business credit form, enter the amount from the last line of that form. If you are filing Form 3800, enter the amount from line 19 of that form (plus any amount from Form 8844, line 24). If you are filing Form 8844 and another general business credit form (other than Form 3800), enter the sum of Form 8844, line 24, plus the last line of the other general business credit form. Line 21 If you cannot use part of the credit because of the tax liability limit (line 20 is smaller than line 10), carry the unused part back 1 year then forward up to 20 years. To carry back an unused credit, file an amended income tax return (Form 1040X, Form 1120X, or other amended return) for the prior tax year or an application for tentative refund (Form 1045, Application for Tentative Refund, or Form 1139, Corporation Application for Tentative Refund), and attach an amended Form 8884. If you file an application for tentative refund, it generally must be filed within 12 months after the end of the tax year in which the credit arose.: 9 hr., 48 min. Recordkeeping 1 hr. Learning about the law or the form Preparing and sending 1 hr., 12 min. the form to the IRS. | https://www.scribd.com/document/543101/US-Internal-Revenue-Service-f8884-2002 | CC-MAIN-2016-40 | refinedweb | 2,858 | 54.26 |
Getting Started
When you create your own blog, you may wonder about the comment function. Do you want to create it yourself or use an external service?
I've used
Firebase
firestore and
Firebase Authentication to create a comment system for anonymous users.
However, if you have a technical blog in mind, wouldn't you like to have the following features?
- User authentication
- Write in markdown format
- Embed links.
- Links should be
noreferrer
- Images can be embedded
- XSS protection
- Can be previewed
- Comment notification
- Notify the blogger
- Notifications to commenters
Also, I think most blogs these days are made with static site generators, so I would like to use the above features in a serverless way.
Personally, I've been obsessed with blog features and have experienced frustration, so I want to make the unrelated parts easy.
In such cases, I recommend
utterances.
What are utterances?
utterances is not a blogging system.
The official description is as follows.
A lightweight comments widget built on GitHub issues. Use GitHub issues for blog comments, wiki pages and more!
utterances provides a lightweight comments component and a bot for commenting on GitHub issues. With utterances, you can connect GitHub issues to articles and pages, and display the issues.
In other words, it is almost the same as embedding a GitHub issues into a blog.
The authentication uses
GitHubOAuth, and can be written in markdown format or any other way you like.
There are also several color themes that support dark mode, and you can even specify issue labels.
It's also free and has no ads.
Features of utterances
Let's see if it meets the requirements for a technical blog commenting system.
User authentication
For user authentication, we will use the
GitHubOAuth flow. If it's a technical blog, the target audience is technical people, so
This is probably the most ideal authentication provider.
For security concerns, anonymous users cannot comment, though.
Can you write in markdown format?
You can write comments as you would write an issue on GitHub. You can write comments as if you were writing an issue on GitHub, as you can see from this blog. It also looks the same. The only difference is that there is no shortcut widget for markdown notation. You can also preview it, so no complaints there.
Comment Notifications
As I mentioned earlier, commenting is the same as commenting on a GitHub issue. So the blogger will get a notification from GitHub. Commenters will also be notified of other comments as well.
The above is all the functionality you need, but there are a few other things worth mentioning.
Reactions to comments
As with GitHub issues, you can react to comments. You can add 🚀 or ❤️ ,etc to the comment. It also works reactively, just like the original.
There are similar projects such as
Gitment and
Gitalk, but the closest in appearance and functionality to GitHub issues is
utterances.
Options for tying to various GitHub issues
There are six ways to tie an article to GitHub issues. You can choose from the following methods for the title of the issue:
- Partial match with the
pathnameof the page
- Partial matching with the
URLof the page
- Partial match with the
titleof the page
- Partial match with the
og:titleof the page
- Contains a specific term
This means that if the tied issue is not found, the comment will not be displayed in any way. When a comment is posted, the comment will be added to the associated issue, if one exists. If not, an issue will be created automatically.
It is also possible to specify an issue number to tie.
This variety of association options allows for flexible support of blogs with complex path structures.
For example, in the case of an internationalized blog like this one, there are articles with the same content in different languages and with different
pathname.
In this case, you can choose whether to unify the comments for the articles or separate them.
In the case of above URL, this blog wanted to have separate comments for the Japanese and English articles, so I chose to tie them by
pathname.
The title of GitHub issues generates
posts/comment-system/ and
en/posts/comment-system/.
Since it is the longest match, you can distinguish them without any problem even if the article is in English.
On the other hand, if you want to unify the comments, you can specify the slug as a specific term that matches in both articles.
Install utterances
Installation is very easy. There are two things to do. The first is to install the utterances-bot in your GitHub App.
This bot will write comments on real GitHub issues.
The other is to load the
utterances script.
Just place the script tag generated according to the official documentation in your HTML and you are done. The script tag looks like this
<scriptsrc=""repo="TomokiMiyauci/me"issue-term="pathname"theme="github-light"crossorigin="anonymous"async></script>
Introduction to the UI component library
React,
Vue or
Svelte, etc working with script tags in these requires a bit of tricky stuff.
In order to handle script tags in
React,
Vue,
Svelte, etc, you need to be a little hack.
So I made a
utterances-component. It currently supports
React/Preact,
Vue3, and
Svelte.
What it does is not much, but it can be handled as a component, so it should be easy to implement
utterances.
import { Utterances } from 'utterances-react-component';<
Since this project was built with
monorepo.
If there are other UI component libraries that you would like to see supported, please submit a feature request.
Limitations of utterances
I have only introduced the good points, but there are some limitations.
Can't get the comment count
If you have a blog, you would like to display the number of comments in a different place as well. Unfortunately, it is not possible to get the number of comments.
The
utterances script actually embeds an
iframe.
Therefore, due to CORS, you can't even access the DOM.
So you can't even extract the number of comments from the string
xxx Comments - powered by utteranc.es.
If you self-host the script, you can use the postMessage API for messaging since it is an iframe.
See Comments counts #36 for details.
Note that this blog uses GitHub APi v4 separately to get only the comment count of an issue.
Rate Limits
utterances makes a request to GitHub issues to get comments.
High frequency requests will be trapped by GitHub's rate limit.
For example, if a comment is fetched too many times due to frequent reloads, the comment becomes unusable.
If you don't mind the above points, I recommend you to try it.
Edit this page on GitHub | https://miyauchi.dev/posts/comment-system/ | CC-MAIN-2021-43 | refinedweb | 1,129 | 65.32 |
Although a comparatively minor release, C# 7.3 addresses several long outstanding complaints from C# 1 and 2.
Overload Resolution
Since version 1.0, C#'s overload resolution rules had a rather questionable design. Under some circumstances it would pick two or more methods as candidates, though all but one couldn't be used. Depending on the priority of the incorrectly selected method, the compiler would then either indicate no method matched or the matches were ambiguous.
C# 7.3 moves some of the checks to happen during overload resolution, rather than after, so the false matches don't cause compiler errors. The Improved overload candidates proposal outlines these checks:
1..
2. When a method group contains some generic methods whose type arguments do not satisfy their constraints, these members are removed from the candidate set.
3. For a method group conversion, candidate methods whose return type doesn't match up with the delegate's return type are removed from the set.
Generic Constraints: enum, delegate, and unmanaged
Developers have been complaining about the inability to indicate a generic type must be an enum since generics were introduced in C# 2.0. This has finally been addressed, and you can now use the
enum keyword as a generic constraint. Likewise, you can now use the keyword
delegate as a generic constraint.
These don't necessarily work the way you might expect. If the constraint is
where T : enum then someone can use
Foo<System.Enum> when what you probably meant is for them to use a subclass of
System.Enum. Nonetheless, this should cover most scenarios for enums and delegates.
The Unmanaged type constraint proposal uses the "unmanaged" keyword to indicate the generic type must be a "type which is not a reference type and doesn't contain reference type fields at any level of nesting." This is intended to be used with low level interop code where you need to "create re-usable routines across all unmanaged types". Unmanaged types include:
- The primitives sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, IntPtr, or UIntPtr.
- Any enum type.
- Pointer types.
- User defined structs only containing the above.
Attributes on Hidden Fields
While auto-implemented properties are very useful, they do have some limitations. You cannot apply attributes to the backing field, because you can't see it. While not usually an issue, this can be problematic when dealing with serialization.
The Auto-Implemented Property Field-Targeted Attributes proposal addresses this in a straight-forward fashion. When applying an attribute to an auto-implemented property, simply prepend the
field: modifier.
[Serializable] public class Foo { [field: NonSerialized] public string MySecret { get; set; } }
Tuple Comparisons (== and !=)
While the name of the proposal, Support for == and != on tuple types, summarizes this feature nicely there are some details and edge cases to be aware of. The most important is a potentially breaking change:
If someone wrote their own ValueTuple types with an implementation of the comparison operator, it would have previously been picked up by overload resolution. But since the new tuple case comes before overload resolution, we would handle this case with tuple comparison instead of relying on the user-defined comparison.
Ideally this custom ValueTuple type would follow the same rules as the C# 7.3 compiler, but there may be subtle differences in how it handles nested tuples and dynamic types.
Expression variables in initializers
In a way this reads like an anti-feature. Rather than adding capabilities, Microsoft removed restrictions on where expression variables can be used.
We remove the restriction preventing the declaration of expression variables (out variable declarations and declaration patterns) in a ctor-initializer. Such a declared variable is in scope throughout the body of the constructor.
We remove the restriction preventing the declaration of expression variables (out variable declarations and declaration patterns) in a field or property initializer. Such a declared variable is in scope throughout the initializing expression.
We remove the restriction preventing the declaration of expression variables (out variable declarations and declaration patterns) in a query expression clause that is translated into the body of a lambda. Such a declared variable is in scope throughout that expression of the query clause.
The original reasoning for these restrictions were simply noted as "due to lack of time". Presumably the restrictions reduced the amount of testing that needed to be done for previous versions of C# 7.
Stack Allocated Arrays
A rarely used, but important feature of C# is the ability to allocate an array inside the stack via the
stackalloc keyword. This may offer performance improvements over normal arrays, which are allocated on the heap and cause GC pressure.
int* block = stackalloc int[3] { 1, 2, 3 };
There is some danger in using a stack allocated array. Since it requires taking a pointer against the stack, it can only be used in an unsafe context. The CLR attempts to mitigate this by enabling buffer overrun detection, which will cause the application to "terminate as quickly as possible".
With C# 7.3, you gain the ability to initialize the array when it is created just like you would with normal arrays. The proposal lacks details, but Microsoft was considering pre-initializing a master array which then could be rapidly copied when the function is invoked. In theory this would be faster than creating an array and then initializing it element by element.
Note stack allocated arrays are meant for scenarios where you need lots of small, briefly used arrays. They shouldn't be used for large arrays or deeply recursive functions, as you may exceed the amount of available stack space.
Stack Allocated Spans
A safe alternative to a stack allocated array is a stack allocated span. By eliminating the pointer, you also eliminate the possibility of a buffer overrun. Which in turn means you can use this without having to mark the method as unsafe.
Span<int> block = stackalloc int[3] { 1, 2, 3 };
Note
Span<T> requires the
System.Memory NuGet package.
Re-assignable Ref Locals
Ref local variables can now be reassigned just like normal local variables.
For other C# 7.3 proposals see the csharplang GitHub site.
Community comments | https://www.infoq.com/news/2018/05/CSharp-7.3?utm_source=infoq&utm_medium=popular_widget&utm_campaign=popular_content_list&utm_content=podcast | CC-MAIN-2019-04 | refinedweb | 1,031 | 55.44 |
Hi. I have an abstract base class and one concrete derivative in C++ and I have wrapped the base class with Boost.Python. Now I want to define another derived class, but I want to do this in Python. With the Boost.Python wrapper, this is easy. But now comes the hard part: I want to create an instance of this Python class and use it in C++. The first thing I did was searching the latest posts on this mailing list which gave me 2 clues: - the example at the bottom of: - PyRun_String Here's what I came up with: #include <iostream> // The abstract base class class Base { public: virtual ~Base() {}; virtual void f() = 0; }; // The C++ derived class class CppDerived : public Base { public: virtual ~CppDerived() {} void f() { std::cout << "CppDerived::f()\n"; } }; //-------------------------------------------------------// #include <boost/python.hpp> #include <boost/python/extract.hpp> namespace python = boost::python; namespace { // Boost.Python wrapper for Base struct BaseWrap : public Base { BaseWrap(PyObject* self_) : self(self_) {} void f() { return python::call_method<void>(self, "f"); } PyObject* self; }; } BOOST_PYTHON_MODULE(pythontest) { python::class_<Base, BaseWrap, boost::noncopyable>("Base", python::no_init) ; } //-------------------------------------------------------// int main() { // Register the wrapper module PyImport_AppendInittab("pythontest", initpythontest); // Initialize the interpreter Py_Initialize(); // Create and use an instance of the C++ derived class boost::shared_ptr<Base> cpp(new CppDerived); cpp->f(); // Define the Python derived class PyRun_SimpleString( "from pythontest import *\n" "class PythonDerived(Base):\n" " def __init__(self):\n" " pass\n" " def f(self):\n" " print \"PythonDerived::f()\"\n" ); // Create and use an instance of the Python derived class Base& py = python::extract<Base&>( PyRun_String("PythonDerived()\n", ???, ???, ???); py.f(); std::cout << "\nPress <enter> to quit..."; std::cin.get(); // Release the Python interpreter Py_Finalize(); } I feel like I'm almost there, but I just can't get this to work. Firstly, I don't know which arguments to feed into PyRun_String. The python.org docs didn't really help me that much: I don't have any dictionaries of globals and locals, and what exactly is a start token? I tried 0s for all 3 arguments and then compiling, but that brought me to the second issue: The 'Base& py = ...' line gave a compilation error saying that a python::extract<Base > could not be converted to a Base&. Then I tried replacing both Base& with Base*, which compiled but gave an access violation. Can anyone help me out? Thanks in advance, Dirk Gerrits | https://mail.python.org/pipermail/cplusplus-sig/2002-November/002267.html | CC-MAIN-2016-30 | refinedweb | 395 | 60.75 |
iSkeletonAnimNode2 Struct Reference
[Mesh plugins]
Base type for nodes in the hierarchical blending tree for skeletal animation system. More...
#include <imesh/skeleton2anim.h>
Detailed Description
Base type for nodes in the hierarchical blending tree for skeletal animation system.
Definition at line 339 of file skeleton2anim.h.
Member Function Documentation
Add a new animation callback to a node.
- Parameters:
-
Blend the state of this node into the global state.
- Parameters:
-
Find a sub-node with given name.
Get the length of the node.
Get the node factory.
Get the current playback position (time).
Get the playback speed.
Is this or any sub-node active and needs any blending.
Start playing the node.
Exactly what this results in depends on the specific node type.
Remove a animation callback from a node.
- Parameters:
-
Set the current playback position.
If set beyond the end of the animation it will be capped.
Set the playback speed.
Stop playing the node (deactivate it).
Update the animation state.
- Parameters:
-
The documentation for this struct was generated from the following file:
- imesh/skeleton2anim.h
Generated for Crystal Space 1.4.1 by doxygen 1.7.1 | http://www.crystalspace3d.org/docs/online/api-1.4.1/structiSkeletonAnimNode2.html | CC-MAIN-2014-15 | refinedweb | 188 | 54.9 |
This document was inspired by this thread.
Problem: UCCX needs to send a recording using the Hypertext Transfer Protocol (HTTP), which is not always suitable for binary data (like a recording).
Analysis: The Base64 encoding algorithm is an excellent method of transforming binary objects into ASCII characters that may be safely transmitted over a text-based protocol like HTTP.
Disclaimer: * * * The usual blah-blah. I am not responsible for anything. UCCX Premium or IP IVR license only (custom Java used). Tested with UCCX Premium 7.0(1)_Build168. * * *
Solution:
1. Download the Apache Commons Codec library. N.B.: there are separate versions of Commons Codec for different Java versions, so this might be the right time to look up the Java version of your UCCX server. Use the compatibility matrix - or, alternatively, use Recipe #2 from this document. In this example, I use UCCX 7.0, this means Java 5 is I need to work with, so I downloaded Commons Codec 1.6).
2. Unzip/Untar-gz the package, and upload the commons-codec-1.x.jar file to UCCX's classpath, and select it on the "Custom File Configuration" page.
3. Reload the server. Or reboot it. Yes, it's really necessary. No, it won't work without this.
4. Create a new script, using the UCCX Script editor.
5. Insert the following variables:
base64encodedRecording - type String - inital value: ""
recording - type Document - initial value: DOC[]
serverResponse - type Document - initial value: DOC[]
url - type String - the URL of the target application, we will send the Base64 encoded recording to here.
6. Insert all the necessary steps to the script (for instance, Accept, Play Prompt, etc).
7. Insert a Recording step. The result document would be the recording variable.
8. Add a Set node to the Successful branch of the Recording step. The result would be the variable named base64encodedRecording. Insert the following code block:
{
java.io.InputStream is = new org.apache.commons.codec.binary.Base64InputStream(recording.getInputStream(),true);
byte[] b = new byte[1024]; // change it to a higher value if it's too slow
StringBuffer buf = new StringBuffer();
int bytesRead = 0;
while ((bytesRead = is.read(b,0,b.length)) != -1) {buf.append(new String(b,0,bytesRead)); }
return buf.toString();
}
As we can see, I got the InputStream object of the recording document, and wrapped it into another InputStream, more precisely, with a Base64InputStream (by specifying true - see the second parameter) I asked it to encode everything I read from the source InputStream, using the Base64 algorithm. Then I just read chunks of bytes out of it - 1024 bytes long chunks - and appending them into a StringBuffer, which then I hand over at the last line, transformed into a String.
9. The next two steps are easy: with a Create URL Document step, with the URL pointing to the HTTP application which, the HTTP method would be POST, and the parameter, in this example named "base64encodedRecording" holds the value of the variable named base64encodedRecording (the last setting, the Document is not used in this example, I used a dummy variable named ServerResponse). Then, using the Cache Document step, the script actually issues the HTTP request.
Testing:
I created a simple Grails application "Base64Recording", with one controller "TakeAndSaveController" with one method, "index" (this is why, in my script the value of the url variable is "":
package base64encodecprompt
class TakeAndSaveController {
def index() {
def encoded = params.base64encodedRecording.replaceAll("\r|\n", "").trim()
def decoded = encoded.decodeBase64()
new File("/tmp/recording.wav").withOutputStream {
it.write(decoded)
}
}
}
Here's a screenshot:
What happens here: I take the parameter named "base64encodedRecording" (out of the params object), while replacing all the newline characters (\n, \r) and trimming the leading and trailing whitespaces (just to be on the safe side) - this yields the encoded variable.
Then, I decode the binary object, by calling the decodeBase64() method on encoded - resulting decoded.
Finally, I create a file named /tmp/recording.wav, and with its OutputStream I just write the binary object into it.
I created an application, then a trigger, called in, after the prompt I created a recording, and in a couple of moments, a file named /tmp/recording.wav appeared on my computer, created by the Grails application.
There are several things to be aware of:
- While encoding the binary stream into Base64 text, line separators (by default, CRLF) are added, after the 76th character. There's nothing wrong with it, but the receiving application may need to remove these extra characters (this is what I did by calling the replaceAll method in my Grails controller).
- Base64 will introduce overhead, making the encoded string longer by 33% of the original string. This may be taken into account when sending large recordings.
Screenshot of the whole UCCX script, for inspiration:
Enjoy.
G.
I am trying to implement this encoding.
I am using uccx 9.0.2 and downloaded Commons Codec 1.9. I installed it like is documented here and created a test script and am unable to create an application with this new script. The error I get is
%MIVR-APP_MGR-1-SCRIPT_LOAD_ERROR:Failed to load script: Script=SCRIPT[SOAP_Connector-5.aef],Exception=com.cisco.script.ScriptIOException: Failed to load script: SOAP_Connector-5.aef; nested exception is:
Here is the text of the set statement
{
java.io.InputStream is = new org.apache.commons.codec.binary.Base64InputStream(dRecorded_Msg.getInputStream(),true);
byte[] b = new byte[2048]; // change it to a higher value if it's too slow
StringBuffer buf = new StringBuffer();
int bytesRead = 0;
while ((bytesRead = is.read(b,0,b.length)) != -1) {buf.append(new String(b,0,bytesRead)); }
return buf.toString();
}
I looked at the Base64InputStream documentation and it looks right.
Does anyone have a suggestion how to fix the incompatible argument to function error?
Hi,
apologies for not responding earlier, I've been a bit busy lately.
I tested Commons Codec 1.9 with UCCX 8.0 (I don't have a 9.x version in my lab). Used a similar script, successfully. The only thing that comes to my mind is that the d_Recorded_Msg variable must be incompatible at runtime.
Can you please reveal more about your script? Would you mind attaching the script or at least a screenshot of the relevant part of it?
Thanks.
G.
Sure here is a screenshot of what I have so far.
Er... I am afraid it was lost in transit. Can you post it again?
I changed the name of the recording to recorded.
Trying different browsers to see if the screenshot will post
Hi, this might sound weird but can you double check your variables? The Recording step assigns the recording to the variable named "Recorded" but in your Set step with the Java code you sort of reference a variable named "recorded". Variable names are case sensitive.
G.
Yes I caught the Recorded after I did the snapshot. I also stripped everything out. I still get the same error.
OK, can you add a Set step right before the existing one, like this:
recorded = (Document) N[1]
And then just try stepping over the script. Does it still throw the same error?
I cannot create an application with the script. When I go into application management and attempt to use the new test script I get the error so I cannot debug anything.
Did you reload the UCCX engine after uploading that jar file you downloaded?
Also, if you try validating your script in UCCX Script Editor, does it pass?
G.
I simplified the java to narrow down where the script loading error is. When I use this script I am able to go to application > soaptest > script > SOAP_Connector-7.aef. and update the application with no errors.
When I add one line to the script envoke the org.apache.commons.codec.binary.Base64InputStream function I then get a MADM error when trying to associate the changed script to the existing application. I have tried commons-codec-1.9.jar, commons-codec-1.8.jar and commons-codec-1.7.jar one at a time but get the same result. Not sure what else to try.
9665: Sep 07 16:31:21.701 EDT %MADM-SCRIPT_MGR-3-UNABLE_LOAD_SCRIPT:Unable to load script: Script=/SOAP_Connector-6.aef,Exception
After loading the commons-codec-1.X.jar file I reboot the UCCX 9.0.2 server. Both scripts validate in the script editor with no issues. | https://community.cisco.com/t5/collaboration-voice-and-video/uccx-send-a-recording-or-any-document-over-http-safely-using/ta-p/3146642 | CC-MAIN-2019-39 | refinedweb | 1,396 | 58.48 |
As most of you are aware, Adobe has released Reader 9.1. What you might not be aware of is that there are some XFA enhancements bundled into this release. This version of Reader now supports XFA 3.0 templates. Here’s my take on a set of "frequently asked questions":
Q. XFA 3.0? Is this a major release?
A. In spite of the fact that XFA 3.0 now has a new major version number, it is not a major revision. We had to choose between incrementing XFA 2.9 to either XFA 2.10 or XFA 3.0. We chose 3.0 primarily because we were worried about code (ours and partners) that converts the XFA version number to a floating point number for comparison purposes. Any code that treats the version as a floating point number would not compare "2.10" properly against "2.9".
Q. What happened to XFA 2.9?
A. We reserved XFA 2.9 for a server-side customer-specific dot release. To the best of my knowledge, we did not end up modifying the specification for XFA 2.9.
Q. When will the XFA 3.0 spec be released to the public?
A. Currently scheduled for release on March 23
Q. When will we have a version of Designer that targets XFA 3.0 and Acrobat/Reader 9.1?
A. I can’t pass along a specific date. There will be a new version of Designer with the next major releases of LiveCycle ES.
Q. What version of PDF will contain XFA 3.0?
A. Acrobat/Reader 9.0/XFA 2.8 were hosted by PDF 1.7 with Adobe Extensions Level 3. Acrobat/Reader 9.1/XFA 3.0 is hosted by PDF 1.7 with Adobe Extensions Level 5.
Q. Does this mean that the XFA template namespace will change again?
A. Yes. The new namespace is: We are looking at an enhancement where we will store the XFA version number separately from the namespace. If you have code in your applications that assumes it can find the version number in the namespace, you might want to think about making the code generic enough so that it could eventually retrieve the version number from somewhere else — perhaps an attribute on the <template> element.
Q. What’s new in XFA 3.0?
A. There are a relatively small number of enhancements, but they are improvements targeting ease of authoring. I plan to blog the specifics in the coming weeks. | http://blogs.adobe.com/formfeed/2009/03/reader_91_and_xfa_30.html | CC-MAIN-2019-22 | refinedweb | 419 | 77.53 |
This is the first in a series of posts on how you can program the product catalog system. The product catalog system that shipped in Commerce Server 2002 provided three programming models:
1. The Catalog Com objects : These are a set of objects which allow you to perform management and runtime operations on the catalog system. These were implemented using COM and they communicate directly with the SQL server. Methods on this object were intended to be called from VB scripts, ASP, ASP.Net, C++ etc (COM aware) clients.
2. The Catalog PIA : These are a set of objects in the Microsoft.CommerceServe.Interop.Catalog namespace which wrap the Catalog com objects and can be used to program the product catalog system from managed clients. To know more about PIA’s see this link. Methods on these objects were intended to be called from managed clients.
3. The Runtime BCL: These are a set of objects which were provided to program the catalog system from your web sites. These types reside in the Microsoft.CommerceServer.Runtime.Catalog namespace and provides methods to access the run time functionality (readonly operations) of the catalog system. Internally though these objects call methods on the PIA but expose a consistent, flexible and easy to use programming model from your runtime commerce server sites.
4. Web services model : The Commerce Server 2002 feature pack further extended the programming model by allowing the product catalog system to be managed by a catalog web service.
As had been a consistent request and user feedback, I will be adding sample code in future posts for each of the above models. | https://blogs.msdn.microsoft.com/vinayakt/2005/09/27/programming-the-commerce-server-product-catalog-system/ | CC-MAIN-2016-44 | refinedweb | 272 | 54.73 |
How to control unipolar/bipolar stepper/stepping motors such as 28BYJ48 using motor drivers such as L293D
Ask QuestionAsked 1 year, 11 months agoActive 5 months agoViewed 805 times31
So I’m having issues with controlling the motor with this ic.
I have got it to work when it was unipolar with the uln2003.
I slit the red wire so there are only 4,two windings. Measured ohms across coils.
Pin 1 ic – 5v pos
Pin2 ic – gpio 27
Pin3 ic – yellow motor wire
Pin 4 ic – ground
Pin 5 ic – ground
Pin 6 ic – Blue motor wire
Pin 7 ic – gpio 22
Pin 8 ic – 5v pos
Pin 9 ic – 3v3 pi
Pin 10 ic – gpio 9
Pin 11 ic – pink motor wire
Pin 12 ic – ground
Pin 13 ic – ground
Pin 14 ic – orange motor wire
Pin 15 ic – gpio 10
Pin 16 ic – 5v pos
When I run:
import RPi. GPIO as GPIO import time GPIO. setmode(GPIO. BCM) ControlPins = [27,22,10,9] for pin in ControlPins: GPIO. setup(pin, GPIO. OUT) GPIO. output(pin, 0) seq = [[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,1,1,0],[0,0,1,0],[0,0,1,1],[0,0,0,1],[1,0,0,1]] def rotate90(direction): if direction == 'CW': for i in range (128): for halfstep in range(4): GPIO. ouput(ControlPins[pin], seq[halfstep] [pin]) rotate90('CW') GPIO.cleanup()
The data sheets do not have a truth table(seq) as far as I can see. They also say to use diodes and caps(I’m assuming that’s for efficiency).
The 28byj is making sounds, but isn’t rotating. I think this is because of my truth table. What should it be?
Sorry for the messy question. I’m on my phone.dc-motorShareEditFollowCloseFlagedited 4 mins agotlfong013,62133 gold badges77 silver badges2222 bronze badgesasked Apr 27 ’19 at 3:52Alex White16155 bronze badges
- Yes, you connection data is messy. I can only count to 7, but you have 16! Can you draw me a picture? – tlfong01 Apr 27 ’19 at 4:26
- Of course she is making sounds – she is complaining that you have made all the connections. You suspect your truth table, but can you show me your truth table? – tlfong01 Apr 27 ’19 at 4:32
- Will draw one up now. – Alex White Apr 27 ’19 at 4:37
- No hurry, I am going out to eat. See you later. – tlfong01 Apr 27 ’19 at 5:04
- imgur.com/gallery/UyG3ii4 – Alex White Apr 27 ’19 at 5:15
- Sorry that took ages… My internet is awful. – Alex White Apr 27 ’19 at 5:16
- Let us continue this discussion in chat. – tlfong01 Apr 27 ’19 at 6:40
Add a commentStart a bounty
1 Answer operation converting the stepper from unipolar to bipolar.
- Open the casing
- Cut away the red wire, so that the two windings do not electrically connected to each other.
Now I am googling something to read, and jot down some pictures, …
Now the schematic for L293D driving a bipolar stepping motor.
I have found a L293D module in my junk box.
Now I have shrinked and merged 4 big pictures into one big picture for my small eyes to look at.
The problem is we don’t know the colour code of the wiring scheme. For example, what colour is for 1a, 1b, 2a, 3b etc. If we could not find the colour code, we may need to use the multimeter and a 6 battery to find by trial and error manually.
Anyway, now I have removed the casing of the 5 wire unipolar motor. Next step is find out which trace to cut to separate the two coils sticking together at the red wire, to make it a 4 wire, two non connecting coils, red wire don’t care bipolar motor.
Now I am also thinking of testing my old stepper and compare how more powerful is, comparing to the small guy. The old guy costed me US$2 (a couple of years ago). The wires were badly torn, but I know there is no contact brushes to wear, so found it good and quite. A new one costed US$25. I thought it was very good money for a hobbyist to play with and learn something. As a newbie, I needed to google hard before I know how to use a battery, a multimeter, and a 1 pole, 12 throw to figure out which wire goes with which other wire, …
A stronger stepping motor to replace 28BYJ48, should be strong enough to turn Rubik cube
/ to continue, …
References
(1) 28BYJ-48 – 5V Stepper Motor
(2) Stepping Motor Fundamentals – Microchip
(3) Control of Stepping Motors A Tutorial – DW Jones Uni Iowa, 1995
(4) L293x Quadruple Half-H Drivers Datasheet – TI
(5) MINI L293D DC/stepping motor controller board – ¥9.50
(6) L293D DC motor control card dual h-bridge Module – US$ 1.43
(7) Stepping Motor Tutorial (Unipolar/Bipolar, Half Step/ Full Step, ULN2003/L293D)
(8) Stepping Motor Tutorial Using L298N Driver
(9) How does a Stepper Motor work? (Youtube 6 minute video) – Learn Engineering 3.17M subscribers 2,453,537 views 2016oct19
(10) What could be the reasons for a stepper motor stuttering with an A4988 driver? – EESE 2021apr05
(11) My experiments with stepper motor – ScientistNobee, 2015mar12
Appendices
Appendix A – Why we need a dual bridge motor driver (L293D or L298N)?
We need to use two H-bridge circuits (dual H-bridge) to drive both coils of a bipolar stepper motor.
How does a H-bridge circuit work?
The field effect transistors (FET) Q1 to Q4 act like switches. The diodes D1 to D4 act like freewheeling diodes to channel back-electromagnetic force (back-EMF) of the motor coils. When the ‘switches’ Q1 and Q4 are closed (and Q2 and Q3 are open) a conducting path is created and current will flow from +9Vdc to Q1 to the coil to Q4 to GND. By opening Q1 and Q4 switches and closing Q2 and Q3 switches, a different conducting path is generated from +9Vdc to Q2 to the coil to Q3 to GND. If you pay close attention you will notice the current flowing through the coil in the opposite direction, allowing reverse operation of the motor.
Note however the switches Q1 and Q2 should never be closed at the same time, as this would cause a short circuit. The same applies to the switches Q3 and Q4. This is why we cannot simply use Arduino [or Rpi] HIGH and LOW outputs to reverse the polarity; a H-bridge circuit is essential.
ShareEditDeleteFlagedited 3 mins agoanswered Apr 27 ’19 at 4:25tlfong013,62133 gold badges77 silver badges2222 bronze badges
- Comments are not for extended discussion; this conversation has been moved to chat. Alex, you should be able to use this one. If not leave a msg here
@goldilocks. – goldilocks♦ Apr 27 ’19 at 13:34
- I know you modified the 28byj48 uniplor stepping motor to bipolar, by tearing it down and disconnecting the common read wire. I did the same thing but found that changing from unipolar to bipolar does not make the motor much more powerful. You also changed the power sequence from half step to full step etc, hopping to increase torque. I also did the same thing, but not much improvement. I forgot to added that to increase torque, 28BYJ48 is very limited. I just found a more powerful stepping motor in may junk box, together with a “micro stepping driver”. This combination is more powerful. – tlfong01 May 22 ’19 at 5:40
- I forgot if you wish to rotate the Rubik cube using 4 stepping motors. 28BYJ24 is not powerful enough. I later used another more powerful one and found it OK to turn the Rubik cube. Perhaps I can show it later. – tlfong01 May 22 ’19 at 5:42
Categories: Uncategorized | https://tlfong01.blog/2021/04/10/stepper-motor-28bjy48-l293d/ | CC-MAIN-2021-31 | refinedweb | 1,325 | 71.24 |
I downloaded the Network Simulator NS-2 from here -
Build ns via GCC 4.2.2 -
tar-xzf ns-allinone-2.35.tar.gz
cd ns-allinone-2.35
./install
Get the error message -
make: *** [tk3d.o] Error 1
tk8.5.10 make failed! Exiting ...
For problem with Tcl / Tk see
I pass on the link - Scriptics.com - there a a message -
"The Script Archive is under reconstruction. Please come back soon."
Then i try -
cd ns-allinone-2.35/ && export CC=gcc-4.2 CXX=g++-4.2 && ./install
Get the following message -
================================
* Build tcl8.5.10
================================
checking whether to use symlinks for manpages... no
checking whether to compress the manpages... no
checking whether to add a package name suffix for the manpages... no
checking for gcc... gcc-4.2
checking for C compiler default output file name...
configure: error: C compiler cannot create executables
See 'config.log' for more details
tcl8.5.10 configuration failed! Exiting...
Tcl is not part of the ns project. Please see
to see if they have a fix for your platform.
How to properly build the NS-2 in Linux Mandriva?
I updated GCC to version GCC-4.7.2, then installed ns-2.34.
Previously made some changes in the source code -
in mac/mac-802_Ext.h(or in mac-802_11Ext.h for ns 2.35), line 65 - add
# include "cstddef";
also-in file linkstate/ls.h at line 137 replace -
void eraseAll () {erase (baseMap :: begin (), baseMap :: end ());}
to
void eraseAll () {this-> erase (baseMap :: begin (), baseMap :: end ());}
Now let us take a simple test (ns-simple.tcl) -
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
Run (according to) -
export DISPLAY localhost:6000
ns ns-simple.tcl
Output -
CBR packet size = 1000
CBR interval = 0.0080000000000000002
[root@localhost ...]# _X11TransSocketINETConnect() can't get address for: Name or service not known
nam: couldn't connect to display ""
What could this mean? How to get the image?
Next. If I point IP of the remote server on which i installed ns-2, I get the following error -
[root@localhost ...]# export DISPLAY=..ip_of_remote_server_:0.0
[root@localhost ...]# ns ns-simple.tcl
CBR packet size = 1000
CBR interval = 0.0080000000000000002
[root@localhost ...]# Xlib: connection to "ip_of_remote_server_:0.0" refused by server
Xlib: No protocol specified
nam: couldn't connect to display "ip_of_remote_server_:0.0"
export $DISPLAY localhost:6000
$
6000
From your log, its looks like you are running the display on the localhost only. My suggestion is to use the following export command:
% export DISPLAY=:0.0
and try running it again. I use this same command on my Ubuntu 12.10 system and it works.
About the installation, make sure that you've installed all the necessary tools for building.
I had the same issue with an Ubuntu 10.04 and I found this.
The tools I installed:
I installed them all using apt-get install and it worked.
Good luck.
By posting your answer, you agree to the privacy policy and terms of service.
asked
1 year ago
viewed
2404 times
active
3 months ago | http://superuser.com/questions/525110/installing-network-simulator-ns-2-allinone-on-linux-mandriva | CC-MAIN-2014-15 | refinedweb | 529 | 70.7 |
Pike 7.8 Release Notes
Pike 7.8 release notes
This is a high level list of changes between Pike 7.6 and Pike 7.8. General bug fixes, build fixes and optimizations are not mentioned here. For a complete list of changes, please consult the CVS changelog either directly or through Code Librarian.
New / improved language functionality
- New syntax to index from the end in range operations.
A "<" can be added before an index in the [..] operator to count from the end instead, beginning with 0 for the last element. This is convenient to e.g. chop off the last element in an array: a[..<1].
- New `[..] operator function.
Range operations have been separated from the `[] operator function and are now handled by the new `[..] which provides greater control for how the range bounds are specified. For compatibility, if there is no `[..] then `[] is still called for range operations.
The `[..] callback will get four arguments, start value, start type, end value and end type. The type arguments is any of Pike.INDEX_FROM_BEG, Pike.INDEX_FROM_END or Pike.OPEN_BOUND. Here are a few examples of what input arguments different calls would generate.
-".
- Added support for getters and setters.
It is now possible to simulate variables with functions. Example:
class A { private int a; int `b() { return a; } // Getter for the symbol b. void `b=(int c) { a = c; } // Setter for the symbol b. int c() { return b; // Calls `b(). } } object a = A(); a->b = 17; // Calls `b=(17). werror("%d\n", a->b); // Calls `b().
- Casting to derived types.
It is now possible to call a value of type type to perform the corresponding value cast. eg:
typedef string MyString; return MyString(17); // Casts 17 to "17".
-.
- Stricter type checker for function calls.
The type checker for function calls is now based on the concept of currification. This should provide for error messages that are more easily understood. It also is much better at typechecking function calls utilizing the splice (@) operator. The mechanisms used by the typechecker are also made available as Pike.get_first_arg_type(), Pike.low_check_call() and Pike.get_return_type().
- Stricter typing of strings.
The string type may now have an optional value range.
string(0..255) bytes;
- Support for having multiple different active backend implementations.
In Pike 7.6 and earlier, there could only be one active backend implementation at a time, which was the one selected for best performance with lots of files (cf Pike.Backend below). This led to problems when Pike attempted to run poll-device based backends on older versions of operating systems where poll devices aren't available, and with extra overhead when the backend was only used with a very small set of files.
Basic backend implementations:
- Pike.PollDeviceBackend
This is a backend that is implemented based on keeping the state in the operating system kernel and thus eliminating the need to send the state in every system call. This is however not available on all operating systems. Currently supported are /dev/poll (Solaris, etc), epoll(2) (Linux) and kqueue(2) (FreeBSD, MacOS X).
- Pike.PollBackend
This is a backend that is implemented based on the poll(2) system call. This is typically available on all System V or Linux based systems.
- Pike.SelectBackend
This is a backend that is implmented based on the BSD select(2) system call. This backend is available on all operating systems supported by Pike.
Derived backend implementations:
- Pike.Backend
This is the backend selected among the basic backend implementations, which is likely to have the best performance when there are lots of files in the backend.
- Pike.SmallBackend
This is the backend selected among the basic backend implementations, which is likely to have the best performance when there are very few files in the backend.
Note that there is also a default backend object:
- Pike.DefaultBackend
This is the Pike.Backend object that is used for file callbacks and call outs if no other backend object has been specified.
- cpp
The preprocessor now supports macro expansion in the #include and #string directives.
#include USER_SETTINGS
- Destruct reason passed to lfun::destroy.
lfun::destroy now receives an integer flag that tells why the object is being destructed, e.g. if it was an explicit call to destroy(), running out of references, or reaped by the garbage collector.
These integers are defined in the new Object module as DESTRUCT_EXPLICIT, DESTRUCT_NO_REFS, DESTRUCT_GC and DESTRUCT_CLEANUP.
- Improved support for mixin.
The Pike compiler now supports mixin for symbols that have been declared protected. Mixin is the concept of overloading symbols via multiple inheritance. In previous versions of Pike the mixin paradigm was only supported for public symbols. For more information about mixin see eg.
- Implicit and explicit create().
The compiler now supports defining classes with both an implicit and an explicit create().
- Warnings for unused private symbols.
The compiler now checks that all symbols that have been declared private actually are used.
class A (int i) { protected string j; protected void create(string j) { A::j = reverse(j); } }
- Warnings for unused local variables.
The compiler now checks that all local variables are used.
- Unicode
Case information and the Unicode module are updated to Unicode 5.1.0.
- The keyword protected
The modifier protected is now an alias for the modifier static. NOTE: In the next release static will be deprecated.
- extern declared variables
Variables can now be declared as 'extern'. This means that inheriting classes must have them. They can be used like normal variables in the base class.
Example: class A { extern int a; int dummy() { return ++a; } }
- __attribute__ and __deprecated__
It's now possible to set custom attributes on types, so that it is possible to make custom type checking. This is currently used to improve the argument checking for sprintf() and related functions, and for marking symbols as deprecated. eg:
__deprecated__ mixed obsolete_function(); __deprecated__(mixed) obsolete_return_value(); mixed fun(__deprecated__(mixed) obsolete_arg); __deprecated__(mixed) obsolete_variable;
The deprecated type flag using __deprecated__ is a convenience syntax to use instead of e.g.
void f(void|__attribute__("deprecated",int) timeout)
Other uses of __attribute__ in type declarations can be seen in e.g. the type for werror():
> typeof(werror); (1) Result: scope(0,function(string : int) | function(__attribute__("sprintf_format", string), __attribute__("sprintf_args", mixed) ... : int) | function(array(string), mixed ... : int))
- __func__
The symbol __func__ now evaluates to the name of the current function. Note that this name currently can differ from the declared name in case of local functions (i.e. lambdas). Note also that __func__ behaves like a literal string, so implicit string concatenation is supported. eg:
error("Error in " __func__ ".\n");
- __DIR__
__DIR__ is a new preprocessor symbol that resolves to the directory that the current file is placed in. Similar to how __FILE__ points out the file the code is placed in.
- #pragma {no_,}deprecation_warnings
Warnings for use of deprecated symbols can be turned off for a segment of code with
#pragma no_deprecation_warnings
and turned on again with
#pragma deprecation_warnings
- Compatibility name spaces
Older versions of a function can be reached through its version name space. For example the 7.4 version of the hash function can be called through 7.4::hash().
- Iterator API
The iterator API method Iterator->next() is no longer optional.
Extensions and New Functions
- exit()
Exit now takes optional arguments to act as a werror in addition to exiting the process.
exit(1, "Error while opening file %s: %s\n", path, strerror(errno()));
- getenv()/putenv()
getenv() and putenv() are now accessing and modifying the real environment.
- get_dir()
Calling get_dir() with no arguments will now return the directory listing for the current directory.
- undefinedp()/destructedp()
undefinedp() and destructedp() have been added as more readable alternatives to zero_type().
- limit()
The new toplevel function limit(a, x, b) is a convenience function that works like min(max(a,x),b).
- listxattr(), getxattr(), setxattr(), removexattr()
The new xattr functions listxattr(), getxattr(), setxattr and removexattr() allows extended file attributes to be modified from within Pike.
- sprintf() and sscanf()
- sprintf() now attempts to lookup the name of the program when formatting types of objects and programs.
- The new formatting directive %H can be used to format a string as a binary hollerith string.
> sprintf("%2H", "Hello"); (1) Result: "\0\5Hello"
- The new formatting directive %q can be used to format a atring as a quoted string, quoting all control character and non-8-bit characters as well as quote characters. Like %O but always on one line.
> sprintf("%q", "abc \x00 \" \' \12345"); (1) Result: "\"abc \\0 \\\" ' \\u14e5\""
- Ranges in sscanf sets can now start with ^, even at the beginning of the set specifier. Example: %[^-^] matches a set with only ^ in it. To negate a set with - in it, the - character must now be the last character in the set specifier.
- encode/decode value and programs
--with-portable-bytecode is now the default. Pike programs that have been dumped on one architecture now can be decoded on another.
- gethrtime, gethrvtime, gauge
Added support for POSIX style timers using clock_gettime(3). Notably this fixes nice high resolution thread local cpu time and monotonic real time on reasonably modern Linux systems.
There are new constants CPU_TIME_* and REAL_TIME_* in the System module to allow pike code to query various properties of the CPU and real time clocks in use.
- ADT.BitBuffer
Added read() method that reads whole bytes from the buffer and returns as a string.
- ADT.Queue
It is now possible to use sizeof() and values() on a Queue object to get the size of the queue and all elements in the queue as an array.
- ADT.Stack
Stack objects can now be cast to arrays to get all elements on the stack.
- ADT.Struct
- New Item class SByte, SWord and SLong represents a signed byte, word and longword respectively.
- The Item classes int8, uint8, int16, uint16, int32, uint32, int64 and uint64 are aliases for already existing Item classes.
- sizeof() now works for empty Struct objects.
- sizeof() can be used on individual Item objects.
- Struct objects can now be used as Items in other Structs.
class Pair { inherit ADT.Struct; Item id = uint8(); Item val = uint64(); } class File { inherit ADT.Struct; Item magic = Chars(4); Item one = Pair(); Item two = Pair(); }
- Array
- New function combinations() returns all combinations of a specified length with elements from a given array.
- Added push(), pop(), shift() and unshift() functions for Perl weirdos.
- Calendar
- Added new calendar Badi, used in the Baha'i religion.
- Fixed bugs in discordian, where the year() was off by 1166 and now() was off 5 month per year.
- Time objects now handle * and / with floats. A split() method has been added for more advanced splitting where the preferred time quanta can be given as an argument.
- A new formatting method format_ext_time_short() has been added to Time objects.
- Timezones are now read from /etc/localtime, if available.
- Cleaned up year-day (yd) handling so that it never goes below 1. Instead be careful to use either year (y) or week-year (wy) depending on context.
- Fixed inconsistent range handling in year() and years() that made them almost but not quite zero-based. Now they are one-based just like day()/days(), month()/months() etc.
- Cleaned up conversion between weeks and years: E.g. if a week has days in two years then converting it to years will produce a range of both years. The attempt to always map a week to a single year is gone since it's inconsistent with how other overlapping time ranges are handled. If the user wants to convert a week to the year it "unambiguously" belongs to, (s)he can do Calendar.ISO.Year(week->year_no()).
- Did away with the attempt to map leap days between February 24th and 29th before and after year 2000, since doing so breaks date arithmetic.
- The last four changes above are not entirely compatible. Compatibility with 7.6 and older is retained with #pike 7.6.
- CompilerEnvironment & CompilerEnvironment()->PikeCompiler
The Pike compiler has been refactored to be more object-oriented and more transparent. It is now possible to customize the compiler by overloading functions in the above two classes. The compiler object used by Pike internally is available through the global constant DefaultCompilerEnvironment.
- Debug
The new function count_objects() will return the different kinds of objects existing within the Pike process. Useful when trying to pinpoint a leak of Pike objects.
- Error
The new function mkerror() will normalize any thrown value into a proper error object (or 0).
- Filesystem
Traversion has been extended with two new create arguments. The first one is a flag to supress errors and the other is a sorting function which will be applied to the entries in every directory. This callback can also be used to filter the directory entries.
- Float
The function isnan() can be used to check if a float is Not a Number.
> Float.isnan(Math.inf/Math.inf); (1) Result: 1
- Gdbm
Gdbm databases can be opened in synchronous mode or locking mode by adding "s" or "l" respectively in the mode parameter to the create method.
- Geography.Position
It is now possible to encode Position objects with encode_value().
- GLUE
- The default event callback will now exit both on Exit and Escape events.
- The texture, list and light id generators will now be created after we are sure that GL has been initialized, to prevent crashes on several systems.
- BaseTexture and BaseDWIM now supports clamped textures.
- Gmp
Many small changes to fix Gmp build issues on different platforms. The most visible being that the Gmp module now is statically linked to work around Mac OS X 10.5 linker issues.
- Gz
- Added compress() and uncompress() functions as a simpler and more efficient but non-streaming interface.
- Support for RLE And FIXED compression method, if supported by zlib. Give Gz.RLE or Gz.FIXED to the strategy argument of compress() or the deflate constructor.
- Added support for configurable compression window size. This is the last argument to compress() and the constructor for inflate/deflate.
- Image.Colortable
- The new method greyp() can be used to query if the color in the color object is grey.
- Partial support for serializing color objects. Dithering type and lookup mode is not currently saved.
- Image.Dims
Support for parsing out the dimensions of TIFF files has been added.
- Image.FreeType
Added support for handling monochrome (bitmap) fonts.
- Image.Image
- Image object can now be serialized and deserialized with encode_value() and decode_value().
- It is possible to convert the colors in an image object to and from YUV (YCrCb) with the new rgb_to_yuv() and yuv_to_rgb() methods.
- Image.Layer
It is now possible to get the raw bitmap data of a layer by casting the layer object to a string.
- Image.PNG
- Properly decode cHRM (chrome), sBIT (sbit), gAMA (gamma), pHYs (physical), oFFs (offset), tIME (time) chunks.
- The compression level and strategy when compressing PNG images can be controlled by passing "zlevel" and "zstrategy" options to the encode() method. Available strategies are filtered, huffman, rle and fixed.
Image.PNG.encode( img, ([ "zlevel":9, "zstrategy":Gz.RLE ]) );
- Image.TIFF
Added support for little endian TIFF files.
- Int
Int.inf is an object that can be used as an infinitly large integer.
- Java
- If possible, Pike now uses libffi instead of creating our own trampolines. Adding libffi as a bundle is supported.
- Added built-in support for SPARC64 trampolines.
- The method signature fuzzy-matcher now only considers Pike strings to match formal parameters of type String, Object, Comparable, CharSequence or java.io.Serializable.
- When the fuzzy-matcher can not decide on a single method signature, all candidates are now listed in the error message.
- Locale.Charset
- The character name normalizer now recognizes Unicode prefixes, e.g. "unicode-1-1-utf-7", though the Unicode version itself is ignored.
- Added support for the following character sets
GB18030/GBK (CP936) UTF-EBCDIC DIN-31624 (ISO-IR-38) ISO-5426:1980 (ISO-IR-53) ISO-6438:1996 (ISO-IR-39, ISO-IR-216) ISO-6937:2001 (ISO-IR-156) GSM 03.38 Mysql Latin 1
- Added typed encode and decode error objects, Locale.Charset.EncodeError and Locale.Charset.DecodeError, to make it possible to catch such errors in a better way.
- ISO-IR non-spacers are now converted into combiners.
- Math
- Matrix multiplication was bugged and gave B*A instead of A*B, which is now fixed.
- Matrix objects now have xsize() and ysize() methods to query their dimensions.
- To ease your logarithmic needs log2() and logn() have been added.
- MIME
- Added remapping variants of the encode words functions with encode_word_text_remapped(), encode_word_quoted(), encode_words_quoted_remapped() and encode_words_quoted_labled_remapped().
- Added workaround for a bug in Microsoft Internet Explorer where it forgets to properly quote backslashes in the Content-Disposition field.
- Fixed a bug that could occur when casting MIME.Message objects to strings.
- Mysql
- Two functions set_charset() and get_charset() have been added to set and query the connection charset. The create() function also takes a "charset" setting in the options mapping.
- Improved Unicode support. The MySQL driver now supports (possibly wide) Unicode queries and text return values, handling the connection charset and all encoding/decoding internally. This is enabled by setting the charset to "unicode", or through the new functions set_unicode_encode_mode() and set_unicode_decode_mode(). See their documentation for further details.
- Odbc
The Odbc module has been updated to support the UnixODBC library, and several issues with Unicode and FreeTDS handling have been fixed.
- Oracle
- The module has been updated to work with Oracle 10.
- An approximation of the number of rows in a result object can be queried from the new function num_rows().
- Parser.HTML
Allow string and array as argument to _set_*_callback(). Those variants work just like a function only returning the string or array.
- Parser.Pike and Parser.C
- Parser.Pike and Parser.C have been rewritten in C for increased performance.
- The #string directives should be handled correctly now.
- Parser.RCS
The RCS parser has been rewritten to be more robust with regards to broken RCS data.
- Parser.XML.NSTree
- Added add_child_before() and add_child_after() methods to the NSNode object.
- Parser.XML.Simple
The autoconvert() function, used to autodetect the character encoding of an XML file and decode it, has been moved from being a method of the Parser.XML.Simple object to being a function in the Parser.XML module.
- Parser.XML.SloppyDOM
Yet another DOM-like module aimed at quickly and conveniently parse an xml snippet (or whole document) to access its parts. Nodes can be selected using a subset of XPath.
Footnote: This module was previously part of Roxen WebServer.
- Parser.XML.Tree
The module code has been refactored and a second "simple" interface has been added. The (new) SimpleNode interface implements a node tree interface similar to the (old) Node interface, with two major differences:
- The SimpleNodes do not have parent pointers, this means that they do not generate cyclic data structures (and thus less garbage, and no need for zap_tree()), but also that it is no longer possible to find the root of a tree from any node in the tree.
- Some methods in SimpleNode return different values than the corresponding method in Node; notably SimpleNode()->add_child(), which returns the current node rather than the argument.
The refactoring also added individual classes for all of the XML node types (both for Nodes and for SimpleNodes). This allows for stricter typing of code involving XML tree manipulation.
Several new functions added to manipulate and insert nodes in the XML tree.
The module now also has a much better knowledge of DTDs and DOCTYPEs.
- Postgres
- Extended the SQL query interface to include affected_rows() and streaming_query() as well as variable bindings.
- Automatic binary or text transfer for queryarguments and resultrows.
- Pike
- A new function count_memory() has been added which can calculate the memory consumed by arbitrary data structures. Useful when implementing memory caches.
- A new function get_runtime_info() has been added which returns information about current ABI, if automatic bignums are enabled, what bytecode method is used, the size of native floats and integers and the native byte order.
- The constants INDEX_FROM_BEG, INDEX_FROM_END and OPEN_BOUND has been added for use with the `[..] operator API.
- The functions low_check_call(), get_return_type() and get_first_arg_type() allows for inspection of attributes and return values of functions.
- Pike.Backend
Besides the new multiple backend implementations described earlier, backends now support two new callbacks: before_callback and after_callback are two new variables in the backend objects. They can be set to functions that gets called just before and after a backend is waiting for events.
- Process
- The new function spawn_pike() will spawn a Pike process similar to the current one, using the same binary file, master and module paths.
- The new function run() is an easy interface that will run a process and return a mapping with all the outputs and exit code.
- Process.popen is now able to run in nonblocking mode. If a second argument is provided a file object will be opened with that mode and return, enabling two way communication with the new process.
- The system() function has been extended to be able to pass stdin, stdout and stderr arguments to the spawn() call it performs.
- Protocols.DNS
- Added support for NAPTR (RFC 3403) and SPF (RFC 4408) records.
- The gethostbyname() function now returns IPv6 addresses too, if available.
- Fixed bugs in IPv6 record parsing.
- Protocols.Bittorrent
- Support for gzipped and compact tracker responses.
- Many performance and bug fixes, such as 30% faster hashing of files.
- Protocols.HTTP
- Added support for httpu and httpmu requests.
- Queries will now throw an exception in case of an errno condition.
- A new function, do_async_method(), has been added to allow access to low level asynchronous HTTP calls.
- The http_encode_string() function now knows how to encode UCS-2 characters.
- Protocols.HTTP.Server
- If accept() fails on the open port, the Port object will continue trying, to support servers with high load.
- Protocols.HTTP.Query
- Added unicode_data() method that will return the payload decoded according to the charset described in the Content-Type header.
- Many fixes for bugs in asynchronous mode.
- A query will not silently downgrade to http from https anymore if there is no crypto support.
- Fixes for keep alive.
- Protocols.LDAP
- Enabled support for paged queries.
- Added more resilience to UTF-8 encode errors. Locale.Charset.DecodeError is thrown for UTF-8 decode exceptions.
- Added a connection pool for connection reuse. It is used through get_connection() and return_connection().
- Added some schema handling and use it to fix the UTF-8 conversion to only affect attributes that actually are UTF-8 encoded.
- Added client.read(), client.read_attr(), client.get_root_dse_attr(), client.get_basedn(), client.get_scope(), client.get_attr_type_descr(), get_constant_name(), and a bunch of constants for various object oids, attributes, well-known object guids and other things.
- Rewrote the search filter parser to handle LDAPv3 extensible matches. It now also throw errors on all syntactic errors (using a new FilterError object), instead of sending a partial filter to the server. It is also possible to compile filters separately through make_filter(), and there is a very simple cache for compiled filters through get_cached_filter().
- Added ldap_encode_string(), ldap_decode_string(), encode_dn_value(), canonicalize_dn(), parse_ldap_url(), client.get_parsed_url(), and client.get_bound_dn().
- Added client.result.fetch_all().
- Added new flag field to client.search() to control various aspects of how results are returned: SEARCH_LOWER_ATTRS lowercases all attribute names. SEARCH_MULTIVAL_ARRAYS_ONLY uses arrays for attribute values only for attributes that might return more than one value. SEARCH_RETURN_DECODE_ERRORS may be used to avoid throwing exceptions on decode errors.
- Added client.get_protocol_version(), client.get_supported_controls(), and the possibility to specify controls in client.search().
- Made the result iterator somewhat more convenient: next() now advances one step past the end so the next fetch() returns zero.
- Added client.error_number(), client.error_string(), and client.server_error_string() to make it possible to query errors when no result object is returned.
- Protocols.SNMP
The readmsg() method in the protocol object now takes an optional timout argument.
- Protocols.XMLRPC
The new AsyncClient class implements an asynchronous XMLRPC client.
- Regexp.PCRE.Widestring
- Replace matches in a string, with support for backreferences, now possible from replace_positional().
> Regexp.PCRE.Plain("my name is ([a-zA-Z]+)")-> >> replace_positional("hello, my name is john.", >> "%[0]s is my name"); (1) Result: "hello, john is my name."
- Regexp.PCRE.Widestring is now reported in the basic feature list (pike --features).
- Sql
- Bugfixes in listing Postgres fields.
- If ENABLE_SPAWN_RSQLD is defined, rsqld will be spawned when needed to complete rsql queries.
- Added streaming_query() method to Sql objects which enables larger result sets than available memory.
- It is possible to iterate over the result object from big_query() queries directly in foreach.
- Support UNDEFINED to designate NULL in emulated bindings.
- Support for ODBC DSN files.Sql.Sql db = Sql.Sql("dsn://user:pass@host/database");
- Some native support for the TDS protocol, used by Sybase and Microsoft SQL server.
Sql.Sql db = Sql.Sql("tds://user:pass@host/database");
- Support for the SQLite database added. A raw interface is available through the SQLite module.
Sql.Sql db = Sql.Sql("sqlite://relative/path/to/file"); Sql.Sql db = Sql.Sql("sqlite:///absolute/path/to/file");
- Sql.pgsql. New driver for native PostgreSQL network protocol support. It implements a superset of the existing Postgres driver. Current features: no library dependencies (no libpq), native binding support, streaming support, NOTIFY/LISTEN support (fully eventdriven, no polling), binary support for integer, float and string datatypes through big_typed_query(), native support for 64-bit ints and doubles, COPY FROM/TO STDIN/STDOUT support, multiple simultaneous streaming queries on the same connection (i.e. multiple PostgreSQL-portal- support), automatic precompilation and caching of often-used long-compile-time-needing queries, extended columndescriptions, accurate error messages under all circumstances, SSL-support, SQL-injection protection since it will ignore everything after the first semicolon delimiting the first command in the query, integrated statistics, _reconnect callback for sessions that use temptables.
Performance tuned, with the helperclass _PGsql.PGsql it currently is around 21% faster than the old libpq based Postgres driver for smaller queries; for large bytea blobs and large texts, it speeds up even more.
Support for this driver is indicated by PostgresNative appearing in the featurelist, and since it has no library or OS dependencies, it will always be available.
This driver serves URLs of the form: pgsql:// (plain) and pgsqls:// (SSL). In case the old Postgres driver is disabled, this driver takes over postgres:// transparently as well.
- SSL
It is now possible to set certificates to SSL connections. Example:
SSL.sslfile ssl_connection(Stdio.File conn, string my_key, string my_certificate) { ctx->client_rsa = Standards.PKCS.RSA.parse_private_key(my_key); // client_certificates is an array holding arrays of certificate // chains. since we've got a self-signed cert, our cert array has // only 1 element. ctx->client_certificates += ({ ({ my_certificate }) }); return SSL.sslfile(conn, ctx, 1, 1); }
- Standards.IIM
Some bugfixes in parsing Photoshop headers and DOS EPS Binary Headers.
- Standards.ISO639_2
Updated with the latest ISO639-2 languages.
- Standards.URI
- Updated to conform to RFC 3986.
- Added methods get_query_variables(), set_query_variables(), add_query_variable() and add_query_variables() to give a better API to to handle query variables.
- The new method get_http_query() returns the query part and get_http_path_query() returns both the path and the query, both coded according to RFC 1738.
- Standards.UUID
- Added support for UUID version 5; name based with SHA hash, which can be generated from the make_version5 function.
- An UUID object can now be used as namespace in the second argument to make_version3 as well as the new make_version5.
- Standards.XML.Wix
- Updated to support a more recent version of the Wix tool chain.
- Improved generation of 8.3-style filenames.
- Added support for Shortcut and IniFile-nodes.
- Added support for overriding the language and installer version.
- Improved support for TTF-files.
- Stdio
- Stdio.cp can now work recursively in a directory tree. It will also keep the permissions of files it copies.
- Added Stdio.recursive_mv which works on every OS and also when the destination isn't on the same filesystem as the source.
- Added more symbolic default termcap/terminfo bindings to Stdio.Readline.
- Improved support for Terminfo on NetBSD.
- read_file(), read_bytes(), write_file() and append_file() will now throw exceptions on uncommon errors such as when write_file() is unable to write all its data.
- Stdio.File->openat(), statat() and unlinkat() opens, stats and removes a file or directory relative to an open directory.
- Stdio.FILE->unread() allows pushing back binary strings into the input stream, as opposed to ungets() which pushes back lines.
- Stdio.UDP has had enable_multicast(), set_multicast_ttl(), add_membership() and drop_membership() added to make real multicast use possible.
- String
- The function int2size has been rewritten to fixpoint as well as using the more common abbreviation of "B" for byte.
- String.secure marks a string as "secure" which currently only means that the memory is cleared before it is freed.
- System
- resolvepath() is now enabled on more OSes and falls back to realpath(3C) if resolvepath(2) doesn't exists.
- On systems that support it, setproctitle() can be used to set the title of the running application.
- Added support for POSIX style timers using clock_gettime(3) to allow for high resolution thread local cpu time and monotonic real time on reasonably modern Linux systems for gethrvtime() and gauge(). Added CPU_TIME_RESOLUTION, CPU_TIME_IMPLEMENTATION, REAL_TIME_IS_MONOTONIC, REAL_TIME_RESOLUTION and REAL_TIME_IMPLEMENTATION constants to tell the system capabilities.
- Tools.Hilfe
- Added support for tab-completion on modules, global and local symbols and operators.
- Added support for file/directory completion within strings.
- Added doc command and F1 key to print documentation on an item if available (currently only works for modules and classes written in pike).
- Tools.Standalone
- "pike -x cgrep" now tries to parse Java code.
- "pike -x features" now tests for several more features.
- Web.Crawler
- Bugfix to support robots.txt created on windows.
- User Agent change to "Mozilla 4.0 (PikeCrawler)"
- Web.RDF
- Added add_statement() method which allows new relations to be added to an RDF set.
New modules / classes / methods added
- Fuse
FUSE (Filesystem in USErspace) provides a simple interface for userspace programs to export a virtual filesystem to the Linux kernel (and some other OS:es). FUSE also aims to provide a secure method for non privileged users to create and mount their own filesystem implementations
This module implements the needed interfaces to make it possible to write a FUSE filesystem in Pike.
- ADT.List
A simple doubly linked list of values.
ADT.List l = ADT.List(1, 2, 3); l->insert(-1, 0); l->append(4, 5); foreach(l; int index; int value) { werror(" %d: value: %d\n", index, value); }
-.
- Arg
The new argument parser module allows for Getopt style argument parsing, but with a much simpler and object oriented API.
class Parser { inherit Arg.Options; Opt verbose = NoOpt("-v")|NoOpt("--verbose")|Env("VERBOSE"); Opt name = HasOpt("-f")|HasOpt("--file")|Default("out"); Opt debug = MaybeOpt("-d")|MaybeOpt("--debug"); }
void main(int argc, array(string) argv) { Parser p = Parser(argv); werror("name: %O, verbose: %O, debug: %O\n", p->name, p->verbose, p->debug); }
A more simplistic interface is also available for smaller hacks and programs.
void main(int argc, array(string) argv) { mapping opts = Arg.parse(argv); argv = opts[Arg.REST]; }
- GSSAPI
Implements Pike access to GSS-API v2 as specified in RFC 2743. This API is used to authenticate users and servers, and optionally also to encrypt communication between them. The API is generic and can be used without any knowledge of the actual implementation of these security services, which is typically provided by the operating system.
The most common implementation is Kerberos, which means that the main benefit of this API is to allow clients and servers to authenticate each other using Kerberos, thereby making single sign-on possible in a Kerberized environment.
- GTK2
Wrapper for the GTK2 library. Not yet 100% completed, but usable.
-.
- Bittorrent.Tracker
Bittorrent tracker with support for scraping and UDP extension.
- Protocols.HTTP.Server.Proxy
A simple HTTP proxy.
- Standards.TLD
Country domains and other TLDs according to IANA. Useful when parsing log information or providing live information about clients connecting to your server.
- Tools.Shoot
Several new tests have been added to benchmark and improve on various aspects of Pike. ReplaceParallel and ReplaceSerial measure the times measure different methods of completing the same task; to remove XML tags from a string.
- Web.CGI
Provides a CGI interface on the callee side. Retrieves information from environment variables and populates the variables in the Request object.
Deprecations
- The keyword nomask has been deprecated. It was functionally equivivalent with the keyword final.
- Stdio.File->set_peek_file_before_read_callback() is deprecated.
Incompatible changes
These incompatible changes can be solved by adding #pike 7.6 to your source file or starting Pike with -V7.6 unless otherwise noted.
- main() environment
The main() method will no longer be given the environment as a mapping as third argument. Use an explicit call to getenv() instead.
- Array.transpose_old
This function has been removed.
- Calendar
Changes made to fix inconsistensies has created som unavoidable incompatibilities. See the entry for Calendar in the functional changes section for details.
- _Charset
The parts of this internal module that were written in Pike have moved to Locale.Charset.
- Crypto
The old crypto functions from Pike 7.4 have been removed. These functions produced a warning when used in Pike 7.6.
- Debug.describe_program
The API for this debug function has changed.
- Image.Image
The functions select_colors(), map_closest(), map_fast() and map_fs() has been removed. Use Image.Colortable operations instead.
-.
- Protocols.LDAP.client
The "dn" field wasn't properly utf-8 decoded in 7.6 and earlier. If your application does it yourself, you need to use the compatibility version of this class.
- spider.XML
The spider module no longer contains the XML parser. The functions isbasechar(), iscombiningchar(), isdigit(), isextender(), isfirstnamechar(), ishexchar(), isidiographic(), isletter(), isnamechar() and isspace() have also been moved to the Parser module.
- Sql.Sql
Pike will no longer create a .column entry in SQL query responses if there is no table name.
- Standards.UUID
Functions new() and new_string() have been removed. Use make_version1(-1)->encode() and make_version1(-1)->str() instead.
- Stdio
The functions read_file(), read_bytes(), write_file() and append_file() now always throw errors on error conditions, to allow easier use as errno doesn't have to be checked. read_file() and read_bytes() still return 0 if the file does not exist.
- The modules Mird, Perl and Ssleay have been removed.
Note that these modules are not avilable via the backwards compatibility layer.
C level module API
- Improved support for embedding.
Several declarations and definitions (most notably the debug and runtime flags) have moved from main.h to pike_embed.h, in an attempt to add support for embedding.
- Major compiler API cleanups.
The Pike compiler is now executing in a pike function context (rather than in an efun context), and it is possible to customize some of its behaviour via inherit (rather than via handler objects). As a consequence the compiler is now much closer to being thread-safe.
- The global variable next_timeout is no more.
It has been replaced by a backend-specific variable. Added backend_lower_timeout() for accessing the new variable. This fixes issues GTK, GTK2 and sendfile had with the new backend implementation.
NOTE! C-API incompatibility!
NOTE! Changed the argument for backend callbacks!
The argument is now a struct Backend_struct * when called at entry (was NULL).
The argument is now NULL when called at exit (was 1).
- Pike_fp->context
Pike_fp->context is now a pointer to the current struct inherit rather than a copy of it. This allows for easier access to inherited symbols in C-code.
- Inherit level argument added to several object handling functions.
In order to implement subtyping of objects, an extra argument "inherit_level" has been added to many object indexing related functions.
- .cmod:
Voidable pointer types are no longer promoted to mixed.
- Support for class symbols with storage in parent scope.
Also added support for aliased symbols.
- Machine code backend for PPC64
Machine code generation is now supported for PowerPC in 64-bit ABI mode.
- Objective-C embedding framwork
Experimental support for interfacing with Objective-C code has been added.
NOTE! This API is experimental and is subject to change
NOTE! without notice.
- Added %c and %C to get_all_args to get char * without NUL characters (no 0 valued characters inside the string).
%c: char * Only narrow (8 bit) strings without NUL. This is identical to %s. %C: char * or NULL Only narrow (8 bit) strings without NUL, or 0
Building and installing
- Dynamic modules now become DLLs on Windows.
This means the homegrown module loader is no longer used, but it also means some DLL limitations:
- PMOD_EXPORT is now required to allow access to an identifier in the pike core.
- DLLs have to be recompiled too if pike.exe is recompiled.
The primary motivation for this change is to work with the new library tracking (so-called "side-by-side assemblies") in Visual C++ 2005 and later.
- Added ABI selection.
It's now possible to select whether to compile in 32bit or 64bit mode at configure time by using the --with-abi option.
- MinGW builds.
It's now possible to build Pike in MinGW on windows computers from source distributions.
- Cmod precompiler.The cmod precompiler (pike -x precompile) now supports declaring all autogenerated identifiers as static.
NOTE! C-API incompatibility!
NOTE! As a side effect of this change, the DECLARATIONS statement
NOTE! is now required in cmod files.
New simplified method to write external C/C++ modules
It's now suggested that you do not use the fairly complex 'pike internal' style of external modules (configure.in with AC_MODULE_INIT etc).
It's also no longer required that you have a configure script to use pike -x module.
Instead simply locate the include files using 'pike -x cflags', and convert .cmod to .c files using 'pike -x precompile'.
An example rather minimal 'pike -x module' compatible Makefile, without a configure script, using .cmod format files for a simple local module:
| CC=gcc | CFLAGS := -O9 -fweb -shared -Wall $(CFLAGS) $(shell $(PIKE) -x cflags) -g | LD=$(CC) -shared -lGL | | all: Spike.so | | install: Spike.so | cp $< $(MODULE_INSTALL_DIR) | | Spike.so: Spike.o | $(LD) -o Spike.so Spike.o $(LDFLAGS) | | Spike.o: Spike.c | | Spike.c: Spike.cmod | $(PIKE) -x precompile $< > $@It's usually OK not to use pike -x module at all, but it will pass on a few extra variables to your make (and configure script):
PIKE: How to start the pike interpreter used running pike -x module MODULE_INSTALL_DIR: Where modules goes LOCAL_MODULE_PATH: Alternative (user local) module location | https://pike.lysator.liu.se/download/notes/7.8.xml | CC-MAIN-2019-43 | refinedweb | 6,380 | 58.08 |
This is a tutorial on C++ While loops.
The C++ while loop has two components, a condition and a code block. The code block may consist.
Syntax
Below is the general code for creating a while loop. The C++ while loop first checks the condition, and then decides what to do. If the condition proves to be false, the instructions in the code block will not be executed.
while (condition) { // Instructions be executed }
C++ While Loop Example
A basic example of the C++ while loop.
#include <iostream> using namespace std; int main() { int x = 0; while (x < 5) { cout << x << endl; x = x + 1; } return 0; }
0 1 2 3 4
As shown above, the while loop printed out all the numbers from 0 to 4. The loop terminated once the value of x reached 5, before the output statement was even reached. Hence 5 was not included in the output.
While Loops with multiple conditions
While loops in their most basic are useful, but you can further increase their ability through the use of multiple conditions.
You can chain together multiple conditions together with logical operators in C++ such as
&& (And operator) and
|| (Or operator). What you’re really doing is creating a longer equation that will return either True or False, determining whether the loop executes or not.
As a brief recap, with the
&& operator both conditions must be
True for it to return
True. For the
|| operator, as long as at least one condition is
True, it will return true.
#include <iostream> using namespace std; int main() { int x = 0; int y = 0; while (x < 5 && y < 6) { x = x + 1; y = y + 2; cout << "X: " << x << " "; cout << "Y: " << y << endl; } }
X: 1 Y: 2 X: 2 Y: 4 X: 3 Y: 6
This marks the end of the While Loops in C++ article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below. | https://coderslegacy.com/c/c-while-loops/ | CC-MAIN-2021-21 | refinedweb | 330 | 69.82 |
Tutorial: Listening for AWS Batch EventBridge
In this tutorial, you set up a simple AWS Lambda function that listens for AWS Batch job events and writes them out to a CloudWatch Logs log stream.
Prerequisites
This tutorial assumes that you have a working compute environment and job queue that are ready to accept jobs. If you don't have a running compute environment and job queue to capture events from, follow the steps in Getting Started with AWS Batch to create one. At the end of this tutorial, you can optionally submit a job to this job queue to test that you have configured your Lambda function correctly.
Step 1: Create the Lambda Function
In this procedure, you create a simple Lambda function to serve as a target for AWS Batch event stream messages.
To create a target Lambda function
Open the AWS Lambda console at
.
Choose Create a Lambda function, Author from scratch.
For Function name, enter batch-event-stream-handler.
For Runtime, choose Python 3.8.
Choose Create function.
In the Function code section, edit the sample code to match the following example:
import json def lambda_handler(event, _context): # _context is not used del _context if event["source"] != "aws.batch": raise ValueError("Function only supports input from events with a source type of: aws.batch") print(json.dumps(event))
This is a simple Python 3.8 function that prints the events sent by AWS Batch. If everything is configured correctly, at the end of this tutorial, you will see that the event details appear in the CloudWatch Logs log stream that's associated with this Lambda function.
Choose Deploy.
Step 2: Register Event Rule
In this section, you create a EventBridge event rule that captures job events that are coming from your AWS Batch resources. This rule captures all events coming from AWS Batch within the account where it's defined. The job messages themselves contain information about the event source, including the job queue where it was submitted. You can use this information to filter and sort events programmatically.
If you use the AWS Management Console to create an event rule, the console automatically adds the IAM permissions for EventBridge to call your Lambda function. However, if you're creating an event rule using the AWS CLI, you must grant permissions explicitly. For more information, see Events and Event Patterns in the Amazon EventBridge User Guide.
To create your EventBridge rule
Open the Amazon EventBridge console at
.
In the navigation pane, choose Rules.
Choose Create rule.
Enter a name and description for the rule.
A rule can't have the same name as another rule in the same Region and on the same event bus.
For Define pattern, select Event Pattern as the event source, and then select Custom pattern.
Paste the following event pattern into the text area.
{ "source": [ "aws.batch" ] }
This rule applies across all of your AWS Batch groups and to every AWS Batch event. Alternatively, you can create a more specific rule to filter out some results.
For Select targets, in Target, choose Lambda function, and select your Lambda function.
For Select event bus, choose AWS default event bus. You can only create scheduled rules on the default event bus.
For Select targets, choose Batch job queue and fill in the following fields appropriately:
Job queue: Enter the Amazon Resource Name (ARN) of the job queue to schedule your job in.
Job definition: Enter the name and revision or full ARN of the job definition to use for your job.
Job name: Enter a name for your job.
Array size: (Optional) Enter an array size for your job to run more than one copy. For more information, see Array Jobs.
Job attempts: (Optional) Enter the number of times to retry your job if it fails. For more information, see Automated Job Retries.
For Batch job queue target types, EventBridge needs permission to send events to the target. EventBridge can create the IAM role needed for your rule to run. Do one of these things:
To create an IAM role automatically, choose Create a new role for this specific resource
To use an IAM role that you created before, choose Use existing role
For more information, see EventBridge IAM role.
For Retry policy and dead-letter queue:, under Retry policy:
For Maximum age of event, enter a value between 1 minute (00:01) and 24 hours (24:00).
For Retry attempts, enter a number between 0 and 185.
For Dead-letter queue, choose whether to use a standard Amazon SQS queue as a dead-letter queue. EventBridge sends events that match this rule to the dead-letter queue if it can't deliver them to the target. Do one of the following:
Choose None to not use a dead-letter queue.
Choose Select an Amazon SQS queue in the current AWS account to use as the dead-letter queue and then select the queue to use from the drop-down list.
Choose Select an Amazon SQS queue in an other AWS account as a dead-letter queue and then enter the ARN of the queue to use. You must attach a resource-based policy to the queue that grants EventBridge permission to send messages to it.
(Optional) Enter one or more tags for the rule.
Choose Create.
Step 3: Test Your Configuration
You can now test your EventBridge configuration by submitting a job to your job queue. If everything is configured properly, your Lambda function is triggered and it writes the event data to a CloudWatch Logs log stream for the function.
To test your configuration
Open the AWS Batch console at
.
Submit a new AWS Batch job. For more information, see Submitting a Job.
Open the CloudWatch console at
.
On the navigation pane, choose Logs and select the log group for your Lambda function (for example, /aws/lambda/
my-function).
Select a log stream to view the event data. | https://docs.aws.amazon.com/batch/latest/userguide/batch_cwet.html | CC-MAIN-2022-05 | refinedweb | 986 | 72.56 |
go to bug id or search bugs for
Description:
------------
Hellow,
I've errors when I compile php on HP-UX
Reproduce code:
---------------
Here's my configure's options :
./configure \
--prefix=/PKl01h01/soft/web \
--with-libxml-dir=/PKl01h01/soft/web
Expected result:
----------------
No error on compile
Actual result:
--------------
/usr/ccs/bin/ld: Unsatisfied symbols:
libiconv (code)
libiconv_open (code)
libiconv_close (code)
zend_error_noreturn (code)
collect2: ld returned 1 exit status
*** Error exit code 1
Stop.
Add a Patch
Add a Pull Request
Please try using this CVS snapshot:
For Windows:
I've tried with the latest CVS and I don't have the zend_error_noreturn error message anymore. The others messages are still here :
/usr/ccs/bin/ld: Unsatisfied symbols:
libiconv (code)
libiconv_open (code)
libiconv_close (code)
collect2: ld returned 1 exit status
*** Error exit code 1
Stop.
Have you tried adding -liconv to your LDFLAGS?
Here's the result with LDFLAGS=-liconv
creating cache ./config.cache
checking for Cygwin environment... no
checking for mingw32 environment... no
checking for egrep... grep -E
checking for a sed that does not truncate output... /usr/bin/sed
checking host system type... hppa2.0n-hp-hpux11.00
checking target system type... hppa2.0n-hp-hpux11.00
checking for gcc... gcc
checking whether the C compiler (gcc -liconv) works... no
configure: error: installation or configuration problem: C compiler cannot create executables.
so I've tried to compile without this LDFLAGS and with the "--without-iconv" configure's argument and it compiles now fine.
So it's a problem with the iconv library on HP-UX. Do you know if this library works on this system or if I should install libiconv ?
Thanks
@++
JC
Same as bug #35288 | https://bugs.php.net/bug.php?id=35554 | CC-MAIN-2015-32 | refinedweb | 277 | 50.23 |
Image from stm32duino.com
When I was first learning programming in the 90’s, embedded systems were completely out of reach. I couldn’t afford the commercial development boards and toolchains that I’d need to even get started, and I’d need a lot of proprietary knowledge just to get started. I was excited a few years ago when the Arduino environment first appeared, since it removed a lot of the barriers to the general public. I still didn’t dive in though, because I couldn’t see an easy way to port the kind of algorithms I was interested in to eight-bit hardware, and even the coding environment wasn’t a good fit for my C++ background.
That’s why I’ve been fascinated by the rise of the ARM M-series chips. They’re cheap, going for as little as $2 for a “blue pill” M3 board on ebay, they can run with very low power usage which can be less than a milliwatt (offering the chance to run on batteries for months or years), and they have the full 32-bit ARM instruction I’m familiar with. This makes them tempting as a platform to prototype the kind of smart sensors I believe the combination of deep learning eating software and cheap, low-power compute power is going to enable.
I was still daunted by the idea of developing for them though. Raspberry Pi’s are very approachable because you can use a very familiar Linux environment to program them, but there wasn’t anything as obvious for me to use in the M-series world. Happily I was able to get advice from some experts at ARM, who helped steer me as a newbie through this unfamiliar world. I was very pleasantly surprised by the maturity and ease of use of the development ecosystem, so I want to share what I learned for anyone else who’s interested.
The first tip they had was to check out STMicroelectronics “Discovery” boards. These are small circuit boards with an M-series CPU and often a lot of peripherals built in to make experimentation easy. I started with the 32F746G which included a touch screen, audio input and output, microphones, and even ethernet, and cost about $70. There are cheaper versions available too, but I wanted something easy to demo with. I also chose the M7 chip because it has support for floating point calculations, even though I don’t expect I’ll need that long term it’s helpful when porting and prototyping to have it.
The unboxing experience was great, I just plugged the board into a USB socket on my MacBook Pro and it powered itself up into some demonstration programs. It showed up on my MacOS file system as a removable drive, and the usefulness of that quickly became clear when I went to the mbed online IDE. This is one of the neatest developer environments I’ve run across, it runs completely in the browser and makes it easy to clone and modify examples. You can pick your device, grab a project, press the compile button and in a few seconds you’ll have a “.bin” file downloaded. Just drag and drop that from your downloads folder into the USB device in the Finder and the board will reboot and run the program you’ve just built.
I liked this approach a lot as a way to get started, but I wasn’t sure how to integrate larger projects into the IDE. I thought I’d have to do some kind of online import, and then keep copies of my web code in sync with more traditional github and file system versions. When I was checking out the awesome keyword spotting code from ARM research I saw they were using a tool called “mbed-cli“, which sounded a lot easier to integrate into my workflow. When I’m doing a lot of cross platform work, I usually find it easier to use Emacs as my editor, and a custom IDE can actually get in the way. As it turns out, mbed-cli offers a command line experience while still keeping a lot of the usability advantages I’d discovered in the web IDE. Adding libraries and aiming at devices is easy, but it integrates smoothly with my local file system and github. Here’s what I did to get started with it:
- I used
pip install mbed-clion my MacOS machine to add the Python tools to my system.
- I ran
mbed new mbed-hello-worldto create a new project folder, which the mbed tools populated with all the baseline files I needed, and then I cd-ed into it with
cd mbed-hello-world
- I decided to use gcc for consistency with other platforms, so I downloaded the GCC v7 toolchain from ARM, and set a global variable to point to it by running
mbed config -G GCC_ARM_PATH "/Users/petewarden/projects/arm-compilers/gcc-arm-none-eabi-7-2017-q4-major/bin"
- I then added a ‘main.cpp’ file to my empty project, by writing out this code:
#include <mbed.h> Serial pc(USBTX, USBRX); int main(int argc, char** argv) { pc.printf("Hello world!\r\n"); return 0; }
The main thing to notice here is that we don’t have a natural place to view stdout results from a normal printf on an embedded system, so what I’m doing here is creating an object that can send text over a USB port using an API exported from the main mbed framework, and then doing a printf call on that object. In a later step we’ll set up something on the laptop side to display that. You can see the full mbed documentation on using printf for debugging here.
- I did
git add main.cppand
git commit -a "Added main.cpp"to make sure the file was part of the project.
- I created a new terminal window to look at the output of the printf after it’s been sent over the USB connection. How to view this varies for different platforms, but for MacOS you need to enter the command
screen /dev/tty.usbm, and press Tab to autocomplete the correct device name. After that, the terminal may contain some random text, but after you’ve successfully compiled and run the program you should see “Hello World!” output. One quirk I noticed was that
\non its own was not enough to cause the normal behavior I expected from a new line, in that it just moved down one line but the next output started at the same horizontal position. That’s why I added a
\rcarriage return character in the example above.
- I ran
mbed compile -m auto -t GCC_ARM -fto build and flash the resulting ‘.bin’ file onto the Discovery board I had plugged in to the USB port. The
-m autopart made the compile process auto-discover what device it should be targeting, based on what was plugged in, and
-ftriggered the transfer of the program after a successful build.
- If it built and ran correctly, you should see “Hello World!” in the terminal window where you’re running your screen command.
I’ve added my version of this project on Github as github.com/petewarden/mbed-hello-world, in case you want to compare with what you get following these steps. I found the README for the mbed-cli project extremely clear though, and it’s what most of this post is based on.
My end goal is to set up a simple way to compile a code base that’s shared with other platforms for M-series devices. I’m not quite certain how to do that (for example integrating with a makefile, or otherwise syncing a list of files between an mbed project and other build systems), but so far mbed has been such a pleasant experience I’m hopeful I’ll be able to figure that out soon! | https://petewarden.com/2018/01/ | CC-MAIN-2019-51 | refinedweb | 1,336 | 65.35 |
Continuations for Curmudgeons
This essay is for people who, in web years, are older than dirt. More specifically, if there was a period of time in which you programmed in a language which did not have garbage collection, then I mean you. For most people these days, that means that you had some experience with a language named C.
It is a pretty safe bet that — despite your deep technical background — you find that you have some genetic defect that makes it completely impossible for you to understand articles with titles like Continuations Made Simple and Illustrated. And for some reason, that bothers you.
If so, then maybe this article is for you. Think of yourself as a frog. Prepare to be boiled.
Local Variables
Let me start with something far, far, away from continuations. Something that you should be comfortable with. It should bring back memories of battles you heroically fought, and mostly won, long ago. This example is in C:
#include <stdio.h> int* f(int n) { int result = n + 1; return &result; } main() { int *n1 = f(1); int *n2 = f(2); printf("%d\n", *n1); }
OK, now let’s walk through this program. First a
function named
f is defined. It takes in one
argument, an integer named
n. It adds one to
that value, and stores the result in a local variable named
result. Finally,
f returns the
address of
result.
At this point, any self respecting compiler should issue a warning. In fact, gcc does exactly that:
test.c: In function 'f': test.c:5: warning: function returns address of local variable
The problem is that local variables are stored on the
stack. And when
f returns, it pops the stack,
making this memory available for other uses.
In this program,
main calls
f
twice. Once with a value of
1 and once with a
value of
2. Quite likely, the second call will
use the exact same storage layout as the first call, meaning that
the first
result will be overlaid.
In fact, on my machine, this is exactly what happens. When I compile and run this example, I get the following result:
3
If you now look around, you will notice that all the tadpoles that never really programmed in C have jumped out of the pond.
ByValue vs ByReference
The above example could be fixed by using
malloc. Of course, this would introduce a leak,
so calls to
free would also have to be added.
Aren’t you glad that you are now programming in a language
with garbage collection?
Even so, there still are quirks that will snare the unsuspecting programmer. For this pair of examples, I will use JavaScript. If you like, you can run these in your favorite web browser.
<script> var v = 5; function f() { v = v + 1; return v; } var x = f(); x = x - 2; document.write(f()); </script>
In this script,
v starts out at 5. Function
f is called, and
v gets incremented, and
the result gets returned and stored in a variable named x.
That variable is then decremented by two. Then
f
is called again,
v get incremented again, and the
result is printed.
When I run this I get
7
Now, lets change this example slightly.
<script> var v = [5]; function f() { v[0] = v[0] + 1; return v; } var x = f(); x[0] = x[0] - 2; document.write(f()[0]); </script>
The only difference between this script and the first script is
that
v is an array of length one. However, this
difference is significant, because arrays are allocated on the
heap, so
v is really just a reference to the
array. And after the first call,
x is a
reference to the same array, so when the value at index
0 is decremented by two, this affects the value
referenced by
v.
Sure enough, when I run the new script, I get
5
Inconsistent? Yes. Strange? Yes. But generally, this doesn’t cause too much problems. In any case, you avoid SEGVs as things allocated on the heap never go out of scope. They simply become eligible to be reclaimed when there is nothing left which references them.
If you are still with me, you don’t realize it yet, but you are about to become dinner.
Frames
Let’s recap.
While a stack can be seen as a consecutive sequence of bytes, in most languages there are either conventions (which are not enforced) or policies (which are) which prevent a function from “popping” off more data than they pushed onto the stack. In other words, each active scope (e.g., a function) is separated from one another much in the same way as the little bars that you put in between groceries on the conveyor belt in line separate each person’s purchases.
A procedure call pushes the return address (the address of the instruction after the call instruction) onto the stack, along with any arguments, and creates a new frame. A return statement uses this information to set the Instruction Pointer and Stack Pointer back to what it was as the point of call.
Within the procedure, arguments and local variables may be located based on their offset from the start of the stack segment.
Hashes
Everything so far has been very traditional computer science. Now, let’s start to diverge from that a bit. Instead of viewing a stack as a contiguous sequence of bytes, let’s view a stack as a linked list of frames. And instead of viewing a frame as a contiguous sequence of bytes, let’s substitute a dictionary or hashtable.
Now instead of knowing that this data resides at a predetermined
offset in the frame, you would look up
x simply by
looking up “
x” in the frame’s hash
table.
In case you didn’t notice, this organization of frames is more oriented towards dynamic languages.
callcc
Now, let’s revisit the notion of a procedure call with
this organization of frames. A procedure call creates a new
frame, and stores the current context (consisting of both the
instruction pointer and the stack pointer) in the new frame.
The syntax for creating a new frame and storing the current context
into a global variable named
$cc in Ruby is:
callcc{|$cc|}
The syntax for returning to this exact point, restoring both the instruction pointer and stack pointer, is:
$cc.call
This is naturally called a continuation, as you are continuing where you left off.
At this point, you are probably feeling a little bit disoriented. But go back and reread the above few paragraphs and examples. Other than the last examples being in a foreign language, all the words make sense. You are probably wondering “is that all there is?” and “what’s the big deal?”. If so, the answers are “pretty much yes”, and “read on”.
One thing to note here is that as long as
$cc
retains its current value, the stack frame it refers to can not be
reclaimed by garbage collection. Frames themselves are not
automatically freed upon encountering
return
statements; instead they are subject to garbage collection.
Simply by “continuing” at a prior point in the
execution, and creating a new continuation, call
“stacks” become arbitrary trees.
Generators
At this point, discussions generally veer off into either contrived or complicated examples. Let’s instead take a simple example where the machinery for continuations is not quite so raw and exposed: Python generators. Here is an example that prints Fibonacci numbers less than 1000:
def fib(): yield 0 i,j = 0,1 while True: yield j i,j = j,i+j for n in fib(): if n>1000: break print n
Instead of
return statements, the fib function uses
yield statements. This yields one
number at a time out of the inexhaustible supply of Fibonacci
numbers. The caller simply invokes that continuation as many
times as desired, and all program state (instruction pointer, local
variables) are restored, and the
fib function starts
back up where it left off.
Once the loop is exited, the state if the
fib
function is eligible for reclaiming.
Cool, eh?
If you try to recode this without continuations, you will find that you will need to return a “token” which contains all the relevant state, and that token will need to be passed back in on subsequent calls. That’s pretty much what is happening under the covers. (Note: you may be tempted to use global variables instead. Don’t. Your code would no longer be reentrant, and if there were two callers, they would get confused).
Cocoon
Now let’s look at a
web application, this time in JavaScript. A single
function implements the entire form based application
that involves the display of three (or four, depending on the
options selected) web pages. This is accomplished via the
cocoon.sendPageAndWait primitive.
This style of programming is quite different than the resource oriented approach advocated by REST. Some, however, find it to be more intuitive.
This hearkens back to the days in Basic when you coded things like
10 print "Enter your name" 20 input a$ 30 print "Hello, "; a$; "!"
When the computer got to the
input statement, the
operating system would suspend your program until the user provided
an input. At which point, your program would be paged back
into memory and would pick up exactly where it left off.
SAX
A SAX parser is an
example of a task that could be recast as a generator. It
consumes an
InputSource byte by byte and occasionally
emits
startElement,
endElement,
characters and other events. After each event,
the parser picks back up where it left off.
While this organization is convenient for parser writers, many consumers find XML Pull Parsers easier to deal with.
Judicious application of continuations allows both constituencies to be satisfied. From the user of the library’s perspective, they are using a pull parser. From the person who codes up the SAX handler, each event simply invokes a continuation. There is no memory bloat like you see with DOM style parsers. Everybody is happy.
UI
Event programming, in general, is for wizards. These wizards live and breathe events. But even they regress every once and a while. You can tell when this happens when you see a modal dialog box.
With User Interface Continuations, even scripters can become £337 h4x0r UI gods. Without a modal dialog box in sight.
Closures
Consider the following JavaScript:
var msg = "Hello, world!"; setTimeout(function(){alert(msg)}, 1000);
The use of
setTimeout is common in JavaScript based
animation. The first parameter is a function to be
invoked. The second parameter is the number of
miliseconds to wait until this string is executed.
The question you should be asking yourself is “in which
context is this function to be evaluated?” In particular,
how does JavaScript go about looking for the value of
msg?
The answer is simple: in the current context. This, it turns out, is a closure, continuation’s more general cousin. Wrapped up in a nice neat little package.
Continuations are bookmarks — they tell you where to pick up after you last left off. Closures are simply the current lexical stack — they represent the current local context and its immediate parent, recursively.
Classes
If the notion of a nested set of scopes residing on the heap seems foreign to you, it really shouldn’t. Here’s an example in Java:
public class Scopes { class Outer { class Inner { void alert() {System.out.println(msg);} } String msg = "Schweet!"; Inner inner = new Inner(); } Outer outer = new Outer(); public static void main(String[] args) { String msg = "Bogus!"; (new Scopes()).outer.inner.alert(); } }
Epilogue
One thing that people don’t often tell you about continuations is that they don’t actually resume exactly where you left off. After all, if they did, you would end up in an infinite loop. The only thing that is really restored is a few pointers. Everything that resides on the heap, or is stored externally in places like files and databases, remains unaffected when you invoke a continuation. But like the ByValue or ByReference discussion above, this doesn’t cause problems very often. In fact, it generally works out pretty much the way you would like it to, without you having to worry about it.
When you realize this, you realize that there really is no magic in continuations. Sure, more things are put on the heap, but there are ways to optimize this.
Oh, and by the way, you probably taste like chicken right about now. | http://www.intertwingly.net/blog/2005/04/13/Continuations-for-Curmudgeons | crawl-002 | refinedweb | 2,096 | 64.2 |
Recent:
Archives:
waitand
notifymethods of the Object class. In "Using threads in Java, Part II" I took the synchronized threads and created an in-memory communication channel so that two or more threads could exchange object references. Then in "Using communication channels in applets, Part 3" I applied these communication channels to co-operating applets that were laid out in an HTML page by a Java-aware browser. These applets combined to create an active HTML page that implemented a simple temperature conversion applet.
In this last column on threads and interapplet communication I'll look at a couple issues associated with this approach, and in particular I'll discuss how a layer can be created on top of the existing DataChannel design to allow multiple DataChannels to feed into a single DataChannel. The source code is also online and available for your use, in either an elaborate form, or as a tar or zip archive.
Next month I'll pick on another oft-misunderstood aspect of the Java system, class loaders.
We implement this easily with a DataChannel.
The skeleton of the OptionButton control is as follows:
1 public class OptionButton extends Applet implements Runnable { 2 public void init() { 3 new DataChannel(getparameter("datachannel"); 4 state = false; 5 } 6 public void paint(Graphics g) { 7 ... display my label and my choice ring ... 8 } 9 public void start() { ... create the data channel ... } 10 public void stop() { ... release the data channel ... } 11 public void run() { 12 while (thread == currentthread) { 13 value = getValue(); 14 current_state = value == myValue; 15 repaint(); 16 } 17 } 18 public boolean mouseUp(...) { sendValue(myID); } 19 }
As you can read in the code, the applet is quite simple. The magic is taken care of by the DataChannel. The basic applet knows only two things -- how to render itself in the checked and unchecked state -- and when it gets clicked it sends its value out to its DataChannel, which is the same channel that it is monitoring. When an option button receives a value from its DataChannel, if the value is equivalent to its own value, it sets its checked state to true and repaints itself.
Can you see how it would be modified to be a non-exclusive choice control? Certainly the boundary condition of an OptionButton with no one else in the group would get halfway there. But recall that the way the button gets unset is that some other choice is set. Obviously the mouseUp method would have to implement a toggle rather than a single set semantic. I'll leave it as an exercise for you to create this class (although there is a version in the sources), and when your write it, change the box shape from round to square. This will give users the idea that this is not a single-choice option. | http://www.javaworld.com/javaworld/jw-07-1996/jw-07-mcmanis.html | crawl-002 | refinedweb | 468 | 61.46 |
Search Discussions
- Some surprisingly wrong results (php 5.2.0): date and time seem not coherent: <?php // Date: Default timezone Europe/Berlin (which is CET) // date.timezone no value $basedate = strtotime("31 Dec 2007 ...
- Simple function that converts more than one <br ,<br/ ,<br / ... to a <p </p . Maybe it's useful for someone =) function br2p($string) { return preg_replace('#<p [\n\r\s]*?</p #m', '', '<p ...
- <?php function array_unique_FULL($array){ foreach($array as $k = $v){ if(is_array($v)){ $ret=F::array_unique_FULL(array_merge($ret,$v)); }else{ $ret[$k]=$v; } }//for return array_unique($ret); } ? ...
- Sometimes it is helpful to check for the existance of a file which might be found by using the include_path like in include("file_from_include_path.php"); A simple function iterates the include_path ...
- Updating internal's PHP timezone database (5.1.x and 5.2.x) ---- Server IP: 69.147.83.197 Probable Submitter: 200.234.208.27 ---- Manual Page -- ...
- This function could be useful to somebody if you want to insert an XML into another when building an XML from many different files. Note that you must specify a name for the node in which the child ...
- This is the fonction for PHP4 : function array_combine($arr1,$arr2) { $out = array(); foreach($arr1 as $key1 = $value1) { $out[$value1] = $arr2[$key1]; } return $out } ---- Server IP: 194.246.101.61 ...
- Check for duplicates in an array (as opposed to removing them): if (array_unique($array) != $array) { echo "Duplicate located in array."; } ---- Server IP: 69.147.83.197 Probable Submitter: ...
- Regarding cyberchrist at futura dot net's function. It makes an unnecessary array_merge(); the elements of $b that are merged with those of $a are immediately removed again by the array_diff(). The ...
- I've been working on a project for a while now, and for example in my DB handler I wanted to load var's to the objects late; However, without doing it manually on the object itself but through a ...
- A simple funtion to format american dollars. <? function formatMoney($money) { if($money<1) { $money='¢'.$money*100; } else { $dollars=intval($money); $cents=$money-$dollars; $cents=$cents*100; ...
- If you intend to pass a copy of an object to a function, then you should use 'clone' to create a copy explicity. In PHP5, objects appear to always be passed by reference (unlike PHP4), but this is ...
- I was wondering what was quicker: - return a boolean as soon I know it's value ('direct') or - save the boolean in a variable and return it at the function's end. <?php $times = 50000; function ...
- Don't forget that using callbacks in a class requires that you reference the object name in the callback like so: <?php $newArray = array_filter($array, array($this,"callback_function")); ? Where ...
- <?php $tmp_array = "123,232,141"; if (strval(intval($tmp_array)) == $tmp_array) { echo "'".intval($tmp_array)."' equals '$tmp_array'\n"; } else { echo "'".intval($tmp_array)."' does not equal ...
- the function posted is false, hier the correction: function rstrpos ($haystack, $needle, $offset) { $size = strlen ($haystack); $pos = strpos (strrev($haystack), strrev($needle), $size - $offset); if ...
- It should be noted that version_compare() considers 1 < 1.0 < 1.0.0 etc. I'm guessing this is due to the left-to-right nature of the algorithm. ---- Server IP: 212.63.193.10 Probable Submitter: ...
- You should probably try to avoid changing any of the items in the args array. Consider this example: ---------- function a(&$value) { echo "start a: $value\n"; b(); echo "end a: $value\n"; } function ...
- filesize() acts differently between platforms and distributions. I tried manually compiling PHP on a 32bit platform. Filesize() would fail on files 2G. Then I compiled again, adding CFLAGS=`getconf ...
- $test = true and false; --- $test === true $test = (true and false); --- $test === false $test = true && false; --- $test === false ---- Server IP: 195.46.80.5 Probable Submitter: 158.195.96.161 ---- ...
- Other languages (in my case Java) allow access to multiple values for the same GET/POST parameter without the use of the brace ([]) notation. I wanted to use this function because it was faster than ...
- Below is the function for making an English-style list from an array, seems to be simpler than some of the other examples I've seen. <?php function ImplodeProper($arr, $lastConnector = 'and') { if( ...
- This code implodes same as the PHP built in except it allows you to do multi dimension arrays ( similar to a function below but works dynamic :p. <?php function implode_md($glue, $array, ...
- To go further with Fabian's comment: The XML specification (production 66) says that (decimal) numeric character references start with '&#', followed by one or more digits [0-9], and end with a ';' - ...
- Fabian's observation that chr(039) returns "a heart character" is explained by the fact that numeric literals that start with '0' are interpreted in base 8, which doesn't have a digit '9'. So 039==3 ...
- Bafflingly, html_entity_decode() only converts the 100 most common named entities, whereas the HTML 4.01 Recommendation lists over 250. This wrapper function converts all known named entities to ...
- Whilst implementing my RSS_FEED reader, I stumbled upon a slight issue, typically on RSS feeds such as the NY Times ones : quotes and apostrophes were replaced by question tags. For example : "the ...
- If you have a class which defines a constant which may be overridden in child definitions, here are two methods how the parent can access that constant: class Weather { const danger = 'parent'; ...
- A further implementation of the great rstrpos function posted in this page. Missing some parameters controls, but the core seems correct. <?php // Parameters: // // haystack : target string // needle ...
- @egingell at sisna dot com - Use of __call makes "overloading" possible also, although somewhat clunky... i.e. <?php class overloadExample { function __call($fName, $fArgs) { if ($fName == 'sum') { ...
- @ zachary dot craig at goebelmediagroup dot com I do something like that, too. My way might be even more clunky. <?php function sum() { $args = func_get_args(); if (!count($args)) { echo 'You have to ...
- Re: Renumbering arrays: This (from rcarvalhoREMOVECAPS at clix dot pt): $a = array_merge($a, null); does not renumber the array in PHP5. However this: $a = array_merge($a, array()); does renumber the ...
- Re: public at kreinacke dot com It has long been a point of frustration to me that md5() functions don't produce the same results as the *nix md5sum program. Reading your comments about the ...
- Using the Unix 'file' program with the -i switch will not work reliably. Consider the following plain-text CSV file (we'll call it 'error.csv'), which has the contents: ...
- There are a couple of things you can do for cleaner code if you want the keys returned from the array. I am not sure how they each impact performance, but the visual readability is more beneficial ...
- How about something like this: function goodFloor($x) { return floor(round($x, strlen((string)($x)))); } It's not elegant but at least short... Regards, Wojciech ---- Server IP: 195.136.184.34 ...
- Smaller version for PHP5 <?php # array array_unique_save (array array [, bool preserve_keys] ) function array_unique_save ($a, $pk = true) { $a = array_diff_key($a, array_unique($a)); return ($pk ? ...
- To svenxy AT nospam gmx net AND rob at digital-crocus dot com <?php $zones = array('192.168.11', '192.169.12', '192.168.13', '192.167.14', '192.168.15', '122.168.16', '192.168.17' ); natsort($zones); ...
- After much messing around to get php to store session in a database and reading all these notes, I come up with this revised code based on 'stalker at ruun dot de' class. I wanted to use PEAR::MDB2. ...
- In the below example posted by "shaun at shaunfreeman dot co dot uk". You shouldn't call gc() within the close() method. This would undermine PHP's ability to call gc() based on ...
- The following works for connecting via POP3 to a gmail server: imap_open("{pop.gmail.com:995/pop3/ssl/novalidate-cert}INBOX", $username, $pasword); ---- Server IP: 209.41.74.194 Probable Submitter: ...
- Here the workaround to the bug of strtotime() found in my previous comment on finding the exact date and time of "3 months ago of last second of this year", using mktime() properties on dates instead ...
- Here are my functions to do a 128 bit aes encryption which is transmitted to the dachser parcel tracking system via url. They expect a true aes 128 bit encryption an process the reqest by a java ...
- ...
- In case of an empty identifier the function returns a warning, not the boolean 'false'. "Warning: timezone_open() [function.timezone-open]: Unknown or bad timezone () " ---- Server IP: 217.160.72.57 ...
- JOECOLE, isn't this the same thing? $str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8"); ---- Server IP: 69.147.83.197 Probable Submitter: 216.145.54.7 ---- Manual Page -- ...
- is also quite good. Np lib install is required -Shelon Padmore ---- Server IP: 69.147.83.197 Probable Submitter: 190.6.231.26 ---- Manual Page -- ...
- Interop Between PHP and Java URLs has changed to: (Part 4) it is linked to Part 1, 2 and 3. ---- Server IP: 69.147.83.197 Probable Submitter: 202.156.12.10 (proxied: ...
- I enhance xml2array (can't remember who author) to work with duplicate key index by change "tagData" function with this - <? function tagData($parser, $tagData) { // set the latest open tag equal to ...
- To add to Stephen's note about logging, I found that if I defined the error_log path to be the Apache error log folder (ie: /var/log/httpd/php_error_log), it would still log to Apache's log, not the ...) | https://grokbase.com/g/php/php-notes/2007/10 | CC-MAIN-2019-26 | refinedweb | 1,555 | 68.16 |
RB_SET_TKT_STRING(3) KRB_SET_TKT_STRING(3)
NAME
krb_set_tkt_string - set Kerberos ticket cache file name
SYNOPSIS
#include <kerberosIV/krb.h>
void krb_set_tkt_string(filename)
char *filename;
DESCRIPTION
krb_set_tkt_string sets the name of the file that holds
the user's cache of Kerberos server tickets and associated
session keys.
The string filename passed in is copied into local stor-
age. Only MAXPATHLEN-1 (see <sys/param.h>) characters of
the filename are copied in for use as the cache file name.
This routine should be called during initialization,
before other Kerberos routines are called; otherwise the
routines which fetch the ticket cache file name may be
called and return an undesired ticket file name until this
routine is called.
FILES
/tmp/tkt[uid] default ticket file name, unless the
environment variable KRBTKFILE is set.
[uid] denotes the user's uid, in deci-
mal.
SEE ALSO
kerberos(3), setenv(3)
MIT Project Athena Kerberos Version 4.0 1 | http://www.rocketaware.com/man/man3/krb_set_tkt_string.3.htm | crawl-002 | refinedweb | 152 | 56.05 |
Yesterday, one of the JAXB users sent me an e-mail, asking for how to solve the problem he faced.
The scenario was like this; you have a client and a server, and you want a client to send an XML document to a server (through a good ol' TCP socket), then a server sends back an XML document. A very simple use case that should just work.
The problem he had is that unless the client sends the "EOS" (end of stream) signal to the server, the server keeps blocked. When he modified his code to send EOS by partial-closing the TCP socket (Socket.shutdownOutput), the server somehow won't be able to send back the response saying the socket is closed.
What's Happening?
So, what's happening and who's fault is this?
When you tell JAXB to unmarshal from InputStream, it uses JAXP behind the scene, in particular SAX, for parsing the document. Normally in Java, the code who opened the stream is responsible for closing it, but SAX says a parser is responsible for closing a stream.
Call it a bug or a feature, but this is done for a reason. People often assume that a parser only reads a stream until it hits the end tag for the root element, but the XML spec actually requires a parser to read the stream until it hits EOS. This is because a parser needs to report an error if anything other than comment, PI, or whitespace shows up. Given that, I'd imagine SAX developers thought "well, if a parser needs to read until EOS, why not have a parser close it? after all, the only thing you can do with a fully read stream is to close it!" In a sense, it makes sense. In any case, it's too late to change now.
So, the net effect is that when you pass in anInputStream from Socket.getInputStream to a JAXB unmarshaller, the underlying SAX parser will call theInputStream.close automatically.
Now, what happens when a socket InputStream is closed? The JDK javadoc really doesn't seem to say definitively, but a little exeriment reveals that it actually fully closes the TCP session. That explains why our guy couldn't write back the response --- by the time he read an input, his socket was already closed!
This seems like a surprising behavior. It would have been better if closing a stream only closes a socket partially in that direction, and you would need to close both InputStreamand OutputStream to fully shutdown a socket. It would have made a lot of sense. I guess the reason why it's not done this way is because of the backward compatibility. The Socket class was there since the very first JDK 1.0, but the notion of partial close is only added in JDK 1.3. JDK 1.3 of course couldn't change the behavior of earlier JDKs, no matter how undesirable it is.
By putting those two behaviors, we now know what has happened. At server, a SAX parser who was reading a request is terminating a connection too prematurely.
How To Fix This?
So how to fix this? To make it work, you don't let a parser to close the stream. You can do this by writing a simpleFilterInputStream that ignores the close method invocation:
public class NoCloseInputStream extends FilterInputStream { public NoCloseInputStream(InputStream in) { super(in); } public void close() {} // ignore close }
Then at server, you invoke JAXB like this:
unmarshaller.unmarshal(new NoCloseInputStream(socket.getInputStream());
You can then do some processing, followed by a marshal method invocation like this:
marshaller.marshal( object, socket.getOutputStream() );
Finally you close the socket and you are done. On the client side, you'll do:
marshaller.marshal( object, socket.getOutputStream() ); socket.shutdownOutput(); // send EOS Object response = unmarshal.unmarshal( socket.getInputStream() );
This time you do want to close the socket after the response is read, so you don't need to use NoCloesInputSTream.
Hird, I'm sorry Java let you down on this one, but hopefully this explains what's going on and why. | https://community.oracle.com/blogs/kohsuke/2005/07/15/socket-xml-pitfall | CC-MAIN-2017-13 | refinedweb | 685 | 64.2 |
Bubble Sort in Python
linxea
・1 min read
Become a Software Engineer -> Pass Technical Interview -> Be darn good at Data Structure and Algorithms -> Starting with Sorting Algorithms -> 1. Bubble Sort
Bubble Sort (Decreasing Order)
def bubblesort(array): # we minus 1 because we are always comparing the current value with the next value lengthOfArray = len(array) - 1 # numbe of rounds will be the total length - 1, for array with length 5, we will do 4 rounds: 0 and 1, 1 and 2, 2 and 3, 3 and 4. for i in range(lengthOfArray): # at each round, we compare the current j with the next value for j in range(lengthOfArray - i): # only swap their positions if left value < right value as we aim to move all the small values to the back if array[j] < array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] return array array = [2, 1, 5, 4, 3] print bubblesort(array)
Classic DEV Post from Nov 19 '18
The video is funny, good idea. Numbers are really boring.
aww thanks, took the chance to showcase my favourite people too :)
I want to see quick sort. When will you publish it?
Your wish is my command. Coming up soon :)
Thanks for caring, expecting..., :) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/linxea/bubble-sort-in-python-2mog | CC-MAIN-2019-35 | refinedweb | 209 | 63.22 |
Scroll down to the script below, click on any sentence (including terminal blocks!) to jump to that spot in the video!
If you liked what you've learned so far, dive in!
video, code and script downloads.
Let's close all our tabs and open up
Container. In the last course, we created
two different ways to load
Ship objects: one that reads a JSON file -
JsonFileShipStorage
and another that reads from a database -
PdoShipStorage:
And you could switch back and forth between these without breaking anything, thanks
to our cool
ShipStorageInterface. Change it to use the PDO version and refresh.
Woh, new error:
Class
Service\PDOnot found in
Container.phpon line 28.
Let's check that out:
Here, we see the exact same error as before: "Undefined Class
PDO". So far, the
answer to this has always been:
Oh, I must have forgotten a
usestatement. I referenced a class, so I probably need to add a
usestatement for it.
But here's the kicker:
PDO is a core PHP class that happens to not live in
a namespace. In other words, it's like a file that lives at the root of you file
system: not in any directory.
So when PHP sees
PDO mentioned, it looks at the top of the class for a
use statement
that ends in PDO, it doesn't find one, and it assumes that
PDO lives in the
Service
namespace. But in fact,
PDO lives at the root namespace.
The fix is easy: add a
\ at the front of
PDO:
This makes sense: if you think of namespaces like a directory structure, This is like
saying
ls /PDO . It doesn't matter what directory, or namespace, we're in, adding
the
\ tells PHP that this class lives at the root namespace. Update the other places
where we reference this class.
This is true for all core PHP classes: none of them live in namespaces. So, always
include that beginning
\. Now, technically, if you were inside of a file that did
not have a
namespace - like
index.php - then you don't need the opening
\.
But it's always safe to say
new \PDO: it'll work in all files, regardless
of whether or not they have a namespace.
If you refresh now, you'll see another error that's caused by this same problem. But this one is less clear:
Argument 1 passed to
PDOShipStorage::__construct()must be an instance of
Service\PDO, instance of
PDOgiven.
This should jump out at you: "Instance of
Service\PDO". PHP thinks that argument
1 to
PDOShipStorage should be this, nonsense class. There is no class
Service\PDO!
PDOShipStorage: the
__construct() argument is type-hinted with
PDO:
But of course, this looks like
Service\PDO to PHP, and that causes problems.
Add the
\ there as well:
Phew! We spent time on these because these are the mistakes and errors that we all
make when starting with namespaces. They're annoying, unless you can debug them quickly.
If you're ever not sure about a "Class Not Found" error, the problem is almost always
a missing
use statement.
Update the other spots that reference
PDO:
Finally, refresh! Life is good. You just saw the ugliest parts of namespaces. | https://symfonycasts.com/screencast/oo-ep4/namespaces-core-php-classes | CC-MAIN-2020-29 | refinedweb | 540 | 74.29 |
The fundamental unit of Hotwire is the concept of an object-oriented pipeline. A pipeline is composed of a chain of Hotwire Builtins, which are Python classes with a specific API.
A Hotwire Builtin in general takes as input a stream of objects, a set of arguments and options, and yields another object stream. All of this is optional though; for example some builtins such as rm (RmBuiltin), only operate on their argument list, and don't input or output anything. Others don't take any arguments.
Let's start with a simple example, in the HotwirePipe language:
proc | filter -i walters owner_name
This example finds all processes on the system whose owner_name property matches the regular expression "walters". Note that unlike a traditional text-line based Unix /bin/sh pipeline, this will not be misled by other extraneous text which happens to match the input (no grep -v grep).
proc references the ProcBuiltin class, which is outputting a stream of Process objects. filter references the FilterBuiltin class, which can take any input type, and will output the same type. The walters and owner_name are string arguments for FilterBuiltin, and -i is processed as an option.
Don't be fooled by the similarity to Unix shell syntax - in this example everything is in the Hotwire process; there is no execution of external programs.
When you give this command to Hotwire, it looks up the names proc and filter in the registry, parses the options and argument list, and then executes it. Each component of a pipeline is executed in a new thread. These threads then simply call the execute method of each Builtin object, which takes a context, arguments, and options.
Because each builtin runs in its own thread, Hotwire internally uses threadsafe Queues to pipe objects from one thread to another.
But to make things more concrete, ignoring threading, the above pipeline is equivalent to this Python code:
import re
from hotwire.sysdep.proc import ProcessManager
prop_re = re.compile('walters')
for process in ProcessManager.getInstance().get_processes():
if prop_re.search(process.owner_name):
yield process
This may also be a bit clearer from looking at the proc source and the filter source.
Unfortunately, for Hotwire we had to implement the code to list processes on a system, and create the Process object. But if the Python distribution included this bit, the pipeline and builtins would just be a simpler syntax for accessing Python libraries.
This point is very important - the intent is that Hotwire builtins are mostly just trivial wrappers around actual APIs which are intended to be used from Python. They take arguments and options in a shell-like way tends to be more convenient.
So the current list of Hotwire builtins is all well and good; we can see files using LsBuiltin, processes using ProcBuiltin, do HTTP GETs using HttpGetBuiltin. But sadly, not every aspect of the operating system has a nice Python API. For example, there is no default Python API to query active network interfaces. Or to list hardware devices. Or to manipulate the X server resolution. And the list goes on.
You may recognize these commands on most Unix/Linux systems as ifconfig, lshal, and xrandr. Realistically, Hotwire can't immediately ship a version of every single one of these commands. We'd like to be able to continue using them.
Enter the SysBuiltin. The idea is pretty simple; it can execute external Unix/Linux binaries as subprocesses, returning their output conceptually as a stream of Unicode strings.
We now have a great deal of backwards compatibility with the existing operating system tools. For example, we can execute:
xrandr --auto
This works exactly like you might expect. The /usr/bin/xrandr program is executed with the argument --auto. In general, if a verb isn't recognized as the name of a builtin, we try to resolve it using the system binaries.
And because we have a model for how system commands fit into the Hotwire pipeline, we can pipe the stream of strings from a system command to Hotwire builtins:
ifconfig | filter -i link
Now, having a stream of objects isn't that interesting if we just display them in the way the default Python toplevel would; you'd see something like:
<Process object at 0x5295802>
<Process object at 0x1285429>
<Process object at 0x5988975>
etc. Layered on top of the Hotwire pipeline processing is an integrated graphical display and introspection system. There is a class called ObjectsRenderer which is an abstract API for displaying a stream of objects. The most important subclass is TreeObjectsRenderer which presents a treeview display of object properties.
Currently, there is a global object called ClassRendererMapping which maps from Python class -> Renderer. When we create a pipeline, we try to determine statically using the information from the builtins which renderer to pick. If this fails, we pick one based on the first object we see.
How do you set a proxy for the http-get builtin?
How do you set a proxy for the http-get builtin? | http://code.google.com/p/hotwire-shell/wiki/HotwireArchitecture | crawl-002 | refinedweb | 835 | 62.88 |
wcsrchr man page
Prolog
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
wcsrchr — wide-character string scanning operation
Synopsis
#include <wchar.h> wchar_t *wcsrchr(const wchar_t *ws, wchar_t wc);
Description
The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard..
Return Value
Upon successful completion, wcsrchr() shall return a pointer to the wide-character code or a null pointer if wc does not occur in the wide-character string.
Errors
No errors are defined.
The following sections are informative.
Examples
None.
Application Usage
None.
Rationale
None.
Future Directions
None.
See Also
wcschr() . | https://www.mankier.com/3p/wcsrchr | CC-MAIN-2017-17 | refinedweb | 153 | 51.65 |
and Development
of Trade Theory
W. W. Leontief was an economist who
won a Nobel Prize in Economics in
1973.
Wassily Wassilyovitch Leontief
(1905~1999).
Science or Pseudoscience
The significance of any theory consists in the fact that the
theory must be a faithful representation and a scientific
summation of the specific practices. In addition such scientific
theory could be used to effectively guide the actual
performances and development of the practices.
Otherwise, if the theory separates far away from the actual
practices, the so-called theory must be either one of the
following two cases:
(1) There is no necessity for the theory to continuously exist or
it would have been a pseudoscience;
(2) It must be necessary to revise or readjust the theoretical
assumptions on which the theory had been established so that
the theory could maintain its rational crux on the even more
scientific basis.
Development of Theory
To a an on the se oscience an the rocesses
of re-exa inin the theoretical ass tions
re resent evelo ent an refine ent of a
artic lar theory.
All of these sho l e one on the asis of
e irical test of the theory.
In other or s, there is no nee to have a
s erstitio s elief in the existin concl sions of
any theory.
On the contrary, in or er to have the theory
evelo e an refine , it is necessary to exec te
e irical test of it.
Empirical Test of Factor Endowment Theory
The rinci le of co arative a vanta es erive fro
classical Ricar ian o el erfor s as the theoretical
ase of factor en o ent theory intro ce y
Heckscher an Ohlin, the ain tren of international
tra e theory.
In other or s, since the co arative a vanta es, no
atter fro here they co e, f nction as the ost
i ortant theoretical re-req isites of international
tra e, econo ists have een intereste in the extent to
hich the eneral concl sions of Ricar ian o el an
H-O Mo el are realize in international tra e.
In artic lar, econo ists foc se on if a co ntrys tra e
reality consistent ith the asic rinci les of factor
en o ent theory.
The Stare Tongue-tied Discovery by Leontief
Thro ho t his life Leontief ca ai ne a ainst theoretical
ass tions an non-o serve facts (the title of a s eech
he elivere hile resi ent of the A erican Econo ic
Association, 1970-1971).
Accor in to Leontief too any econo ists ere rel ctant
to et their han s irty y orkin ith ra e irical
facts. To that en Wassily Leontief i ch to ake
q antitative ata ore accessi le, an ore in is ensa le,
to the st y of econo ics.
In a 1953 article y Leontief sho e , sin in t-o t t
analysis, that . . ex orts ere relatively la or-intensive
co are to . . i orts.
This as the o osite of hat econo ists ex ecte at the
ti e, iven the hi h level of . . a es an the relatively
hi h a o nt of ca ital er orker in the nite tates.
Leontiefs iscovery as ter e the Leontief Para ox.
Leontiefs First Test
One million dollars' worth of typical exportable and importable in 1947
(K/L)
x
= K
x
/ L
x
= $14,300
(K/L)
m
= K
m
/ L
m
= $18,200
The US is believed to be endowed with more capital per worker than any other
country in the world in 1947. Thus, the H-O theory predicts that the US exports
would have required more capital per worker than US imports. However, Leontief
was surprised to discover that US imports were 30% more capital-intensive than
US exports,
(K/L)
m
= 1.30 (K/L)
x
.
( ee: W. Leontief, Do estic Pro ction an Forei n Tra e: The A erican Ca ital
Position Re-exa ine , Proceedings of the American Philosophical Society 97, e te er
1953.)
Capital Requirement Labor Requirement
Exports K
x
= 2550780 L
x
=182.313 man-years
Imports K
m
= 3091339 L
m
=170.114 man-years
Leontiefs Second Test
One million dollars' worth of typical exportable and importable in 1951
Capital Requirement Labor Requirement
Exports
x
6 L
x
man-years
Imports
m
3 3 L
m
6 man-years
( /L)
x
x
/ L
x
$ ,9
( /L)
m
m
/ L
m
$ 3,
( /L)
m
. ( /L)
x
In 1956 Leontief repeated the test for US imports and exports which prevailed in
1951. In his second study, Leontief aggregated industries into 192 industries. He
found that US imports were still more capital-intensive than US exports. US
imports were 5.7% more capital-intensive. The degree had been reduced but the
paradoxical conclusion remained.
(See: W. Leontief, Factor Proportions and the Structure of American Trade: Further
theoretical and empirical analysis, Review of Economics and Statistics 38, no. 4 November
1956.)
Leontiefs Comments on His Discovery
Facing such a stare ton e-tie paradoxical
conclusion Leontief surprisingly pointed out:
These figures show that an average million
dollars worth of our exports embodies
considerably less capital and somewhat more
labor than would be required to replace from
domestic production an equivalent amount of our
competitive imports.
Americas participation in the international
division of labor is based on its specialization on
labor intensive, rather than capital intensive, lines
of production.
In other words, this country resorts to foreign
trade in order to economize its capital and dispose
of its surplus labor, rather than vice versa.
The widely held opinion thatas compared with
the rest of the worldthe United States economy
is characterized by a relative surplus of capital
and a relative shortage of labor proves to be
wrong. As a matter of fact, the opposite is true.
Who can tell me
who I am?
Baldwin Test (See: Robert E. Baldwin, Determinants of the Commodity
Structure of U.S. Trade, American Economic Review 61, no. 1 March
1971.)
One million dollars' worth of typical exportable and importable in 1962
(K/L)
x
= K
x
/ L
x
= $14,321
(K/L)
m
= K
m
/ L
m
= $17.916
(K/L)
m
= 1.251 (K/L)
x
Capital Requirement Labor Requirement
Exports K
x
= 187 000 L
x
=131 man-years
Imports K
m
= 2132000 L
m
=119 man-years
Professor Ro ert E. Bal in (1971) se the 1962 tra e statistics to al ost
entirely re eat hat Leontief i y sin the ata of 1947 an 1951. Bal in
fo n that ca ital/la or ratio for ex orts as a o t $14200 hereas
ca ital/la or ratio for i orts as a o t $18000. In other or takin
tra e in 1962 into consi eration i orts ere 26.8% ore ca ital-
intensive than ex orts hile ex orts ere 26.8% ore la or intensive
than i orts. Fifteen years ast t the ara ox contin e .
Other Empirical Tests after Leontief
Test of Tate oto an Ichi ra ( ee: M. Tate oto an .
Ichi ra, Factor Pro ortions an Forei n Tra e: The Case of
Ja an, Revie of Econo ics an tatistics, no 41 Nove er
1959)----Para ox Exists.
Test of tol er an Roska ( ee: Wolf an F. tol er an Karl
Roska , "In t-O t t Ta le for East Ger any, ith
A lications to Forei n Tra e." B lletin of the Oxfor Instit te
of tatistics, Nove er 1961.) ----No Para ox.
Test of Wahl ( ee: D. F. Wahl, "Ca ital an La or Req ire ents
for Cana a's Forei n Tra e," Cana ian Jo rnal of Econo ics
an Political cience, A st 1961.)---- Para ox Exists.
Test of Bhara aj ( ee: R. Bhara aj, Factor Pro ortions an
the tr ct re of In ia- . . Tra e, In ian Econo ic Jo rnal,
Octo er 1962.)---- Para ox Exists.
Effect of Different Labor Efficiency
Leontief hi self favore H-O theory. He trie to rovi e so e
ex lanation y stressin the ifferent efficiency in the an the
other co ntries.
He ar e that orkers i ht e ore efficient than forei n ones.
As Leontief s este that erha s . . orkers ere three ti es as
effective as forei n orkers.
He sai in his a er in any co ination ith the iven q antity of
ca ital, one an-year of A erican la or is eq ivalent to, say, three
an-years of forei n la or. It eans that the avera e A erican
orker is three ti es as effective as he o l e in the forei n
co ntry.
Given the sa e K/L ratio, Leontief attri te the s erior efficiency
of A erican la or to remarkable entrepreneurship
, s erior econo ic or anizationan
environ ent f ll of econo ic incentives
in the . .
Ho ever, Leontief fo n very fe follo ers a on econo ists. Even
Leontief hi self s itte that he ha a e a la si le alternative
ass tion
Factor Intensity Reversal
See: B. S. Minhas: The Homohypallagic Production Function, Factor-
Intensity Reversals and Heckscher-Ohlin Theorem
, Jo rnal of Political
Econo y 70, no.2, A ril 1962.
a
m
k
a
t
k
b
b
t
k
b
m
k
b
m
l
b
t
l
' a
a
t
l
a
m
l
If a co o ity is ro ce y a la or-intensive rocess in the
la or-rich co ntry an also y the ca ital-intensive rocess in
the ca ital-rich co ntry, then factor intensities are reverse in
the ro ction of that co o ity.
A ca ital a n ant Co ntry
A an a la or a n ant
Co ntry B ill res ectively
ake ro ction ecisions
follo in the la of
econo ic efficiency. B t
factor intensity reverses.
Act ally, these t o co ntries sel o tra e ith each other, instea , they oth
ex ort their co aratively a vanta eo s oo s to the thir co ntry.
Agriculture is labor-intensive in India but capital-intensive in the United States.
Since India is surely a labor abundant
country agricultural production in India
must be a typical labor-intensive
process. While because of very
relatively high wage rate and a
relatively low price of capital the United
States tends to substitute labor input
with a great deal of agricultural
machinery.
If the United States imports agricultural
products from abroad, then it looks like to
import some capital-intensive goods, a
Leontief paradox occurs in the US,
because a false appearance shows that a
capital abundant country is importing
capital-intensive products.
If the United States exports agricultural
products to India, that is true in the US-
Indian bilateral trade, then a Leontief
paradox occurs in India, because a widely
recognized labor-abundant country, India,
is importing some labor-intensive goods.
Natural Resources
See: Jaroslav Vanek, The Natural Resource Content of
the United States Foreign Trade 1870-1955,
Ca ri e, MA: MIT Press, 1963.
Jaroslav Vanek ar e that Leontief ay have
oversi lifie the ro ction f nctions an faile to
reco nize the en o ents of nat ral reso rces. With
three factors of ro ction, the ty ical H-O o el oes
not re ict ch. This is eca se the notion of
a n ance an intensity st e re efine .
Let N stan s for nat ral reso rces e co l have so e
N-a n ant an N-scarce co ntries. Also e co l have
N-intensity oo .
If an N-a n ant co ntry ex orts N-intensive oo
hile an N-scarce co ntry i orts N-intensive oo , no
Leontief Para ox.
Relations between natural resources and capital inputs
In the act al ro ction rocesses of nat ral reso rce-
intensive oo s there st e co le entary relations
et een nat ral reso rces in ts an ca ital in ts an in
the ost art of s ch ro ction rocesses ca ital an
nat ral reso rces cannot e s stit te for each other.
The so-calle N-intensive oo s are asically ro ce in
consi era ly ca ital-intensive etho s.
Ty ical nat ral reso rce intensive oo , etrole an oil
ro cts, in every sta e of the ro ction rocesses,
incl in ex loitation, extraction, refine ent, trans ortation,
as ell as an fact rin , storin ( s ally tankin ) an
carria e ( s ally i in ) of ifferent ty es of oil ro cts
( asoline, iesel, nat ral as, an so on) a lar e vol e of
ca ital in ter s of an array of s ecific achinery an
eq i ents st e se .
It is i ossi le for a co ntry ith an a n ant ca ital
en o ent, s ch as the nite States, to s stit te the
relatively ex ensive recio s nat ral reso rces ith the
relatively chea ca ital in ts.
US Trade Pattern Consistent with H-O Model
There are at least t o reasons for the S to i ort lar e
vol e of N-intensive oo s.
Econo ic consi eration. To i ort s ch oo s fro
a roa st e consi era ly chea er than to
o estically ro ce the .
Strate ic consi eration. To esta lish the national strate ic
reserve of so e i ortant nat ral reso rces is to the
national enefit of the nite States.
As an N-scarce co ntry the S nat rally i orts a reat
vol e of N-intensive oo s fro a roa . No ara ox
here.
Beca se of the s ecific relation et een nat ral
reso rces an ca ital in ts the S see s to i ort
ca ital-intensive oo s if e have no consi eration of
nat ral reso rces hen analyzin its tra e attern.
Leontief Para ox is nothin t a is n erstan in .
Human Capital
Nations an in ivi als invest in their f t re
not only y acc latin hysical ca ital, s ch
as lant il in s, eq i ents, an
inventories, t also y s en in on e cation,
trainin , an other invest ents that are
e o ie in h an for , that is, h an
ca ital.
H an ca ital invest ent acq ires an
a ro riate rate of ret rn in ter s of relatively
hi her a e rate.
The eneral level of a e rate is hi her in
those in stries in hich h an ca ital is
e loye in a relatively lar er ro ortion.
Eq ivalently, hi her a e rate of a artic lar
co ntry eans it st e en o e ith
relatively a n ant h an ca ital eca se of
the evelo e hi her learnin e cation an
the a vance social service syste .
See: Irving Kravis, Wages and Foreign Trade, Review of Economics and Statistics 38, February
1956 and Peter. B. Kenen, Nature, Capital and Trade, Journal of Political Economy 73, October
1965.
Old Campus of
Yale University
False Appearance Makes the Paradox
When e insert a ne factor of h an ca ital into the tra e o el, tra e
attern of the nite States st e co letely reexa ine .
At first, the S st e re ar e as to e a n ant in h an ca ital
en o ent. The relevant statistics s est that a ty ical S la orer has an
avera e ore years of e cation than a forei n orker. Th s the S
la orers earn a relatively hi her salary than their forei n co etitors.
Takin a vanta es of its a n ant h an ca ital the S ay have een
ex ortin h an ca ital-intensive oo s to the other co ntries. Such sorts
of the S tra e is consistent ith the asic re iction of the H-O theory no
ara ox at all.
nfortunately, the effect of human ca ital, enerally hi her a e rate ha
een falsely concluded as more la or in ut y Leontief. That false
a earance must e the reason for Leontief Paradox.
Peter Kenen in 1965 calculated the value of extra human ca ital and
reexamined trade attern of the S. He suggested that if the value of human
ca ital ere included, the S ex orts ere ca ital-intensive relative to S
imports. This ould reverse the Leontief paradox.
Skills of Labor
A nations la or force is far from homogeneous ut rather consists of many
skill groups. Some economists, such as Donald Keesing, have sought the
explanation of trade patterns in endo ments of skills.
The asic point is that the use of la or as factor of production may involve a
category that is too aggregative, since there are many different kinds and
qualities of la or.
Keesing divided the S la or in production into the follo ing eight different
categories (They are listed in a descending order of skills): 1. Scientists and
Engineers ; 2.Technicians and Draftsmen; 3.Other Professional; 4. Managers;
5.Skilled La orers; 6.Other Skilled Handworkers; 7.Marketing Personnel and
8.Semiskilled and nskilled La orers. Keesing argued the first seven
categories could e skilled la or while the last category must e unskilled
la or.
In addition Keesing contri uted the differences in skills of la orers to how
many years of education received y different workers.
See: Donald Keesing, Labor Skills and Comparative Advantages, American
Economic Review 56, no. 2, May 1966.
Labor with Different Skills in US
Exports and Imports
Keesi f t t i eri t ere s siti e
rrel ti et een t e r nking f t e r ti s f
exports over t e tot l output of n industr , t t is (X
/ T )
i
, nd t e ove list of l or it different skills.
In ot er ords t ose industries in t e it ore
skilled l or ould ve exported l rger proportion
of t eir output to road.
Keesing also found t at skilled labor
(Categor 1 till 7) accounted for 55% of t e
total labor requirement in t e exports of
manufacturing goods ich is higher than the
same ratio for the import substitutes. In
the imports unskilled labor is required in a
relativel larger proportion. Thus it can be
said that the is exporting skilled labor-
intensive goods hile importing unskilled
labor-intensive goods.
Keesings Conclusion
It must a common knowledge that a typical
S la orer received more years of education
on average than the foreigners and the S
possessed substantially more scientists,
engineers and the other sorts of skilled
labor in the world.
Keesing argued that as a skilled labor
abundant and unskilled labor scarce
country the S trade pattern is consistent
with the basic prediction of the H-O theory.
There is no paradox.
The US Trade Policies
William Travis, suggested that the Leontief paradox might be
duo largely to tariffs and other forms of protection. There is
evidence that, in the nited States and some other developed
countries labor-intensive industries are relatively heavily
protected. Such trade protection must influence trade patterns
of those countries.
Robert E. Baldwin Baldwin tried to explain what he discovered
by considering specific tariff policy and the other relevant
trade policies taken by the nited States. The S takes a lot of
measures to protect its labor-intensive industries and at the
same time encourages its capital-intensive goods exports by so
many means.
See: William. P. ravis, he heory of rade and Protection, Cambridge: Harvard
University Press, 1964 and Robert E. Baldwin, Determinants of the Commodity
Structure of U.S. rade, American Economic Review 61, no. 1 March 1971.
Free trade, fare trade or no trade?!
Effect of Trade Policies
Such mixture of trade policies must have great impacts on the
actual trade pattern of the S.
On one hand, protectionist policies, especially the high trade
barriers, must inevitably hinder the foreign labor-intensive
commodities from entering into the S domestic market.
Consequently labor intensity of S imports would be relatively
reduced. On the contrary, capital intensity of S imports would
be relatively increased.
On the other hand a set of preferential policies for speeding up
S exports would inexorably stimulate exports of S labor-
intensive commodities thus relatively increase the proportion of
labor-intensive commodities in S total exports and
consequently the overall labor intensity of S exports might be
relatively increased.
R & D Factor
Some economists analyzed proportion of R and D investment
over the total sale and proportion of scientists and technicians
over the total employees in 19 industries of the S.
Statistics showed that those industries with the relatively
higher such proportions, such as transportation industry,
chemical industry, machinery manufacturing industry, and
instrument making industry, export more of their products
overseas. Those four industries accounted for 39.1% of the
total sale, 72% of the total exports and 89.4% of the total R and
D investment of the S manufacturing industries.
Therefore, Gruber, Melta and Vernon concluded that those
industries with more R and D investment thus an advanced
technology are the major exporters of the S.
See: W. Gruber, D. Melta, R. Vernon, The R and D Factor in International Trade and
Investment of United States IndustryJournal of Political Economy, Vol. 75
February, 1967.
They insisted that the S had developed an advanced risk
investment mechanism and constituted a comparatively greater
capability of technologic innovation and creation it must enjoy a
substantial comparative advantages over the other countries in
the high-tech industries.
This country, the nited States of America, produces and
exports R and D factor-intensive goods based on its comparative
advantages in high-tech industries derived from its relatively
abundant R and D factor and meanwhile imports the sorts of
products with relatively lower intensity of R and D factor from
abroad.
The S trade structure is consistent with the basic principle of
H-O Model and no paradox at all.
The argument of R and D factor presented, to some extent a
reasonable explanation of Leontief paradox.
In real terms (constant or inflation-
adjusted dollars), total R&D
performance grew 40.5 percent
between 1994 and 2000 at an average
annual real growth rate of 5.8 percent
over the period .
otal 2003 R&D performance in the
United States is projected to be $283.8
billion, up from an estimated $276.4
billion in 2002 and $274.2 billion in
2001.
R&D performance as a proportion of
GDP rose from 2.40 percent in 1994 to
2.69 percent in 2000 as growth in R&D
outpaced the growth of the overall
economy. he ratio of R&D to GDP
peaked in 2001 at 2.72 percent as the
rate of economic growth from the late
1990s slowed. In the subsequent
years, total R&D grew at a slower pace
than the overall economy, resulting in
R&D to GDP ratios of 2.65 percent in
2002 and 2.61 percent in 2003.
Demand Bias
Stefan Valavanis-Vail might be a pioneer of this approach. In
1954 he suggested a hypothesis of consumption structures.
He argued that there would be possibility in the real world that
a capital abundant country did not need to export capital-
intensive good if her tastes are strongly biased toward capital-
intensive goods.
Equivalently, a labor abundant country would import labor-
intensive goods from abroad if residents of this country had a
very strong bias toward consumption of labor-intensive goods.
Thus, Leontief Paradox can be explained if the S had a strong
consumption bias toward the capital-intensive goods.
See: Stefan ValavanisVail, Leontiefs Scarce Factor ParadoxJournal of Political
Economy, Vol. 62Dec. 1954. H. S. Houthakker, An International Comparision of
Household Expenditure Patterns, Commemorating the Centenary of Engels Law
Econometrica, Vol. 25, Oct. 1957. Staffan Linder, An Essay on Trade and
Transformation, Stockholm, Almquist and Wikell, 1961.
Statistics show that the industrial developed countries,
typically the nited States, indeed have a strong consumption
preference to some high quality and thus expensive luxury
goods (A relatively capital-intensive approach must be
employed in production processes of those goods) since the
overall income levels in those countries are much higher than
the less-developed countries.
In order to meet a great requirement of their consumers
many capital-intensive goods have been shipped from
abroad.
The opposite situation could be found
in the less-develop countries with a
very low income.
Consumption bias in those low-income
countries would strongly toward
inferior goods (They are basically labor
intensive) and therefore they do import
labor-intensive goods from abroad.
Theoretical Position of Leontief and His Paradox
In summary, Leontiefs research and his paradox not only
triggered the extensive empirical tests of factor endowment
theory but more importantly, induced more and more
economists to do a lot of valuable research in depth in order to
give the answer to such riddle. In this process they gave
different explanations to the new discovery of Leontief.
They either explored the influences of production factors with
different qualities or different essentialities on trade pattern of
a country, or introduced some new factors into the theoretical
framework, or analyzed the possible effects on trade of some
distortions in the real economy.
Even though they took different methods in their analysis and
they also focused on different points, they had a common
ground. That is they all advocated the principle of factor
endowment theory. They hoped lay a more scientific
foundation for factor endowment theory by their research.
For this purpose, those economists inserted some new factors,
which were abstracted by Heckscher and Ohlin when they
established theoretical system of factor endowment theory,
into theoretical framework of H-O Model.
More valuable is that all of those economists, happen to
coincide, accentuated the effects of technical progress on trade
pattern.
Their research thinking and the conclusions they had reached
reflected the actual variations in development of international
trade and the world economy.
Consequently what they had done in different research
developed and refined trade theory particular factor
endowment theory.
To this extent, we see without Leontief and his paradox it
would not be expected that trade theory could have been
developed so intensively.
Questions and problems
How to understand the significance of the empirical testing
of trade theory?
Why people termed the discovery of Leontiefs study as a
Paradox? What does the paradox mean?
How did Leontief himself present explanation of the
paradox?
Try to illustrate the major explanations of Leontief Paradox.
Try to describe your own ideas concerning the origin and the
reasonable explanation of the Paradox.
Try to illustrate the theoretical position of Leontiefs
research and discovery in development of trade theory. | https://www.scribd.com/document/221798414/50865375-9-1-Leontief-Paradox-and-Development-of-Trade-Theory-1-pdf | CC-MAIN-2019-35 | refinedweb | 4,588 | 59.64 |
Here is a listing of C++ quiz on “Classes” along with answers, explanations and/or solutions:
1. What does a class in C++ holds?
a) data
b) functions
c) both data & functions
d) none of the mentioned
View Answer
Explanation: The classes in C++ encapsulates(i.e. put together) all the data and functions related to them for manipulation.
2. How many specifiers are present in access specifiers in class?
a) 1
b) 2
c) 3
d) 4
View Answer
Explanation: There are three types of access specifiers. They are public, protected and private.
3. Which is used to define the member of a class externally?
a) :
b) ::
c) #
d) none of the mentioned
View Answer
Explanation: :: operator is used to define the body of any class function outside the class.
4. Which other keywords are also used to declare the class other than class?
a) struct
b) union
c) object
d) both struct & union
View Answer
Explanation: Struct and union take the same definition of class but differs in the access techniques.
5. What is the output of this program?
#include <iostream>
using namespace std;
class rect
{
int x, y;
public:
void val (int, int);
int area ()
{
return (x * y);
}
};
void rect::val (int a, int b)
{
x = a;
y = b;
}
int main ()
{
rect rect;
rect.val (3, 4);
cout << "rect area: " << rect.area();
return 0;
}
a) rect area: 24
b) rect area: 12
c) compile error because rect is as used as class name and variable name in line #20
d) none of the mentioned
View Answer
Explanation: In this program, we are calculating the area of rectangle based on given values.
Output:
$ g++ class.cpp $ a.out rect area: 12
6. What is the output of this program?
<< "execute";
}
else
{
cout<<"not execute";
}
return 0;
}
a) execute
b) not execute
c) none of the mentioned
d) both execute & not execute
View Answer
Explanation: In this program, we are just pointing the pointer to a object and printing execute if it is correctly pointed.
Output:
$ g++ class1.cpp $ a.out execute
7. Which of the following is a valid class declaration?
a) class A { int x; };
b) class B { }
c) public class A { }
d) object A { int x; };
View Answer
Explanation: A class declaration terminates with semicolon and starts with class keyword. only option (a) follows these rules therefore class A { int x; }; is correct.
8. The data members and functions of a class in C++ are by default ____________
a) protected
b) private
c) public
d) none of the mentioned
View Answer
Explanation: By default all the data members and member functions of class are private.
9. Constructors are used to
a) initialize the objects
b) construct the data members
c) both initialize the objects & construct the data members
d) none of the mentioned
View Answer
Explanation: Once the object is declared means, the constructor are also declared by default.
10. When struct is used instead of the keyword class means, what will happen in the program?
a) access is public by default
b) access is private by default
c) access is protected by default
d) none of the mentioned
View Answer
Explanation: For structures, by default all the data members and member functions are public.
Sanfoundry Global Education & Learning Series – C++ Programming Language. | https://www.sanfoundry.com/c-plus-plus-quiz-classes/ | CC-MAIN-2019-09 | refinedweb | 547 | 61.16 |
How to Publish Your Vue.js Component on NPM
How to Publish Your Vue.js Component on NPM
If you've built a Vue.js component, check out this tutorial to learn how to share it with other developers by packaging and publishing it on NPM.
Join the DZone community and get the full member experience.Join For Free
Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.
You:
- Ensuring dependencies are not included in the package
- Using Webpack to create separate builds for the browser and Node
- Creating a plugin for the browser
- Important configuration of package.json
- Publishing on NPM
Note: this article was originally posted here on the Vue.js Developers blog on 2017/07/31
Case Study Project: Vue Clock
I've created this simple clock component which I'm going to publish on NPM. Maybe it's not the coolest component you've ever seen, but it's good enough for demonstration.
Here's the component file. There's nothing too special here, but note that I'm importing the moment library in order to format the time. It's important to exclude dependencies from your package, which we'll look at shortly.
Clock.vue
<template> <div>{{ display }}</div> </template> <script> import moment from 'moment'; export default { data() { return { time: Date.now() } }, computed: { display() { return moment(this.time).format("HH:mm:ss"); } }, created() { setInterval(() => { this.time = Date.now(); }, 1000); } } </script>
Key Tool: Webpack
Most of what I need to do to prepare this component for NPM is done with Webpack. Here's the basic Webpack setup that I'll be adding to in this article. It shouldn't include many surprises if you've used Vue and Webpack before:
webpack.config.js
const webpack = require('webpack'); const path = require('path'); module.exports = { entry: path.resolve(__dirname + '/src/Clock.vue'), output: { path: path.resolve(__dirname + '/dist/'), filename: 'vue-clock.js' }, module: { loaders: [ { test: /\.js$/, loader: 'babel', include: __dirname, exclude: /node_modules/ }, { test: /\.vue$/, loader: 'vue' }, { test: /\.css$/, loader: 'style!less!css' } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin( { minimize : true, sourceMap : false, mangle: true, compress: { warnings: false } }) ] };
Externals
The
externals configuration option provides a way of excluding dependencies from the Webpack output bundle. I don't want my package to include dependencies because they will bloat its size and potentially cause version conflicts in the user's environment. The user will have to install dependencies themselves.
In the case study project, I'm using the moment library as a dependency. To ensure it doesn't get bundled into my package, I'll specify it as an external in my Webpack configuration:
webpack.config.js
module.exports = { ... externals: { moment: 'moment' }, ... }
Environment Builds
In Vue.js, there are two different environments where a user might want to install a component. Firstly, the browser e.g.
<script type="text/javascript" src="vue-clock.js"></script>
Secondly, Node.js-based development environments e.g.
import VueClock from 'vue-clock';
Ideally, I want users to be able to use Vue Clock in either environment. Unfortunately, these environments require the code to be bundled differently, which means I'll have to set up two different builds.
To do this, I'll create two separate Webpack configurations. This is easier than it sounds because the configurations will be almost identical. First I'll create a common configuration object, then use webpack-merge to include it in both environment configurations:
webpack.config.js
const webpack = require('webpack'); const merge = require('webpack-merge'); const path = require('path'); var commonConfig = { output: { path: path.resolve(__dirname + '/dist/'), }, module: { loaders: [ ... ] }, externals: { ... }, plugins: [ ... ] }; module.exports = [ // Config 1: For browser environment merge(commonConfig, { }), // Config 2: For Node-based development environments merge(commonConfig, { }) ];
The common configuration is exactly as it was before (I've abbreviated most of it to save space), except I've removed the
entry and
output.filename options. I'll specify these individually in the separate build configurations.
Browser Bundle
Browsers can't import JavaScript modules from another file the same way a Node can. They can use a script loader like AMD, but for maximum ease, I want to allow my component script to be added more simply as a global variable.
Also, I don't want the user to have to think too hard to figure out how to use the component. I'll make it so the component can easily be registered as a global component when the user includes the script. Vue's plugin system will help here.
The result I'm aiming for is this simple setup:
index.html
<body> <div id="app"> <vue-clock></vue-clock> </div> <script type="text/javascript" src="vue-clock.js"></script> <script type="text/javascript"> Vue.use(VueClock); </script> </body>
Plugin
First, I'll create a plugin wrapper to allow for easy installation of the component:
plugin.js
import Clock from './Clock.vue'; module.exports = { install: function (Vue, options) { Vue.component('vue-clock', Clock); } };
This plugin registers the component globally, so the user can call the clock component anywhere in their application.
Webpack Configuration
I'll now use the plugin file as the entry point for the browser build. I'll output to a file called
vue-clock.min.js as that'll be most obvious to the user.
module.exports = [ merge(config, { entry: path.resolve(__dirname + '/src/plugin.js'), output: { filename: 'vue-clock.min.js', } }), ... ];
Exporting as a Library
Webpack can expose your bundled script in a variety of different ways, e.g. as an AMD or CommonJS module, as an object, as a global variable etc. You can specify this with the
libraryTarget option.
For the browser bundle, I'll use the
window target. I could also use
UMD for more flexibility, but since I'm creating two bundles already, I'll just confine this bundle for use in the browser.
I'll also specify the library name as 'VueClock'. This means that when a browser includes the bundle, it will be available as the global
window.VueClock.
output: { filename: 'vue-clock.min.js', libraryTarget: 'window', library: 'VueClock' }
Node Bundle
To allow users to use the component in a Node-based development environment, I'll use the UMD library target for the Node bundle. UMD is a flexible module type that allows code to be used in a variety of different script loaders and environments.
module.exports = [ ... merge(config, { entry: path.resolve(__dirname + '/src/Clock.vue'), output: { filename: 'vue-clock.js', libraryTarget: 'umd', // These options are useful if the user wants to load the module with AMD library: 'vue-clock', umdNamedDefine: true } }) ];
Note that the Node bundle uses the single-file component as its entry point and does not use plugin wrapper, as it is not needed. This allows a more flexible installation:
import VueClock from 'vue-clock'; new Vue({ components: { VueClock } });
package.json
Before publishing to NPM I'll setup my package.json file. A detailed description of each option is available on npmjs.com.
package.json
{ "name": "vue-clock-simple", "version": "1.0.0", "description": "A Vue.js component that displays a clock.", "main": "dist/vue-clock.js", "scripts": { "build": "rimraf ./dist && webpack --config ./webpack.config.js" }, "author": "Anthony Gore", "license": "MIT", "dependencies": { "moment": "^2.18.1" }, "repository": { ... }, "devDependencies": { ... } }
I've abbreviated most of this file, but the important things to note are:
1. The main script file i.e.
"main": "dist/vue-clock.js". This points the Node bundle file, ensuring that modules loaders know which file to read i.e.
import VueClock from 'vue-clock' // this resolves to dist/vue-clock.js
2. Dependencies. Since I've excluded any dependencies from the package, users must install the dependencies to use the package.
Publishing to NPM
Now that my component is set up correctly, it's ready to be published on NPM. I won't repeat the instructions here since they're covered nicely on npmjs.com.
Here's the result:
Take A Free Vue.js Course! Get started with Vue by learning the basic features and building a real web app in our free 2-hour video course Build Your First Vue.js App. Enroll for free!
Take a look at an Indigo.Design sample application }} | https://dzone.com/articles/how-to-publish-your-vuejs-component-on-npm | CC-MAIN-2019-04 | refinedweb | 1,363 | 51.24 |
Plant Physiol, September 2000, Vol. 124, pp. 153-162
Horticultural Sciences Department, University of Florida,
Gainesville, Florida 32611 (S.D.M., B.L.)
Previous work has shown that tobacco (Nicotiana tabacum)
plants engineered to express spinach choline monooxygenase in the chloroplast accumulate very little glycine betaine (GlyBet) unless supplied with choline (Cho). We therefore used metabolic modeling in
conjunction with [14C]Cho labeling experiments and in
vivo 31P NMR analyses to define the constraints on GlyBet
synthesis, and hence the processes likely to require further
engineering. The [14C]Cho doses used were large enough to
markedly perturb Cho and phosphocholine pool sizes, which enabled
development and testing of models with rates dynamically responsive to
pool sizes, permitting estimation of the kinetic properties of Cho
metabolism enzymes and transport systems in vivo. This revealed that
import of Cho into the chloroplast is a major constraint on GlyBet
synthesis, the import rate being approximately 100-fold lower than the
rates of Cho phosphorylation and transport into the vacuole, with which import competes. Simulation studies suggested that, were the
chloroplast transport limitation corrected, additional engineering
interventions would still be needed to achieve levels of GlyBet as high
as those in plants that accumulate GlyBet naturally. This study reveals the rigidity of the Cho metabolism network and illustrates how computer
modeling can help guide rational metabolic engineering design.
Daniel Koshland's recent commentary
on "the era of pathway quantification" encapsulates the growing
importance to basic biochemistry of mathematical tools for quantifying
metabolic fluxes in vivo (1998). Moreover, advances in metabolic
control theory and metabolic engineering experience show that we must
quantify fluxes if we wish to understand metabolism well enough to
manipulate it effectively (Fell, 1997; Nuccio et al., 1999;
Stephanopoulos, 1999). No matter the approach used to investigate
fluxes (e.g. radio or stable isotopes), it is generally necessary to
use computer-assisted modeling to derive in vivo flux values from
experimental data because there are too many variables to handle by
intuition (Bailey, 1998). Here we apply computer modeling to interpret
experimental radiolabeling data in a metabolic engineering situation:
Gly betaine (GlyBet) synthesis in transgenic tobacco (Nicotiana
tabacum L. cv Wisconsin 38) expressing choline (Cho) monooxygenase (CMO).
GlyBet is an established target for metabolic engineering of stress
tolerance because it is a potent osmoprotectant that many plants lack
(McNeil et al., 1999). In spinach, GlyBet is synthesized in the
chloroplast by a two-step oxidation of Cho and catalyzed by CMO and
betaine aldehyde dehydrogenase (BADH). The absence of CMO is the most
obvious constraint on GlyBet production in GlyBet-deficient plants such
as tobacco, but tobacco transgenics expressing CMO in chloroplasts at
up to 10% of the level in spinach accumulated at most 70 nmol GlyBet
g1 fresh weight, or approximately 0.3% of that
in spinach (Nuccio et al., 1998). However, GlyBet levels increased
greatly when Cho or its precursors mono- and dimethylethanolamine were
supplied, suggesting that the endogenous Cho supply is inadequate
(Nuccio et al., 1998). Similar results were obtained with tobacco and other dicots expressing a bacterial Cho oxidase in the cytosol (Huang
et al., 2000).
Radiotracer and modeling studies have shown that tobacco leaves
synthesize Cho moieties via parallel phosphobase (P-base) and
phosphatidylbase (Ptd-base) pathways, and that the former accounts for
some 85% of the total flux (McNeil et al., 2000). These pathways
respectively produce phosphocholine (P-Cho) and phosphatidylcholine (Ptd-Cho; Fig. 1).
Free Cho, the substrate required by CMO, originates almost solely from
Ptd-Cho turnover. Once released from Ptd-Cho into the cytosol, Cho is
either rapidly converted to P-Cho by Cho kinase and reused in Ptd-Cho
synthesis or transported into a storage pool, presumably in the vacuole (McNeil et al., 2000). In tobacco engineered with CMO in the
chloroplast the CMO must therefore compete for free Cho with both Cho
kinase and vacuolar Cho transport (Fig. 1). However, since CMO is
inside the chloroplast and Cho is generated in the cytosol, unless Cho crosses the chloroplast envelope freely it would be the chloroplast Cho
uptake process, not CMO itself, that would be pitted against Cho kinase
and vacuolar import (Fig. 1). Thus the supply of endogenous Cho for
GlyBet synthesis could be limited by the rates of processes besides Cho
synthesis; these include Cho phosphorylation, Cho storage in the
vacuole, and Cho transport into the chloroplast.
To identify which of these processes most limit flux to GlyBet in
transgenic tobacco, [14C]Cho was supplied to
transgenic leaf tissue, the radiolabeling kinetics of Cho, GlyBet,
P-Cho, and Ptd-Cho were followed, and the data were subjected to
computer modeling. This enabled us to derive a quantitative picture of
the fluxes and pool sizes in the Cho metabolism network and to
hypothesize how flux to GlyBet would respond to hypothetical engineered
changes. A key deduction from the modelingthat the P-Cho pool is
entirely cytosolicwas verified by in vivo 31P
nuclear magnetic resonance (NMR) analyses.
Model Outputs and Their Implications
Vmax and
Km values for fluxes B through E, G, and H
in the model (Table I; Fig. 2) were
obtained by progressive adjustment, until the simulated
radiolabeling kinetics closely matched those observed. The
first order rate constants governing Cho uptake and the cytosolic
Cho (Chocy) chloroplastic Cho
(Chochl) and vacuolar Cho (Chovac)
Chocy fluxes (fluxes A, I, and F) were obtained in the same way. Of these model-derived parameters, those for
Cho kinase (flux B) and CTP:P-Cho cytidylyltransferase (flux D) can be
checked against literature values. For both enzymes the modeled
Km values are close to published ones. The
modeled Km for the cytidylyltransferase
of 80 nmol g1 fresh weight
corresponds to 3.3 mM (80 nmol/24 µL = 3.3 mM), which is within a factor of three of the
measured Km for P-Cho of the castor bean
enzyme (1.1 mM; Wang and Moore, 1989). The modeled Km for Cho kinase, 1.7 mM, is within the range reported for plants
(0.03-2.5 mM; Setty and Krishnan, 1972; Bligny
et al., 1989; Gawer et al., 1991). The modeled
Vmax values for both enzymes also fall
inside the limits known for plant tissues (e.g. Tanaka et al., 1966;
Kinney et al., 1987; Bligny et al., 1989; Wang and Moore,
1989).
The success of the model in accounting for radiolabeling data is
illustrated in Figure 3, which shows
simulations (curves) superimposed on experimental data points for four
different experiments. Figure 3, a and b show simulated and actual data
for immature, unsalinized leaf tissue, for which the model was
initially developed. Figure 3, c through h summarize data for salinized
and mature tissue, and will be discussed later. We will turn first to
the outputs of the immature leaf model.
The simulated flux rates (Fig. 4, a-e),
and pool sizes (Fig. 4, f-j) during the time-course illustrate the
model's usefulness in analyzing dynamic metabolic behavior. As the
large dose of supplied [14C]Cho is taken up
(Fig. 4f), Chocy rapidly expands (Fig. 4g). This
in turn drives up the rate of synthesis of P-Cho and the rates of Cho
flux into the vacuole and chloroplast (Fig. 4, b-d). The transient
rise in Chochl drives a matching increase in the rate of Cho oxidation to GlyBet (Fig. 4c). Elevated levels of P-Cho
(Fig. 4i) increase the flux from P-Cho Ptd-Cho (Fig. 4d). However,
since the Ptd-Cho pool is large, the expansion of the Ptd-Cho pool is
modest in relative terms (Fig. 4h) and the perturbations to the Ptd-Cho
P-Cho and Ptd-Cho Chocy fluxes are
consequently minor (Fig. 4, d and e). When the large dose of
[14C]Cho has been metabolized, the fluxes and
pool sizes in the model revert to a steady state (Fig. 4). The
model-generated steady-state fluxes at 600 min (Fig. 4, a-e) were very
similar (r2 = 0.98) to the fluxes in Cho
metabolism that were previously determined from
33P-base and [14C]formate
labeling data (McNeil et al., 2000).
The following five features of the model output are significant for
understanding Cho metabolism; the first four are consistent with
previous analyses (McNeil et al., 2000). Taken together, all five
indicate that the Cho metabolism network in tobacco is rigid as
defined by Stephanopoulos and Vallino (1991); having evolved to meet
demands for Ptd-Cho synthesis and turnover, it tends intrinsically to
resist redirection of flux. (a) The cytosolic P-Cho pool is always
substantial, and its main fate is conversion to Ptd-Cho, not
Chocy. (b) The Chocy pool
returns to a very low value regardless of the starting
Chocy value used to prime the model at
t = 0 min (not shown), whereas the
Chovac pool reaches a near steady state of
approximately 80 nmol g1 fresh weight (Fig.
4g). This confirms that the Chocy pool is normally only a small fraction of the total Cho. (c) Ptd-Cho is catabolized to P-Cho and Chocy at similar and
substantial rates, resulting in a Ptd-Cho turnover rate of
approximately 50% per day, which is typical for plants (e.g. Mongrand
et al., 1997). (d) The net rate of Ptd-Cho synthesis is adequate to
meet the Ptd-Cho requirement for growth, which is approximately 90 to
160 pmol min1 g1 fresh
weight, assuming a leaf growth rate of 10% d1
(McNeil et al., 2000). (e) Flux to GlyBet is highly sensitive to
changes in the rate constant describing Cho transport into the
chloroplast, but not to the Vmax or
Km assigned to CMO and BADH. (The flux
split Chocy P-Cho:Chocy
Chovac:Chocy Chochl was 84.8:15:0.2. This flux split did not
change when simulations were run with 10-fold higher
Vmax values for CMO and BADH or when Chocy was increased 10-fold.) This clearly points
to the chloroplast Cho import process as the step with most control of
flux through the GlyBet pathway in CMO+ tobacco.
Moreover, during steady-state conditions Cho flux across the
chloroplast membrane (flux I) is approximately 380-fold less than to
P-Cho (flux B) and approximately 70-fold less than to the vacuole (flux
G), which indicates that the chloroplast Cho uptake process competes
poorly for Chocy with Cho kinase and vacuolar Cho transport.
Testing the Model: Application to Other Experimental Data
Sets
The robustness of the model was tested by examining its ability to
simulate the labeling patterns obtained in
[14C]Cho experiments with immature leaf tissue
from salinized CMO+ plants, salinization being
known to increase CMO activity 3- to 5-fold and to reduce the P-Cho
pool size 3-fold (Nuccio et al., 1998). After making these changes to
the model a good fit was obtained between model-generated and observed
values (Fig. 3, c and d) using parameters that were very similar to
those used for unsalinized immature leaf tissue (Table I). Minor
exceptions were the rate constant for Cho movement across the
chloroplast envelope and the Vmax for Cho
transport into the vacuole, both of which were about 2-fold higher in
the salinized tissue. Similar tests of the model were made with data
from [14C]Cho experiments with unsalinized and
salinized mature leaf tissue (Fig. 3, e-h). In these instances also,
the observed labeling patterns were simulated satisfactorily without
making major changes to the model parameters (Table I). The largest
changes needed were a doubling of the Vmax
for Cho kinase, and a halving of that for the cytidylyltransferase.
Lastly the model was tested by supplying larger
[14C]Cho doses, which increased the amount
absorbed to as much as 4000 nmol g1 fresh
weight. Again the labeling patterns in these experiments were
satisfactorily modeled (not shown).
Testing the Model: Localizing the P-Cho Pool
The model above accounts for the radiolabeling patterns seen for
immature and mature leaves of unsalinized or salinized
CMO+ plants, but the model values shown are far
from the only possible solutions that fit the data. It was therefore
crucial to test, to the extent possible, the model's hypotheses and
assumptions, and preferably to do so by means independent of
radiolabeling data. A major model-generated hypothesis is that leaf
tissue supplied with excess Cho will accumulate cytoplasmic P-Cho at a
linear rate of at least 2.4 nmol min1
g1 fresh weight for several hours (Fig. 4d).
This prediction was directly tested by in vivo
31P-NMR using leaf tissue strips perfused with Cho.
We made use of the pH sensitivity of certain NMR signals to
distinguish vacuolar from cytoplasmic P- Cho accumulation. Figure 5A shows a 31P in
vivo NMR spectrum of tobacco leaf tissue, and Figure 5B is a series of
subspectra of the phosphomonoester signals during a time-course of
perfusion with Cho. The observed accumulation of a P-Cho signal over
several hours is quantitatively consistent with the model's
predictions (Fig. 5B, legend), and also with the elevated P-Cho levels
found in plants cultured on Cho-containing medium (Nuccio et al.,
1998). The position of the P-Cho signal indicates that it is in a
compartment whose pH is comparable with that of the compartment
containing Glc-6-P and one of the inorganic phosphate
(Pi) signals; that is, the cytoplasm at a pH
close to 7.5. (This compartmental assignment was made by comparison to literature values [Bligny et al., 1989, 1990] and to spectra of P-Cho
solutions of defined pH; not shown).
This observation of P-Cho accumulation in a compartment of near-neutral
pH was made in leaf tissue from plants grown under greenhouse
conditions and in axenic culture with or without Cho (not shown). If
there were a significant P-Cho storage pool in the vacuole its signal
would be expected to have appeared slightly to the right of the
vacuolar Pi signal in Figure 5A. No evidence of
such a signal was seen in these or other spectra, even when the
vacuolar Pi peak was smaller and/or narrower than
in Figure 5A (not shown).
To further eliminate the possibility that a small vacuolar P-Cho signal
might have been obscured by overlap with vacuolar Pi, we rapidly alkalinized both the vacuole and
cytoplasm by perfusion with ammonia-containing solution. Under these
conditions all compartments would be expected to come to the same
elevated pH and signals from any vacuolar P-Cho would be shifted to
join the cytoplasmic P-Cho peak. There was no change in the amplitude
of the P-Cho peak under such conditions (not shown) supporting the view
that there was no additional P-Cho pool in this tissue that was not seen at physiological pH. Besides confirming a cytoplasmic location for
P-Cho, other in vivo NMR observations were in agreement with the model.
(a) No measurable (less than 50 µM) accumulation of cytidyldiphosphate choline (CDP-Cho) or glycerophosphorylcholine occurred even when high levels of P-Cho accumulated. (b) Leaf tissue
from Cho-grown plants, which contain high levels of Cho (Nuccio et al.,
1998), gave a P-Cho signal corresponding to a cytoplasmic concentration
in the low millimolar range. Perfusion of this tissue with 100 µM Cho resulted in a further accumulation of P-Cho at
similar rates to that of tissue from plants grown without exogenous
Cho. This supports the view that much of the accumulated Cho is in a
non-metabolic pool, since exogenous Cho resulted in further cytoplasmic
P-Cho accumulation whereas the high level of endogenous Cho was not
being converted to P-Cho.
Metabolic Engineering Applications
Thus far we have used the model to describe the fluxes occurring
in CMO+ tobacco and to deduce the kinetic
properties of the reactions and transport steps of the network. We now
illustrate the usefulness of the model in generating testable
hypotheses concerning metabolic engineering strategies to enhance
GlyBet production without seriously reducing the net flux to Ptd-Cho,
which is essential to growth. Our target flux to GlyBet was 350 pmol
min1 g1 fresh weight
because this is the rate required to sustain a GlyBet pool of 5 µmol
g1 fresh weight, assuming a tissue growth rate
of 10% d1. A tissue GlyBet content of 5 µmol
g1 fresh weight is within the range
characteristic of GlyBet-accumulating plants and would be expected to
confer significant protective effects (Sakamoto et al., 1998). To
introduce and illustrate the results of our simulations, Figure
6 shows the impact of some single-parameter changes: engineering a higher CMO level, increasing the rate of Cho uptake into the chloroplast, and lowering Cho kinase
expression.
Figure 6A shows that a 35-fold increase in the
Vmax of CMO does not increase flux to
GlyBet at all because control resides in the previous step in the
pathway, Cho uptake into the chloroplast. Thus when the capacity for
Cho uptake is enhanced (Fig. 6B) there is a near-proportional increase
in flux to GlyBet. However, it should be noted that flux to GlyBet
cannot be increased indefinitely in this way, for two reasons. First,
the activity of CMO eventually becomes limiting. Second, without an
increase in the synthesis of P-Cho via the P-base pathway (or Ptd-Cho
via the Ptd-base route), only a modest Cho flux can be diverted to
GlyBet without causing the net flux to Ptd-Cho to sink below the
minimum needed for growth, i.e. approximately 90 pmol
min1 g1 fresh weight
(see above). Figure 6C makes a similar point: Decreasing Cho kinase
activity (which increases Chocy) causes a modest
increase in GlyBet synthesis, but this effect is soon vitiated by a
collapse in the net flux to Ptd-Cho. The results of further
manipulations of the parameters in Figure 6, other model parameters,
and their combinations led to the following hypotheses.
Major gains in GlyBet synthesis in CMO+ tobacco
plants cannot be achieved without increasing the supply of Cho
available in the chloroplast. A dramatic increase in GlyBet synthesis
rate is observed (from 0.8 to 78 pmol
min1 g1 fresh weight)
when the rate constant for Cho flux across the chloroplast
envelope is increased 150-fold (Fig. 6B). This rate could sustain a
GlyBet pool of 1.1 µmol g1 fresh weight
in a leaf growing at 10% d1, without
pushing net Ptd-Cho synthesis below the estimated threshold for normal
growth of approximately 90 pmol min1
g1 fresh weight. It is interesting that this
predicted ceiling in GlyBet level is exceeded by up to 2-fold in
tobacco transgenics expressing bacterial Cho oxidase genes in the
cytosol, where the chloroplast membrane is not a constraint, but these
plants show significantly impaired growth (Huang et al., 2000). The
results of our modeling suggest that one reason for this impairment may be the insufficient production of Ptd-Cho.
Increasing GlyBet synthesis much beyond 78 pmol
min1 g1 fresh weight
would encroach on the Ptd-Cho synthesis requirements for growth. This
problem would be exacerbated were Cho kinase to be down-regulated in
order to elevate cytosolic Cho levels because slowed P-Cho synthesis
from Cho would further reduce the rate of Ptd-Cho synthesis (Fig. 6C).
These difficulties can be overcome by increasing the flux from the
P-base methylation pathway by enough to match the increased Cho demand
for GlyBet synthesis. Fluxes to GlyBet in excess of 100 pmol
min1 g1 fresh weight
would also require CMO activity to be increased.
A flux to GlyBet of close to 350 pmol min1
g1 fresh weight (adequate to maintain a GlyBet
pool of 5 µmol g1 fresh weight) can be
achieved with a combination of four interventions: increasing the rate
constant for Cho flux across the chloroplast envelope 3,000-fold;
decreasing the Vmax of Cho kinase 30-fold; increasing the Vmax of CMO at least
3.5-fold; and increasing the de novo synthesis flux of P-Cho 4- to
8-fold. There is some uncertainty about this last figure as it is
sensitive to assumptions about how much, if at all, the Ptd-Cho pool
can expand beyond the normal range of approximately 1.3 to 2.3 µmol
g1 fresh weight (McNeil et al., 2000).
These model-generated hypotheses are obviously subject to caveats. Gene
expression changes might accompany and accommodate altered Cho demand
in engineered plants, as occurs in yeast (Henry and Patton-Vogt, 1998).
Further controls may operate at the enzyme level within the Cho
metabolism network. However, because these considerations apply to
steps lying upstream of Cho transport into the chloroplast and
oxidation to GlyBet, they are peripheral to the central issue of
diverting more Cho flux to GlyBet. They are therefore unlikely to
invalidate many of the model's predictions.
The computer simulation model described here was designed to
identify the processes in the Cho metabolism network of
CMO+ tobacco plants that constrain GlyBet
accumulation. Qualitative reasoning led Nuccio et al. (1998) to suggest
that the small size of the cytosolic Cho pool, a low capacity for P-Cho
synthesis, and a low rate of Ptd-Cho turnover could all be involved.
Quantitative flux modeling supported the first two of these
possibilities, and suggested two others: an inadequate capacity to
transport Cho into the chloroplast and excessive Cho kinase activity.
The finding that large gains in GlyBet accumulation require the
introduction of a high affinity, high capacity Cho transporter into the
chloroplast membrane draws attention to an interesting area for basic
research, for nothing is known about how Cho moves from cytosol to chloroplast.
Our results provide good examples of the "quantitative conclusions
that are possible when quantification and the mathematics of
quantification become part of the arsenal of investigators of metabolic
interactions" (Koshland, 1998). When used in a metabolic engineering
context, it is clear that modeling cannot only help decide which
enzymes or transporters to target in further rounds of engineering to
overcome constraints, but can also suggest by how much to change their
flux capacities or affinity constants in order to attain specific
engineering goals.
Plant Material
All experiments were carried out with vegetatively propagated
primary transformants of tobacco (Nicotiana tabacum L. cv Wisconsin 38) expressing spinach CMO (CMO+ tobacco; line
4, Nuccio et al., 1998). Plants for [14C]Cho labeling
were grown in a light soil mix in a naturally lit greenhouse; the
minimum temperature was 18°C. Irrigation was with 0.5× Hoagland
nutrient solution. Half or fully expanded leaves from mature plants
that had not flowered were harvested between February and May 1998. Plants for 31P NMR experiments were grown as above, or
cultured axenically for 4 weeks on medium plus or minus 5 mM Cho (Nuccio et al., 1998).
Radiolabeling Experiments
[Methyl-14C]Cho (54 mCi mmol1) was
obtained from NEN (Boston) and purified as described (Weigel et al.,
1988). Discs (11 mm in diameter) were cut from the mid-blade region of
a single leaf for each experiment. Eight shallow radial incisions were
made on the abaxial surface of each disc. Samples were batches of three discs (approximately 50 mg fresh weight). Labeled solutions were applied (2 µL per disc) to the incisions; the discs were then incubated, abaxial surface uppermost, on moist filter paper circles in
Petri dishes at 25°C ± 2°C in fluorescent light
(photosynthetic photon flux density 150 µE m2
s1).
Analysis of Labeled Metabolites
Procedures were essentially as described (Hanson and Rhodes,
1983; Nuccio et al., 1998; McNeil et al., 2000). Briefly, discs were
extracted by a methanol-chloroform-water procedure after boiling in
isopropanol to denature phospholipases, and organic and aqueous phases
were separated. Radioactivity in both phases was quantified by
scintillation counting. The only labeled metabolite in the organic
phase was shown to be Ptd-Cho by thin-layer chromatography. Water-soluble metabolites were fractionated by ion-exchange using 1-mL
columns of AG-1 (OH), BioRex-70 (H+), and
AG-50 (H+) arranged in series; P-Cho was eluted from AG-1
with 5 mL of 2.5 N HCl, Cho from BioRex-70 with 5 mL of 1 N HCl, and GlyBet from AG-50 with 5 mL of 2.5 N
HCl. The identities of the labeled metabolites in the eluates were
confirmed by thin-layer chromatography. Glycerophosphorylcholine, which appears in the effluent from the three-column series, was found not to acquire appreciable label. Data
were corrected for recovery by using samples spiked with [14C]P-Cho, [14C]Cho, or
[14C]GlyBet.
Computer Modeling of Labeling Data
The computer model was evolved from that described by McNeil et
al. (2000). Models were implemented with programs written in Microsoft
Visual Basic. Key assigned parameters were the initial pool sizes,
their specific activities, and the rates connecting the various pools.
Most flux rates (v) were assumed to respond to substrate
pool size (S) according to the Michaelis-Menten equation, i.e.
v = (Vmax × S)/(Km + S), where individual
Vmax and Km
values were specified for each enzyme reaction or transport step. In time-course simulations the assigned parameters and existing substrate pool sizes were used to calculate how much material of defined specific
activity was drawn from one pool to another during 0.1-min intervals.
During each iteration new specific activities and pool sizes were
computed, and total radioactivity in each pool plotted (superimposed on
observed data) as a function of time. Model values and initial pool
sizes were progressively adjusted (within limits set by experimentally
determined or literature values) until a close match between observed
and simulated radioactivity was obtained for the time-course, as judged
graphically or by computing mean absolute deviations between observed
and simulated values. Further details on our models are available at.
31P NMR
Leaves were cut into 2- to 4-mm wide strips and vacuum
infiltrated for 1 to 3 s in a 1 mM CaSO4
solution. Approximately 2 g of tissue was packed in a 10-mm
diameter NMR tube and perfused with aerated 1 mM
CaSO4 (flow rate 2-5 mL min1) at
approximately 18°C. For incubation with Cho, 100 µM Cho
chloride was added to the perfusion medium. Alkalinization was induced by perfusing with 1 mM CaSO4 containing 30 mM NH4Cl at pH 9.0. 31P NMR spectra
were acquired on a UnityPlus 600 MHz instrument (Varian Inc., Palo
Alto, CA) using a 10 mm Broadband probe. Acquisition conditions
were: 90° pulses, a recycle time of 1 s, and no lock or
decoupling; acquisition times for time-courses were 1 to 3 h per
spectrum except for alkalinization experiments where they were 7 min.
Data were processed with minimal exponential multiplication (line
broadening of 10-30 Hz for in vivo spectra) and Fourier transformation
using spectrometer software. Peak assignments and referencing were made
by reference to literature values and to spectra of external solutions
of Pi, P-Cho, and CDP-Cho buffered at cytoplasmic (7.5) or
vacuolar (approximately 5) pH (Chang and Roberts, 1992; Y. Shachar-Hill
and D. Brauer, unpublished data). Chemical shift values in spectra are
given in reference to 85% phosphoric acid at 0 ppm.
We began model development using data for metabolism of
[14C]Cho by half-expanded leaves of CMO+
plants because the endogenous pool sizes and fluxes of Cho metabolites are well documented for young tobacco leaves (Nuccio et al., 1998; McNeil et al., 2000). The model we built is shown in Figure
2; its main features and their rationales
are as follows.
Metabolite Pools
The initial sizes of the endogenous pools of Cho, betaine
aldehyde (BetAld), GlyBet, P-Cho, and Ptd-Cho were based on measured values (Nuccio et al., 1998; McNeil et al., 2000). The model posits a
small metabolically active pool of Cho in the cytosol
(Chocy, 2 nmol g1 fresh weight), a large
vacuolar storage pool (Chovac, 75 nmol g1
fresh weight; Hanson and Rhodes, 1983; McNeil et al., 2000), and a
small chloroplastic pool (Chochl, 0.2 nmol g1
fresh weight) serving as substrate for GlyBet production. These three
pools sum to the measured total free Cho value in CMO+
tobacco (Nuccio et al., 1998). There are single pools of BetAld, GlyBet, P-Cho, and Ptd-Cho, the Ptd-Cho pool (1,800 nmol
g1 fresh weight) being far larger than any other in the
network. Because BetAld was not detectable, its pool size was set to
the detection limit of approximately 0.2 nmol g1 fresh
weight (Rhodes et al., 1987). There is a single, cytosolic P-Cho pool
because the modeling of radiotracer data on Cho synthesis in tobacco
suggested this feature (McNeil et al., 2000). The GlyBet pool is
assumed not to turn over because tobacco was found not to catabolize
GlyBet (Nuccio et al., 1998).
Transport Fluxes
Uptake of Cho from the apoplast has the characteristics of
passive diffusion at Cho concentrations > 100 µM (Bligny
et al., 1989). Assuming the apoplast to be approximately 5% of leaf
volume (Winter et al., 1994), the initial apoplastic
[14C]Cho levels in this study were approximately 3 mM; Cho uptake (flux A) is accordingly modeled as a passive
flux. The kinetics of Cho movement between cytosol and vacuole are
modeled as a "pump-leak" system, with active import into the
vacuole (flux G) and passive efflux to the cytosol (flux F). Active
uptake via a saturable carrier is invoked since Chovac is
much larger than Chocy, and the membrane potential across
the tonoplast does not favor Cho influx (Rea and Poole, 1993); passive
leakage is the simplest mechanism to explain efflux from the vacuole.
Cho uptake into the chloroplast (flux I) is also modeled as a passive
process because no literature suggests a more complex mechanism, and
our data do not require one. Note that this process could correspond to
diffusion or to a saturable, carrier-mediated process whose Km is higher than the Chocy
values that were reached in our experiments. Passive fluxes are
proportional to the sizes of their substrate pools (Fick's first law),
and are described by first-order rate constants (Table I); uptake into
the vacuole is characterized by a Vmax and a
Km (see below). Cho efflux from the
chloroplast and from the cytosol to the apoplast are assumed to be
negligible due to the low Cho concentrations in these compartments. Nor
was GlyBet efflux from the chloroplast considered, since the model cannot address the location of an inert end product.
Metabolic Fluxes
The model provides for P-Cho and Ptd-Cho synthesis from
unlabeled endogenous precursors (fluxes L and M). While these fluxes add no 14C to the system they contribute to P-Cho and
Ptd-Cho turnover and, in the absence of supplied Cho, they are the sole
sources of new Cho moieties. These fluxes are assigned constant rates (0.12 and 0.02 nmol min1 g1 fresh weight
for P-Cho and Ptd-Cho synthesis, respectively) that lie within the
ranges obtained from the modeling of 33P-base and
[14C]formate tracer kinetics (McNeil et al.,
2000).
Other metabolic fluxes were assumed to be mediated by Michaelian
enzymes and hence to show saturable responses to substrate pool size.
These fluxes are therefore assigned a Vmax
(nmol min1 g1 fresh weight) and an apparent
Km (nmol g1 fresh weight), as
summarized in Table I. Vmax and
Km values were interconverted between the
fresh weight-based units required in the model and the customary units
of nmol min1 mg1 protein and
µM by assuming a leaf protein content of 10 mg
g1 fresh weight, a chlorophyll (Chl) content of 1 mg
g1 fresh weight, and the following subcellular
compartment volumes (Winter et al., 1994): cytosol, 24 µL
mg1 Chl; chloroplast stroma, 66 µL mg1
Chl; and vacuole, 546 µL mg1 Chl.
Ptd-Cho synthesis from P-Cho proceeds in two steps via the intermediate
CDP-Cho. However, as the CTP:P-Cho cytidylyltransferase catalyzing the
first step appears to exert most of the control over flux (Price-Jones
and Harwood, 1986; Kinney et al., 1987), and since the level of CDP-Cho
in tobacco was below the detection limit, for simplicity we treated the
P-Cho CDP-Cho Ptd-Cho reactions as a single process (flux D)
that largely reflects the properties of the cytidylyltransferase. The
model postulates that Ptd-Cho is catabolized to Chocy via
phospholipase D (flux H), or to P-Cho (e.g. via phospholipase C; flux
E), and that P-Cho is converted to Chocy by phosphatase
activity and/or the reverse reaction of Cho kinase (flux C; McNeil et
al., 2000).
Enzyme data were used to assign Vmax and
Km values to the Chochl BetAld GlyBet steps (fluxes J and K). CMO activities in unsalinized
and salinized CMO+ leaves were estimated to be 0.1 and 0.3 nmol min1 g1 fresh weight, respectively
(Nuccio et al., 1998; S. McNeil, unpublished data). BADH activity in
tobacco leaves is 3 to 10 nmol min1 g1
fresh weight (Rathinasabapathi et al., 1994; Trossat et al., 1997), and
approximately 20% of BADH was shown to be chloroplastic (S. McNeil,
unpublished data). We therefore assigned a
Vmax value of 1 nmol min1
g1 fresh weight to chloroplastic BADH. The
Km value for spinach CMO is 100 µM (Brouquisse et al., 1989); that for BADH was taken to
be 50 µM, the value for spinach BADH expressed in tobacco
chloroplasts (Trossat et al., 1997).
Other Models Tested
Several plausible variations of the model were tested, alone and
in combination, using the experimental data for immature leaves. These
included models in which (a) Cho import into the chloroplast is
mediated by a saturable transporter, (b) the expansion of the
P-Cho pool caused by the rapid influx of
[14C]Cho transiently inhibits de novo P-Cho and
Ptd-Cho synthesis (Mudd and Datko, 1989), (c) P-Cho inhibits
phospholipase C (Berka and Vasil, 1982), and (d) Cho kinase has a
20-fold lower Km for Chocy than
shown in Table I. None of these variations substantially improved the
goodness-of-fit between simulated and observed values.
We thank Dr. Steven J. Blackband for assistance with NMR
analyses at the University of Florida.
Received February 29, 2000; accepted May
grant from the National Institute of Science and Technology (to
Y.S.-H.), by an endowment from the C.V. Griffin, Sr., Foundation, and
by the Florida Agricultural Experiment Station. This is journal series
paper no. R-07426.
2
Present address: Corning Community College, Corning,
NY 14830.
*
Corresponding author; e-mail adha{at}gnv.ifas.ufl.edu
This article has been cited by other articles: | http://www.plantphysiol.org/cgi/content/full/124/1/153 | crawl-002 | refinedweb | 5,762 | 50.36 |
Tests that compare all elements of two iterable objects.
The to
checkIterable (or the
checkInexactIterable) method.
The class
ExamplesIterables contains all test cases.
You can also download the entire souce code as a zip file.
Complete test results are shown here.
Here is an example comparing
iterable objects.
public class CartPtDouble { Double x; Double y; public CartPtDouble(Double x, Double y) { this.x = x; this.y = y; } public Double distTo0() { return Math.sqrt(this.x * this.x + this.y * this.y); } public Double distTo(CartPtDouble that) { return Math.sqrt((this.x - that.x) * (this.x - that.x) + (this.y - that.y) * (this.y - that.y)); } } public class ExamplesIterables { CartPtDouble cpt1 = new CartPtDouble(3.0, 4.0); CartPtDouble cpt2 = new CartPtDouble(7.0, 7.0); CartPtDouble cpt2a = new CartPtDouble(7.0, 6.9995); // p2a is very close to p2 but not exactly CartPtDouble cpt3 = new CartPtDouble(15.0, 8.0); List
list1 = Arrays.asList(cpt1, cpt2, cpt3); List list2 = Arrays.asList(cpt1, cpt2a, cpt3); // list2 is very close to list1 but not exactly List list3 = Arrays.asList(cpt1, cpt3); List list4 = Arrays.asList(cpt1, cpt3); public void testIterables(Tester t) { t.checkIterable( list3, // 1st iterable list4, // 2nd iterable "Success: same lists"); // test name t.checkIterable( list1, // 1st iterable list2, // 2nd iterable "Should fail: should be checkInexactIterable"); // test name t.checkInexactIterable( list1, // 1st iterable list2, // 2nd iterable 0.01, // tolerance "Success: Test Inexact Iterable"); // test name t.checkInexactIterable( list1, // 1st iterable (3 elements) list3, // 2nd iterable (2 elements) 0.01, // tolerance "Should fail: not the same lists"); // test name } }
backLast updated: March 29, 2011 11:20 am | http://www.ccs.neu.edu/javalib/Tester/Samples/iterable/index.html | crawl-003 | refinedweb | 265 | 54.18 |
Opened 7 years ago
Closed 2 years ago
#2726 closed defect (worksforme)
PageOutline macro always renders the outline of WikiStart through getPageHTML()
Description
This problem comes from missing page name information that is used in method render_macro.
I apply below modification to my local enviornment:
def getPageHTML(self, req, pagename, version=None): """ Return page in rendered HTML, latest version. """ text = self.getPage(req, pagename, version) + req.args['page'] = pagename html = wiki_to_html(text, self.env, req, absurls=1) return '<html><body>%s</body></html>' % html
I know it's very dirty hack, but I have no idea to solve this problem in more elegant manner now.
Attachments (0)
Change History (5)
comment:1 Changed 7 years ago by ghama
- Cc ghama added; anonymous removed
comment:2 Changed 6 years ago by osimons
- Priority changed from normal to low
comment:3 follow-up: ↓ 4 Changed 5 years ago by thijs
- Cc thijs added
- Priority changed from low to lowest
This should probably be closed, focus is on 0.11/0.12 afaik.
comment:4 in reply to: ↑ 3 Changed 2 years ago by osimons
comment:5 Changed 2 years ago by osimons
- Resolution set to worksforme
- Status changed from new to closed
Note: See TracTickets for help on using tickets.
Just tested with trac 0.11 and latest xmlrpc from trunk, and not an issue for these versions. I doubt the 0.10 version will get much attention moving forward, but I'll leave it open for now. | http://trac-hacks.org/ticket/2726 | CC-MAIN-2015-06 | refinedweb | 246 | 59.64 |
[solved...sort of... works... far from perfect] How to properly control (arm+calibrate+command) an HK-20 ESC with arduino?
- Login or register to post comments
- by kariloy
---.
In the end the solution was a mix of the regular RC usage instructions:
"Full throttle (stick up); power up ESC & *beeps* ; Throttle 0% (stick down) *beeps* & it's ready to GO!"
& the interactive serial code... once I seen that inserting:
*beeps* 90 <enter> 10 <enter> 20 *beeps* <40 would start the motor at the minimum and progressively incremented it up to 90> ...
...I decided to implement this interation using remote buttons instead of the previously attempted loops...
1x Button for <10> (throttle 0%)
1x Button for <90> (throttle 100%)
and 2x button for increment/decrement by 10 units within that range.
At setup() I set lift fan velocity to 90 (max) and then I just went directly to 10 by pushing the respective button...
...and pushing the increment button after that... eventually led to me hearing the calibration/arming beep. I had however, to be persistant and try this procedure a few times, because either implementation isn't that good and/or I just had some timing issues in the first iterations.
--- Original post ---
I've been trying to control a brushless motor (EMAX CF2812) via ESC with arduino, but so far I've had limited sucess. I've managed to start the motor, but I can't seem to get reproducible results.
The first success I've got was by following the instructions here. From there I also got the following code:
/* * This code is in the public domain. * (Do whatever you want with it.) */ // Need the Servo library #include <Servo.h> // This is our motor. Servo myMotor; // This is the final output // written to the motor. String incomingString; // Set everything up void setup() { // Put the motor to Arduino pin #9 myMotor.attach(9); // Required for I/O from Serial monitor Serial.begin(9600); // Print a startup message Serial.println("initializing"); } void loop() { // If there is incoming value if(Serial.available() > 0) { // read the value char ch = Serial.read(); /* * If ch isn't a newline * (linefeed) character, * we will add the character * to the incomingString */ if (ch != 10){ // Print out the value received // so that we can see what is // happening Serial.print("I have received: "); Serial.print(ch, DEC); Serial.print('\n'); // Add the character to // the incomingString incomingString += ch; } // received a newline (linefeed) character // this means we are done making a string else { // print the incoming string Serial.println("I am printing the entire string"); Serial.println(incomingString); // Convert the string to an integer int val = incomingString.toInt(); // print the integer Serial.println("Printing the value: "); Serial.println(val); /* * We only want to write an integer between * 0 and 180 to the motor. */ if (val > -1 && val < 181) { // Print confirmation that the // value is between 0 and 180 Serial.println("Value is between 0 and 180"); // Write to Servo myMotor.write(val); } // The value is not between 0 and 180. // We do not want write this value to // the motor. else { Serial.println("Value is NOT between 0 and 180"); // IT'S a TRAP! Serial.println("Error with the input"); } // Reset the value of the incomingString incomingString = ""; } } }
It allows to interactively send signals (ints) to control the ESC. After a bit I've got some success by sending first a value of 10, followed by 55 (I believe I might have heard the arming beep then) and then I got the motor actually spinning with a value of 120. After a few more tests it seemed like that I would need a value equal or above 100 to make it spin. So, after analyzing the above code I've tried to write a stripped down code to programatically control the ESC, the code can be found below:
#include <Servo.h> Servo esc; void setup() { delay(1000); esc.attach(9); // attaches the servo on pin 9 to the servo object //delay(1000); Serial.begin(9600); esc.write(10); delay(1000); //esc.write(90); } void loop() { esc.write(100); //delay(3500); //esc.write(0); //delay(10000); }
At first, with this code or small variations I got success in making the motor run, alas today when I've tried again (with variations) no such luck. When back to the interactive code and managed to make the motor work with a sequence of inputs: 10, 90, 100, 0. However, after stopping the motor (sending zero) I was unable to start it again even with sending values above 100 without resetting the arduino...
So, does anyone can shed some light on what is happening here? How can I "tame" this beguilling ESC? :/
Further info:
Regarding ESC documentation the beep list found here seems to be the best that can be found.
Also rumaged the web for answers, but couldn't find anything that I could either wrap my head around or very enlightening :s
A long shot
After googling a little on your problem here I have this feeling that power-up sequence is important. Like, make sure your arduino is transmitting a servo signal, say 55, before you attach lipo power to the ESC. and first then, after "some time" start the arm sequence.
Dunno, I have no experience with RC ESC's yet.
me too
im trying to use the 30A model of this..from what i read the throttle must be under 10 when powered on. so have arduino write between 0 and ten. then power on the esc. wish i had my arduino i could be testing all this right along with you
Well... I had _some_ success
Well... I had _some_ success sending "90" two seconds after attaching the ESC on the setup() ... but could only managed to make it work once... again no reproducibility :/
So, the only thing I can conclude is that "90" is perhaps the arming value (a.k.a. neutral?) the question remains when should I send that value? or what is the best set of circumpstances to do so programatically :|
I guess I'll be having to lock the cat in the bedroom a few more times... :/
just an idea
why not use the arduino servo and pot sample code and mess with it that way?
you could get all the timing things down and be good to go
Mostly just a guess, but
Additional info
Good stuff.
Arming sequence: When the arduino is in the setup function "setup(){}", I have had a lot of luck with stepping from 0 to 55 in steps of 5.
After arming use: Writing anything greater than 65 would get the motors turning.
Getting the motors to stop: If the motors were spinning and I wanted to stop them, I wrote 60. Here's the tricky part, if I wrote the value "0" to the motors, I would get unpredictable behaviour and the motors would fail to respond anymore until I disconnect/reconnect power.
For reference on the code used to arm (I used two (2) motor/esc's):
Useful no "zero" tip
Well, earlier this morning before I've left to work I had the oportunity to do some 20 minutes worth of testing...
So using the "interactive code" I get the "esc-has-detected-a-lipo" beep intial beep once I connect the battery. Afterwards, I kept sending randomly several values like 10, 50, 55, 60 5, etc. all below 90 and nothing happened. After it I finally send 90 and I got what I assume is the "arming beep". Then sending 100 would make the motor spin, following your tip writing 90 again (or below -- but not zero -- which I haven't tried this time) would make them stop, but I could start the motor again just by sending 100 or above.
So, I wrote a simple sketch:
- setup: attach esc, wait 2 sec, send 90
- loop: send 100
Uploaded it... and it work... HOWEVER... I've pulled the usb cable to stop it, and variants of re-plugging it, reseting the arduino, re-uploading the code and disconnecting/connecting the battery haven't managed to putting it to work again.
So, I'm still stumped regarding programatically arming the ESC... and don't quite understand what you mean with this:
"Arming sequence: When the arduino is in the setup function "setup(){}", I have had a lot of luck with stepping from 0 to 55 in steps of 5."
And I only can guess it will get uglier when I try to add all the rest of the setup regarding r/c comms and stuff :s
code snippet
for(int I = 0;I <= 55; I++){
esc.write(I);
}
delay
You will need some delay in that loop as well. otherwise it will be done way faster than anything can be sent on the servo line
yeah
the thing is... I actually don't see the purpose of having that on setup()... wouldn't it be ran just once?
The problem I seem to see here is "how to programatically find the right window of oportunity to arm the ESC". :s | http://letsmakerobots.com/content/solvedsort-works-far-perfect-how-properly-control-armcalibratecommand-hk-20-esc-arduino | CC-MAIN-2015-18 | refinedweb | 1,516 | 64.3 |
The QScriptContext class represents a Qt Script function invocation. More...
#include <QScriptContext>
This class was introduced in Qt 4.3..
This enum specifies types of error.
This enum specifies the frameution()).().
Returns the callee. The callee is the function object that this QScriptContext represents an invocation of.
Returns the QScriptEngine that this QScriptContext belongs to..
Returns the parent context of this QScriptContext.
Sets the activation object of this QScriptContext to be the given activation.
If activation is not an object, this function does nothing.
See also activationObject().
Sets the `this' object associated with this QScriptContext to be thisObject.
If thisObject is not an object, this function does nothing.
See also thisObject().
Returns the frameution state of this QScriptContext.
Returns the `this' object associated with this QScriptContext.
See also setThisObject().().
This is an overloaded function.
Throws an error with the given text. Returns the created error object.
See also throwValue() and state().
Throws an exception with the given value. Returns the value thrown (the same as the argument).
See also throwError() and state().
Returns a string representation of this context. This is useful for debugging.
This function was introduced in Qt 4.4. | https://doc.qt.io/archives/qt-4.7/qscriptcontext.html | CC-MAIN-2021-17 | refinedweb | 192 | 55.91 |
Java:Tutorials:VolatileImage
Contents
- 1 Introduction
- 2 How to Use VolatileImage
- 3 VolatileImage Techniques
- 4 More Information
- 5 References
Introduction
What is a VolatileImage?
VolatileImage is a relatively new object in the Java API. It differs from other Image variants in that if possible, VolatileImage is stored in Video RAM (VRAM). This means that instead of keeping the image in the system memory with everything else, it is kept on the memory local to the graphics card. This allows for much faster drawing-to and copying-from operations. There is a price to pay for this advantage though. On certain occasions, the image contents can be lost. Knowing this, the Java developers gave us ways to handle this.
Why Would a VolatileImage be Lost?
"It's true: VolatileImages can (and quite often will) go away and the API for VolatileImage was developed specifically to deal with that problem. All of the loss situations currently occur only on Windows.
You would think that we would actually be notified prior to these problems, so that we could prevent the loss, or backup the image, or something. But you'd be wrong; we only find out from Windows that there is a problem the next time we actually try to use the image. Surface loss situations arise from situations such as:
- Another app going into fullscreen mode
- The display mode changing on your screen (whether caused by your application or the user)
- TaskManager being run
- A screensaver kicking in
- The system going into or out of StandBy or Hibernate mode
- Your kid just yanked the power cord to the machine
Okay, so that last one applies to all platforms. And there's not much that the VolatileImage API can do to help you there. Try locking the door to your office." [1]
Why Should I use a VolatileImage?
Chances are if you're reading this, you're a game programmer. In most cases, this will mean that you want to be able to squeeze as much performance out of your system as possible. Using a VolatileImage helps you to do that by letting your video card take care of some of the graphical processing. Not only does a VolatileImage keep the information closer to where it's needed, but it also avoids having to send it over the system bus.
"Imagine trying to render 60 frames per second in an animation application, with a screen size of 1280x1024 and 32bpp screen depth; that's about 5 megs of data per frame * 60 frames = 300 MBytes of data moving across the bus, just to copy the buffer to the screen, not including anything else that needs to happen over the bus or through the CPU/cache/memory."[2]
How to Use VolatileImage
There are three main methods you need to worry about:
createCompatibleVolatileImage()
A VolatileImage is meant to optimize performance. In order to achieve this, the image data must be compatible with the hardware and the settings. That is, if the user's display is set to use 32-bit colour, then a 32-bit VolatileImage must be created so that it doesn't need to be converted to a 32-bit image later. That's why if the display mode changes, your VolatileImage will be lost.
The createCompatibleVolatileImage() method does not belong to VolatileImage, but rather GraphicsConfiguration. The GraphicsConfiguration object represents the display settings of the user's hardware. In order to create a VolatileImage, you need to obtain the current GraphicsConfiguration. Code Example 1 shows the syntax to retrieve the current GraphicsConfiguration.
Code Example 1
import java.awt.*; import java.awt.image.VolatileImage; ... GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); ...
Important Decisions
Once you have your GraphicsConfiguration, you can create your VolatileImage. At this point, you have a couple of choices to make:
- How big will the VolatileImage be?
- Do you want it to be hardware-accelerated? (Yes, hopefully.)
- Will your image have transparent regions?
- Will your image be translucent?
These choices are encapsulated in the various overridden versions of the method:
createCompatibleVolatileImage(int width, int height)
- Returns a VolatileImage with a data layout and color model compatible with this GraphicsConfiguration.[3]
createCompatibleVolatileImage(int width, int height, ImageCapabilities caps)
- Returns a VolatileImage with a data layout and color model compatible with this GraphicsConfiguration, using the specified image capabilities.[3]
createCompatibleVolatileImage(int width, int height, ImageCapabilities caps, int transparency)
- Returns a VolatileImage with a data layout and color model compatible with this GraphicsConfiguration, using the specified image capabilities and transparency value.[3]
createCompatibleVolatileImage(int width, int height, int transparency)
- Returns a VolatileImage with a data layout and color model compatible with this GraphicsConfiguration, using the tranparency value.[3]
The ImageCapabilities object seems to only exist to specify/determine if the VolatileImage is accelerated. You probably don't need to worry about it.
The transparency parameter can be used to specify if the VolatileImage will be opaque, transparent, or translucent. These can be specified with the constants, Transparency.OPAQUE, Transparency.BITMASK, Transparency.TRANSLUCENT, respectively.
OPAQUE should be used if there will be no transparency. BITMASK should be used if there are transparent regions, but the image is otherwise opaque. TRANSLUCENT images can have pixels that are fully or partially transparent. Translucent images are a little bit trickier, so they have their own section.
validate()
Now that the VolatileImage has been created, we need to make sure we can use it. The validate() method has two uses:
- After creation, validate() puts the VolatileImage into a known state, effectively clearing it, so it can be drawn to without artifacts showing up.
- Before any operation is done to the VolatileImage, it makes sure that the image is still there and usable.
validate() takes one parameter, a GraphicsConfiguration object. This is to ensure that the VolatileImage is still compatible with the current settings.
validate() can return three different results:
- VolatileImage.IMAGE_OK
- The VolatileImage is still okay, and can be used.
- VolatileImage.IMAGE_RESTORED
- Something happened to the VolatileImage that may have affected its contents. If you're just going to clear the contents and draw over it, this doesn't matter. If you're copying from it, you should redraw the image first.
- VolatileImage.IMAGE_INCOMPATIBLE
- The VolatileImage is no longer in a usable state. You should recreate the VolatileImage.
Depending on what validate() returned, you might have to redraw or recreate your image. It can be easier to just recreate the image in both cases. Code Example 2 gives an example of creating a VolatileImage.
Code Example 2
Creating a VolatileImage.
import java.awt.*; import java.awt.image.VolatileImage; ... private VolatileImage createVolatileImage(int width, int height, int transparency) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); VolatileImage image = null; image = gc.createCompatibleVolatileImage(width, height, transparency); int valid = image.validate(gc); if (valid == VolatileImage.IMAGE_INCOMPATIBLE) { image = this.createVolatileImage(width, height, transparency); return image; } return image; } ...
You might notice that the potential for infinite recursion exists. In practice, if the VolatileImage can't be created in VRAM, then it will resort to using system memory, which will never be incompatible. Once we cover contentsLost(), a more inclusive example can be shown.
Code Example 3
Copying from a VolatileImage.
import java.awt.*; import java.awt.image.VolatileImage; // From the Code Example 2. VolatileImage vimage = createVolatileImage(800, 600, Transparency.OPAQUE); ... public void draw(Graphics2D g, int x, int y) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); // Since we're copying from the VolatileImage, we need it in a good state. if (vimage.validate(gc) != VolatileImage.IMAGE_OK) { vimage = createVolatileImage(vimage.getWidth(), vimage.getHeight(), vimage.getTransparency()); render(); // This is coming up in Code Example 4. } g.drawImage(vimage,x,y,null); } ...
contentsLost()
The contents of a VolatileImage can be lost at anytime, so what happens if it happens while you're drawing to it? You'd like to know so that it can be redrawn. This is where contentsLost() comes into play. It will tell you if anything has happened to the VolatileImage since you last called validate(). This method should be called at the end of your drawing routine.
It is common to use a do...while loop in for this. If the contents are lost, then you'll have to redraw. Using a do...while loop rather than a while loop ensures that the image is drawn atleast once, and as many times as necessary before continuing.
It looks like this could cause an infinite loop, but in practice, it is very unlikely. Considering that your drawing routine will likely run fast enough so that it runs about 60 times per second, and what causes the contents to be lost, you can see that the contents being lost during your drawing routine will be a rare occurrence. Code Example 4 shows a drawing routine.
Code Example 4
Drawing to a VolatileImage.
import java.awt.*; import java.awt.image.VolatileImage; // From the Code Example 2. VolatileImage vimage = createVolatileImage(800, 600, Transparency.OPAQUE); ... public void render() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); Graphics2D g = null; do { int valid = vimage.validate(gc); if (valid == VolatileImage.IMAGE_INCOMPATIBLE) { vimage = createVolatileImage(width, height, transparency); } try { g = vimage.createGraphics(); mySprite.draw(g); // This is assumed to be created somewhere else, and is only used as an example. } finally { // It's always best to dispose of your Graphics objects. g.dispose(); } } while (vimage.contentsLost()); }
VolatileImage Techniques
Using a VolatileImage isn't straight-forward, even after you make sure its content is valid. Here are some techniques have been found useful.
The Toolkit is old. The guys at Sun don't really want us to use it anymore, in favour of ImageIO. Unfortunately, the read() methods in ImageIO return BufferedImage. There's no way to get around that. However, you can load a file into a BufferedImage, and then draw the contents of the BufferedImage onto a VolatileImage. Code Example 5 shows how to do this.
Code Example 5
How to load a file into a VolatileImage.
import java.io.*; import java.awt.*; import java.awt.image.VolatileImage; import java.awt.image.BufferedImage; public VolatileImage loadFromFile(String filename) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration(); // Loads the image from a file using ImageIO. BufferedImage bimage = ImageIO.read( new File(filename) ); // From Code Example 2. VolatileImage vimage = createVolatileImage(bimage.getWidth(), bimage.getHeight(), Transparency.OPAQUE); Graphics2D g = null; try { g = vimage.createGraphics(); g.drawImage(bimage,null,0,0); } finally { // It's always best to dispose of your Graphics objects. g.dispose(); } return vimage; }
How to Make Transparent Regions in a VolatileImage
Once you try the code from Code Example 5, you might notice that you get white in the regions that are supposed to be transparent. Did you notice that the transparency parameter is Transparency.OPAQUE? Good. It still doesn't work if you try Transparency.BITMASK, does it? When validate() is called in the createVolatileImage() method, it sets the VolatileImage to a known state. This means that it will clear it to white, in most cases. In order to get the transparency, you need to clear the VolatileImage to transparent. Code Example 6 demonstrates this.
Code Example 6
Clearing a VolatileImage to transparent before drawing to it.
// This uses the same code as from Code Example 5, but replaces the try block. try { g = vimage.createGraphics(); // These commands cause the Graphics2D object to clear to (0,0,0,0). g.setComposite(AlphaComposite.Src); g.setColor(Color.black); g.clearRect(0, 0, vimage.getWidth(), vimage.getHeight()); // Clears the image. g.drawImage(bimage,null,0,0); } finally { // It's always best to dispose of your Graphics objects. g.dispose(); }
Translucent Images
"To turn on acceleration of translucent images in 1.4 and 1.5 (using the DirectDraw/Direct3D pipeline):
:
- GraphicsConfiguration.createCompatibleImage(w,h, Transparency.TRANSLUCENT)
- Images loaded with Toolkit.getImage() that have a translucent color model
As of 1.5, translucent images created with a BufferedImage constructor can also be accelerated. To find out whether an image can be accelerated on a particular device, you can use the Image getCapabilities method (added in 1.5) to get an ImageCapabilities object, which you can query using the isAccelerated method. Note that a managed image gets accelerated only after a certain number of copies to the screen or to another accelerated surface.
The following code fragment illustrates the use of accelerated images. The fragment assumes that back buffer is a VolatileImage. BufferStrategy can);
Note: The translaccel property has no effect if the OpenGL pipeline is in use."[4]
The cited reference fails to mention that in order to use "-Dsun.java2d.translaccel=true", it must be used as a VM option. For example:
java -Dsun.java2d.translaccel=true MyProgram
But I Need BufferedImage.getSubImage()!
BufferedImage has a handy method, getSubImage(). Unfortunately, that's not available for VolatileImage. There are ways to get around this if you only need part of a VolatileImage though:
Method 1
You're probably loading an image from a file and then drawing to a VolatileImage, so if it is something like a character sprite, where there are multiple poses in one file, you can split it up into individual poses when you load the image, rather than taking part of the image when it's needed. An array or Vector can be used to store the individual images.
Method 2
If you have a large image that you wish draw part of to the screen, like a background, it's hard have it split into smaller pictures. Instead, you can start drawing the entire image offscreen such that the part you want ends up on the screen.
There is some inherent potential performance loss in this case, as you waste time drawing to something that isn't the screen.
More Information
References
- [1.0] Chet Haase's Blog - VolatileImage: Now you See it, Now you Don't, September 2003.
- [2.0] Chet Haase's Blog - VolatileImage Q&A, September 2003.
- [3.0],[3.1],[3.2],[3.3] Java Platform SE 5.0 API Specification - Class GraphicsConfiguration, 2004
- [4.0] System Properties for Java2D(TM) Technology, 2004. | http://content.gpwiki.org/index.php/Java:Tutorials:VolatileImage | CC-MAIN-2015-14 | refinedweb | 2,335 | 50.33 |
2694/how-is-ordering-of-transactions-done-in-block-in-hyperledger
Consensus is the key concept for validating the order of transactions in a block, on a blockchain network. The ordering is critical because many types of network transactions have dependency on one or more prior transactions.
In current version of hyperledger there is a leader who is responsible for ordering transactions before they are executed by other peers. A peer communicates and maintain the blockchain state and the ledger.
Such peers receive ordered state updates from the consensus service and apply them to locally held state. Peers connect to the channel and may send and receive messgaes on the channel.
The channel outputs the same messages to all connected peers and outputs them to all peers in the same logical order. The communicted messages are called the candidate transactions and are included later in the block.
There are two types to implement ordering:
1. ...READ MORE
Is your transaction actually called 'OrderPlaced' (in ...READ MORE
For hyperledger fabric you can use query ...READ MORE
The transactions in the network is ordered ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
This link might help you: ...READ MORE
Technically, it's not difficult at all, all ...READ MORE
OR | https://www.edureka.co/community/2694/how-is-ordering-of-transactions-done-in-block-in-hyperledger | CC-MAIN-2019-22 | refinedweb | 236 | 59.7 |
I am taking columns from a csv file , now I don't have the exact number of columns so I wish to use Double dimension array
so here is what I am doing
sub column_segregation
{
my ($file,$col) = @_;
use Text::CSV;
my @array_A2 = ();
open my $io,'<',$file or die "$!";
my $csv = Text::CSV->new ({ binary => 1 });
while (my $row = $csv->getline($io)) {
push @array_A2, $row->[$col];
}
close $io;
return (@array_A2);
}
[download]
so this routine will return an array , now i want each column should go to each corresponding column in Double dimension array. i.e. column 1 should go to column of 1 DD array and so on .
So I have never worked with DD array so how to put it in the DD array column is what I need help with <\n>
G'day torres09,
You asked about this less than 48 hours ago: indefinite number of columns
You were provided with code for doing this and links to documentation explaining about this.
How about you go back and read what's already been provided.
If there was something you didn't understand, either in the code examples posted or the documentation linked to, then ask a specific question about that issue.
-- Ken
I think, I don't understand the problem completely.
$csv->getline($io) already returns a ref to an array where, each entry "n" is the cell of column "n+1".
So this should already give you the correct array:
while (my $row = $csv->getline($io)) {
push @DD, $row;
}
[download]
$DD[$r][$c] should give you the entry in row "r+1" and column "c+1".
So I have never worked with DD array so how to put it in the DD array column is what I need help with
Hmm, some of the answer in indefinite number of columns show that, so Basic debugging checklist to Data::Dump::dd some data to find out which one is the one you want
Another example of working with arrays of arrays is in How to traverse a two dimentional array in a constructor? including a link to a free book which teaches this
You may view the original node and the consideration vote tally.
Also, you could google it.
I hope that helps.
-Michael
A foolish day
Just another day
Internet cleaning day
The real first day of Spring
The real first day of Autumn
Wait a second, ... is this poll a joke?
Results (427 votes),
past polls | http://www.perlmonks.org/index.pl?node_id=1044753 | CC-MAIN-2014-15 | refinedweb | 411 | 63.93 |
Step-by-step
Introduction
Today, IoT devices generate a humongous amount of data, which are extremely varied, noisy, time-sensitive and often confidential. In many scenarios, these data need to be processed in real-time to detect anomalies, filter events, enrich the data for machine learning and prediction. This requires an integration between the IoT Platform and Apache Spark. For example, Apache Spark can be used to analyze the vehicle telematics data, detect anomalies if any, and trigger a corresponding action back to the vehicle in real-time.
This recipe explains, how to configure the Spark service running in IBM Bluemix to receive data from IBM Watson IoT Platform in simple steps, to process the IoT data in real-time. The following diagram shows various components involved in the integration.
Where,
IBM Watson Internet of Things Platform is a fully managed, cloud-hosted service that makes it simple to derive value from Internet of Things (IoT) devices. The platform provides simple, but powerful application access to IoT devices and data.
Apache Spark is a powerful open source, general engine for big data processing, built around with speed, ease of use, and sophisticated analytics. Apache Spark Streaming is an extension of the core Spark API that enables scalable, high-throughput, fault-tolerant stream processing of live data streams. Spark Streaming receives live input data streams and divides the data into batches, which are then processed by the Spark engine to generate the final stream of results in batches.
Spark-Streaming-MQTT helps to receive data from any MQTT sources to Spark Streaming application.
Jupyter Notebook allows one to create and share documents that contain live code, equations, visualizations and explanatory text.
Register your Device(s) In Watson IoT Platform
In order to receive the device events in Spark, we need to setup the IBM Watson IoT Platform and register the device(s) first. This section shows how you can setup.
At this step, we have successfully created the IBM Watson IoT Platform service and registered the device(s) in it.
Publish Device Events
In order to receive the device events in Apache Spark, we need to configure the device to send the events to IBM Watson IoT Platform. This section shows how to send sample device events to the Watson IoT Platform.
- Download and install Maven and Git if not installed already.
- Open a command prompt and Clone the device-samples project using git clone as follows,
git clone
Navigate to the device-samples project, cd iot-device-samples/java/device-samples
- Build the project using maven as follows,
mvn clean package
(This will download the Java Client library for Watson IoT Platform, other required dependencies and starts the building process. Once built, the sample can be located in the target directory, for example, target/ibmiot-device-samples-0.0.1.jar)
- Modify the device.prop file present under target/classes directory structure, by entering the following device registration details that you noted in the previous step:
Organization-ID = <Your Organization ID>
Device-Type = <Your Device Type>
Device-ID = <Your Device ID>
Authentication-Method = token
Authentication-Token = <Your Device Token>
- Run the deviceeventpublish sample by specifying the following command:
mvn exec:java -Dexec.mainClass="com.ibm.iotf.sample.client.device.DeviceEventPublishWithCounter"
(The sample code is present here)
- This code makes the device to publish the events every 1 second each event contains a counter, name, cpu and memory usage of the process. Observe that the datapoint event-count is increased for every new event that gets published.
In this section, we have successfully started a device sample. Let’s consume and process these events by creating the Apache Spark application in the next section.
Setup IBM Data Science Experience and create a Jupyter notebook,
On-Board IoT Device Events to Spark
In this step, we will create the scala notebook application to onboard the device events to Apache Spark.
Generate API Key and Token of Watson IoT Platform
In order to connect Apache Spark service to IBM Watson IoT Platform to receive device events, we need to generate the API key and token first. This can be achieved by carrying out steps present in this section – Generate API Key in Watson IoT Platform.
Note down API Key and Authentication Token. We need these to connect the Spark application to Watson IoT Platform.
Create the notebook application to receive the device events in the Spark service,
- Go to the notebook, In the first cell, enter the following special command AddJar to upload the MQTT and spark-streaming-mqtt jars to the IBM Analytics for Spark service.
%AddJar -f
%AddJar -f
%AddJar -f
(The % before AddJar is a special command, which is currently available, but may be deprecated in an upcoming release. We’ll update this tutorial at that time. The -f forces the download even if the file is already in the cache)
- In the next cell, import the necessary classes and create the Apache Spark Streaming context as shown below. In this example, we set the streaming batch interval to 1 second.
import org.eclipse.paho.client.mqttv3._
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.mqtt._
import org.apache.spark.SparkConf
val ssc = new StreamingContext(sc, Seconds(1))
- Then, create the MQTT stream using the the spark-streaming-mqtt-connector service that is available in Github. We customized the connector from Apache Spark and added the following,
- Add the following code that creates the MQTT stream,
val lines = MQTTUtils.createStream(ssc, // Spark Streaming Context
"ssl://<your-org>.messaging.internetofthings.ibmcloud.com:8883", // Watson IoT Platform URL
"iot-2/type/+/id/+/evt/+/fmt/+", // MQTT topic to receive the events
"a:<your-org>:random", // Unique ID of the application
"<API-Key>", // API-Key
"<Auth-Token>") // Auth-Token
(Modify the above code with your Organization ID, API-Key and Auth-Token that you received earlier. The MQTT topic used in this code snippet subscribes to events from all the devices in the given Organization. Refer to the documentation if you want to control the subscription)
- In the next step, add the code to parse the topic and associate the messages with deviceId as shown below, Also start the streaming context such that it runs for every second.
/*
* The message topic and payload is split with space, so lets split the message with space
* and keep the deviceId as key and payload as value.
*/
val deviceMappedLines = lines.map(x => ((x.split(" ", 2)(0)).split("/")(4), x.split(" ", 2)(1)))
deviceMappedLines.print()
ssc.start()
ssc.awaitTermination()
- Then run the code all at once by going to Cell->Run All as shown below,
- Observe that, the Spark application maps the events with the deviceId, and outputs the event every second as shown below, In this case the device Id is SoftwareDevice.
In this step, we have successfully created a scala notebook application and received the events in Apace Spark.
Threshold based Anomaly detection
In this step, we will see how to detect anomalies based on threshold settings.
One can use the Filter operator to detect the threshold based deviations. The filter transformation removes tuples from the RDD by passing along only those lines that satisfy a user-specified condition.
- In the existing notebook, remove the line deviceMappedLines.print() and paste the following code that initially maps the JSON payload into thescala map and then filters the lines where thecpu usage is greater than 10%.
import java.util.Map.Entry
import com.google.gson.JsonElement
import java.util.Set
// Map the Json payload into scala map
val jsonLines = deviceMappedLines.map(x => {
var dataMap:Map[String, Any] = Map()
val payload = new JsonParser().parse(x._2).getAsJsonObject()
var deviceObject = payload
if(deviceObject.has("d")) {
deviceObject = payload.get("d").getAsJsonObject()
}
val setObj = deviceObject.entrySet()
val itr = setObj.iterator()
while(itr.hasNext()) {
val entry = itr.next();
try {
dataMap.put(entry.getKey(), entry.getValue().getAsDouble())
} catch {
case e: Exception => dataMap.put(entry.getKey(), entry.getValue().getAsString())
}
}
(x._1, dataMap)
})
/**
* Create a simple threshold rule. If cpu usage is greater than 10, alert
*/
val threasholdCrossedLines = jsonLines.filter(
x => {
var status = false;
val value = x._2.get("cpu")
if(value != null) {
if(value.get.asInstanceOf[Double] > 10.0) {
status = true
}
}
status
})
threasholdCrossedLines.print()
(The complete code is available here)
- Stop the previous job by clicking on the interrupt & restart kernel buttons.
- Then run the code all at once by going to Cell->Run All. Observe that the output line is printed only when the CPU usage crosses 10%.
In this step, we saw how to filter the lines where the CPU usage is greater than 10%. Similarly, you can filter rows based on other datapoints as well.
Compute Running Average
In this step, we will see how to compute running average of various data points that the IoT devices send.
- Open a new notebook
- Copy the code that calculates the running average from the Github and place it in the notebook.
- Modify the line that creates the MQTT stream with your Organization ID, API-Key and Auth-Token:
Open a new notebook
Copy the code that calculates the running average from the Github and place it in the notebook.
Modify the line that creates the MQTT stream with your Organization ID, API-Key and Auth-Token:
- Then run the code all at once by going to Cell->Run All as shown below, (you may need to interrupt & restart the kernel if there is an instance running already)
- Observe that each line prints the average along with the number of events consumed so far.
At this step, we have successfully computed the running average of individual datapoints that the device sends.
Conclusion
In this recipe, we demonstrated how to connect Apache Spark Streaming application to IBM Watson IoT Platform and receive device events in real-time. Developers can look at the code made available in the Github repository to understand whats happening under the hood. Developers can consider this recipe as a template for integrating Apache Spark with IBM Watson IoT Platform.
Where to go from here?
- Go through IBM Watson IoT Real-Time Insights recipe that enables one to perform analytics on real-time data from the IoT devices and gain diagnostic insights. Though the recipe is written to analyze the vehicle data, the same can be used as a template to derive insights from any IoT data.
- Go through Engage Machine Learning for detecting anomalous behaviors of things recipe that showcases how one can make use of the Predictive Analysis service, available on the IBM Bluemix, to determine the hidden patterns on the events published by IoT devices, on the IBM Watson IoT Platform.
Hi,
Would it be possible to update the GitHub fork to use the latest version of the park Project External MQTT Assembly library?
Regards,
Kevin | https://developer.ibm.com/recipes/tutorials/spark-streaming-ibm-watson-iot-platform-integration/ | CC-MAIN-2017-22 | refinedweb | 1,798 | 53.1 |
When Panic unveiled their status panel to the world, I was both impressed and inspired. In today's tutorial and screencast, I'll show you how to built a similar status board!
Overview
Here's what our status board will have: at the top, there will a pageviews graph; it would take another tutorial to get that data from Google Analytics, so for today, we'll just use some random data. Then, we'll pull in our upcoming events from Google Calendar. We'll have a project status table, pulling data from a database. Finally, we'll show tweets from our "company" and other people mentioning our company. Let's go!
Before we get started, I should mention that the icons I use in this project come from Smashing Magazine's free set entitled On Stage; unfortunately, I can't include them in the demo files, but here's a list of the file names I renamed them to for the project (most of the project depends on the file names); I've resized the icons to 64x64px; it should be obvious as you go through the tutorial which icons belong where.
- bazquirk.png
- behind.png
- complete.png
- foobar.png
- gadget.png
- gizmo.png
- jane.png (editted buddy.psd)
- joe.png (editted buddy.psd)
- john.png (editted buddy.psd)
- ontime.png
- sally.png (editted buddy.psd)
- waiting.png
- widget.png
Step 1 Start it with the Markup
While our finished page will have dynamic content, we'll build the interface first by using static content to get everything set up, and then we'll work on the server-side code later.
Here's our preliminary shell:
<!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <title>Status Board</title> <link rel="stylesheet" href="default.css" /> </head> <body> <div id="wrap"> <div id="data"></div> <div id="projects"></div> <div id="twitter"></div> </div> </body> </html>
Not hard at all: three divs in a wrapping div. Let's look at
div#data right now. Inside it, we'll put two divs:
<div id="visits"></div> <div id="schedule"> <h1>Schedule</h1> <ul> <li><em>3/22</em>Meet with Chris <small>details go here</small></li> <li><em>3/26</em>Holiday</li> <li><em>4/15</em>Foobar Deadline</li> <li><em>5/24</em>Office Party</li> </ul> </div>
We'll fill in
div#visits with JavaScript in a while. As for
div#schedule, we've put in a list. Later, we'll pull this data from Google Calendar, but this will give us something to build the interface on. The important part is that we've wrapped the event date in
em tags and the event details in
small tags.
The next main section is
div#projects. This will show us the latest information about the projects our little imaginary company is working on. Just like the schedule, we'll be pulling this in from a data source (a database, in this case); for now, it's just a static table:
<table> <tbody> <tr> <td><img src="" /></td><td>Gizmo</td> <td><img src="" />On Time</td> <td>Joe Sally</td> </tr> <tr> <td><img src="" /></td><td>Widget</td> <td><img src="" />Behind</td> <td>John Joe Jane</td> </tr> <tr> <td><img src="" /></td><td>Gadget</td> <td><img src="" />Complete</td> <td>Sally Jane</td> </tr> <tr> <td><img src="" /></td><td>Foobar</td> <td><img src="" />Waiting</td> <td>John Joe</td> </tr> <tr> <td><img src="" /></td><td>Bazquirk</td> <td><img src="" />On Time</td> <td>Sally Jane Joe</td> </tr> </tbody> </table>
The
div#twitter will show us two groups of tweets: those made by our company, and those mentioning our company. We'll use Remy Sharp's twitterlib to do this. Here's the markup we'll need:
<div id="our_tweets"></div> <div id="their_tweets"></div>
Finally, we'll import the scripts we're using:
- jQuery
- twitterlib
- jQuery Flot Plugin
- ExplorerCanvas for IE (needed for Flot)
- jQuery Pause / Resume Animation Plugin
Of course, in production, you would put all these into one file.
<script type="text/javascript" src=""></script> <script type="text/javascript" src="js/twitterlib.min.js"></script> <!--[if IE]><script type="text/javascript" src="js/excanvas.compiled.js"></script><![endif]--> <script type="text/javascript" src="js/jquery.flot.min.js"></script> <script type="text/javascript" src="js/jquery.pauseanimate.js"></script> <script type="text/javascript" src="js/statBoard.js"></script>
The last file here,
statBoard.js will be our own creation.
Full Screencast
Step 2 Prettify it with the CSS
Before we start the CSS, here's what our finished product will look like; this should make the CSS a bit clearer.
First, we'll set up the body and h1, as well as set all our main content divs to contain their children.
body { background: #f3f3f3; font:bold 25px/1.5 'Helvetica Neue', Arial, 'Liberation Sans', FreeSans, sans-serif; color:#494949; } h1 { margin:0; padding:0; font-size:40px; } #wrap > div { overflow:hidden; }
Next, let's consider that first content div, which has an id of
data.
#data { margin-bottom:40px; } #visits { width:48%; margin-right:2%; float:left; font-size:12px; } #tooltip { position: absolute; display:none; padding: 2px 5px; background:#494949; color:#fefefe; border-radius:15px; -moz-border-radius:15px; -webkit-border-radius:15px; }
We'll give that div a bottom margin of 40px, just for breathing. Then we'll turn to its first child,
div#visits: float it to the left, set its width and right margin, and reduce the font size.
Where's this tooltip div coming from? It will be inserted when we create the analytics graph using a jQuery plugin. Here, we're setting the visual styles, as well as positioning it absolutely and hiding it. When we hover over points on our chart, it will be positioned and then fade in.
Let's look at
div#schedule next:
#schedule { float:left; background:#494949; color:#f3f3f3; width:44%; padding:3%; overflow:hidden; border-radius:15px; -moz-border-radius:15px; -webkit-border-radius:15px; } #schedule ul { list-style-type:none; margin:0; padding:0; } #schedule li { margin-bottom:5px; width:1000px; } #schedule em { font-style:normal; background:#aa3636; margin-right:10px; display:inline-block; width:50px; padding:0 10px; border-radius:15px; -moz-border-radius:15px; -webkit-border-radius:15px; } #schedule small { font-size:12px; color:#bababa; font-style:italic; }
This shouldn't be too hard to figure out; we want
div#schedule to be to the right of
div#visits, so we float it to the left and make sure the width + padding will equal 50%. Then add some colour and shave off the corners. The
overflow:hidden is important. Remember that we'll be pulling in the event details; we don't want the details to wrap to more than one line, so we'll let them overflow and then hide the overflow.
The styling for the
ul and
li are pretty simple; we've given the
li a width of 1000px so that those details won't wrap.
Next up we have the
ems inside
div#schedule. This is where our dates will go. We remove the usual italic-ness by setting the font-style to normal. By setting the display to inline-block we can set a width on 50px; since we're showing the date in the format m/d, this should look good in all cases. And of course, round the corners.
Finally, for the details, we're using the
small tag; we'll set font-size, font-style, and colour.
The next main section of our status board is
div#projects.
#projects table { width:100%; border-spacing:5px; } #projects td { padding:2px; background:#efefef; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; } #projects td:not(:last-child) { text-align:center; } #projects img { vertical-align:middle; }
We'll make sure our table takes up the entire width of the page; we'll also give the cells some margin with
border-spacing. We'll give each cell some padding and slightly round the corners. Then, let's use some CSS3 selectors to center the text in every cell expect the last one; if the browser doesn't support :not() or :last-child, this rule will be ignored, and all the cells will stay left-aligned: not a big deal. Finally, we'll vertically center the images.
We only have the twitter div left:
#twitter > div { overflow:hidden; font-size:20px; } #twitter ul { list-style-type:none; width:5000px; position:relative; } #twitter li { float:left; margin-right:10px; } #twitter img { vertical-align:middle; margin-right:10px; border:0; height:20px; width:20px; }
Currently, our
div#twitter has only two empty divs within. We'll load the tweets with JavaScript soon, but here's what we want to happen: each
div within
div#twitter will be a marquee, scrolling tweets across the screen. Therefore, we'll set those
divs to hide their overflow, and also set their font to 5px less than the rest of the page. For the lists, we'll remove the bullets, position it relatively (so we can animate the right positioning to do the marquee) and set the width to 5000px; I'll explain the width once we get to the JavaScript. Each list item (each tweet) will be floated left and given a bit of right margin. Finally, the images (we'll be displaying twitter profile images) are styled appropriately.
Step 3 Interact with it with the JavaScript
On to the JavaScript! So we don't clutter up the global namespace, we'll create a single function that will return the methods of our status board. Here's the shell we'll start with:
var statBoard = function () { return { graphVisits : function (selector) {}, twitterize : function (selector, fn, subject) {}, iconizeWorkers : function (selector) {} } }
Let's build out
graphVisits first; you'll probably want to pull in analytics from Google Analytics or your choice of stats app. However, we're just going to generate some random data for our example.
First, we'll set up our variables:
var el = $(selector), data = [], prev = null, showTooltip = function (x, y, contents) { $('<div />', { id : 'tooltip', text : contents, css : { top: y + 5, left: x + 5 } }).appendTo('body').fadeIn(200); };
Respectively, we've got the element that we'll insert the graph into, the array of data we'll pass to the Flot jQuery plugin,
prev, which you'll see in use, and a showTooltip function. This creates that
div#tooltip that we styled earlier, appends it to the body, and fades it in.
el.height($('#schedule').outerHeight()); for (i = 0; i < 32; i++) { data.push([new Date(2010, 2, i).getTime(), Math.floor(Math.random() * 6000)]); }
Next, we set the height of the element that will contain the graph; the flot plugin requires this. We set it to the same height of
div#schedule; jQuery's outerHeight method returns the height of the object including its padding and border. Then, we'll fill up our array
data; the flot plugin accepts an array of arrays, each inside array having an x and y coordinate. For our x-coordinates, we're going to use a JavaScript date; the values we pass into the Date constructor are the year, month, and day (there are more, to set the time). We're setting the year to 2010, and the month to March (it's zero based, so Jan = 0). This will allow us to have dates in the bottom. We'll set the y-coordinate to a random number.
(Note: In the screencast, I mistakenly said that the year parameter was based on the Unix epoch, so that putting 10 would result in 1980; this is incorrect; what I've explained above it right.)
$.plot(el, [{ data: data, color:'#494949', lines : { show: true }, points : { show : true} }], { xaxis : { mode : 'time', timeformat : '%b %d' }, grid : { hoverable : true, clickable : true } });
Now we create the graph; we'll call the plot method and pass in the element that will hold the graph as the first parameter. The second parameter is an array, with only one object: the data will be our data array, the color will be the color of our graph line; then, we set the lines and points objects to show : true; lines will "connect the dots" on our graph, and points will make each datapoint more prominent. We could put miltiple objects like this one in the second-parameter array to chart multiple sets of data.
The last parameter is another object; it sets some properties on the graph. We'll set the x-axis to be in time mode; the timeformat is how we want the date to be formatted. According to the Flot documentation, "%b %d" will give use the month and day. Then, we set the grid enable hoverable and clickable.
el.bind('plothover', function (event, pos, item) { if (item) { if (prev != item.datapoint) { prev = item.datapoint; $('#tooltip').remove(); showTooltip(item.pageX, item.pageY, item.datapoint[1]); } } else { $('#tooltip').remove(); prev = null; } });
The next step is to build the tooltip functionality. The
plothover event is fired whenever you hover over the graph, and it passes three parameters to event handlers: the event, the position, and the datapoint you're hovering over. First, we'll check to see if we're on an item. If we are, we'll check to see if
prev does not equal the position of the point. If it doesn't that means we were not on this point at the last
plothover (we could move around on one item, remember). Therefore, we'll record which point we're on, make sure the tooltip isn't showing somewhere else, and show the tooltip in the new position. If
prev does equal the current datapoint, we don't need to do anything, because the tooltip is already showing. Finally, if we're not on a point, we'll make sure the tooltip isn't showing and set
prev back to null.
That's the end of our
graphVisits function; let's move on to our
twitterize function:
twitterize : function (selector, fn, subject) { var container = $(selector);
Twitterize takes three parameters: the selector of the element to load the tweets into, the name of the function we want to call in the twitterlib library, and the subject of our twitter call; this could be a username if we're using the timeline function, or it could be a search string if we're using the search function.
Once we're in the function, we'll get the tweet container.
twitterlib[fn](subject, { limit : 10 }, function (tweets) { var list = $('<ul />'), i, len = tweets.length, totalWidth = 0;
Next, we call twitterlib. We use the function name passed in, and set the subject as the first parameter. Then, we use the options object to tell the library to only get us the ten latest tweets to match our request. Finally, we add a callback function, which takes the tweets we get from twitterlib. First things first, we set our variables. You'll see them all in use.
for (i = 0; i < len; i++ ) { $('<li><a><img/></a></li>') .find('a') .attr('href', '' + tweets[i].user.screen_name + '/status/' + tweets[i].id) .end() .find('img') .attr('src', tweets[i].user.profile_image_url) .end() .append(this.ify.clean(tweets[i].text)) .appendTo(list); } container.append(list);
Now we loop over each tweet in the group. We'll make an HTML fragment of a list item and an anchor-wrapped image inside. We find the anchor, set the
href, and use
end() to go back to the
li. Then we find the image, set the source, and go back to the list item. Finally, we append the text of the tweet to the list item, which will put it in after the anchor. We run this text through
twitterlib.ify.clean; this will link up the links, mentions, and hashtags. Then we'll append the list item to the unordered list we created.
When we've worked through all our tweets, we'll append the list to the container.
Flashback: remember how we set the width of
#twitter ul to 5000px? We did this so that each tweet would be on a single line, and wouldn't wrap. This is because we're now going to get the width of each list item.
$('li', list).each(function (i, el) { totalWidth += $(el).outerWidth(true); }); list.width(totalWidth);
We'll loop through each list item (we can use the list as a context parameter) and use the
outerWidth function to get the width. Just like
outerHeight,
outerWidth includes the border and padding, and (since we've passed in
true) the margins. We add all those widths to our
totalWidth variable. Now totalWidth is the right width for our list, so we'll set that.
function scrollTweets() { var rand = totalWidth * Math.floor(Math.random() * 10 + 15); list.startAnimation({ right: totalWidth }, rand, 'linear', function () { list.css('right', - container.width()); scrollTweets(); }); } scrollTweets();
Next order of business: get that list scrolling. We'll calculate the scrolling speed by multiplying the totalWidth by a random whole number between ten and fifteen. Then, we do the animation. Normally, we'd use the
animate function, but we're using the pauseanimate plugin, so we use the function
startAnimation. We want to animate the right value to totalWidth. The duration parameter gets the random number. We'll set the easing to 'linear'; by default, it is 'swing,' which will ease in at the beginning and out at the end. Lastly, a callback function: we'll set the right position of our list to negative the container width. This will push it to the right of the screen. Then, we'll call our scrollTweets function so the cycle restarts.
Outside our
ScrollTweets function, we'll call it to get things started.
The last part of
twitterize is the hover events:
list.hover(function () { list.pauseAnimation(); }, function () { list.resumeAnimation(); }); }); // end of twitterlib call
When we hover over our tweets list, we'll use the pauseanimate plugin to pause the animation temporarily. We'll use the resumeAnimation function in the mouseout function. That's the end of
twitterize!
Our last function will swap out the workers' names for their images.
iconizeWorkers : function (selector) { $(selector).each(function (i, el) { var el = $(el), workers = el.text().split(' '), imgs = ''; $.each(workers, function (i, val) { imgs += '<img src="' + val.toLowerCase() + '.png" alt="'+ val + '" />'; }); el.html(imgs); }); }
It isn't too complicated; we'll get the elements matching the selecor that's passed in and iterate over each of them. We get their content, spliting it at the spaces, and store that in an array called
workers. Then, for each worker, we append an image to the imgs string, which uses the names to get the images. Then, we replace the names with the imgs string, using jQuery's html method.
Of course, we have to call our methods from within our HTML:
<script type="text/javascript"> var board = statBoard(); board.graphVisits('#visits'); board.iconizeWorkers('#projects tr td:last-child'); board.twitterize('#our_tweets', 'timeline', 'nettuts'); board.twitterize('#their_tweets', 'search', 'nettuts'); </script>
Step 4 Power it with PHP
The final stretch: getting the data in with PHP. First let's get the project data from a database. This requires that's we've made a database. You're probably pretty familiar with the process: I fired up PhpMyAdmin and made a database called 'projects.' Then, I created a table called 'project_status.' This has four fields: id (the auto-incrementing primary key), name, status, and workers. Here's the data I put in:
The function that gets this data isn't hard. Create a file called
statboard.php and let's get into it!
function getProjects() { $sql = new mysqli('localhost', 'root', '', 'projects') or die('could not connect'); $result = $sql->query("SELECT * FROM project_status"); $html = ""; while ($row = $result->fetch_object()) { $name = ucwords($row->name); $status = ucwords($row->status); $img = str_replace(" ", "", $row->status); $html .= "<tr><td><img src='->name.png' alt='$name' /></td>"; $html .= "<td>$name</td><td><img src='' alt='$status' /> $status</td>"; $html .= "<td>$row->workers</td>"; } return $html; }
First we create an instance of the mysqli class and connect it to our databases. Next, query the database for all the rows. We'll create a string called
$html, which we'll return at the end. Then we'll use a while loop to go over each row that we recieved. In our loop, we set three variables. We get the name and status, and use the PHP function
ucwords to capatlized the first letters of each word. Then, we get the status. We want to use this status as the name of the status icons, so we'll use
str_replace to remove any spaces in the status label. Finally, we concatenate the table row together. These three lines will produce the same HTML we used when prototyping.
Once we've looped through each row, we'll return the HTML string. To use this on our page, we'll first have to get
statBoard.php:
<?php require('statBoard.php'); ?> <!DOCTYPE html>
Then, we'll remove the table we hard-coded earlier and add this in its place:
<table> <?php echo getProjects(); ?> </table>
Our last job is to pull the schedule in from Google Calendar; first, you'll need to set your calendar to public; then, you'll need to get the XML feed for the calendar.
We'll do this in two functions; let's begin the first:
function parseCalendarFeed($feed_url, $count = 4) { $content = file_get_contents($feed_url); $x = new SimpleXmlElement($content); $entries = $x->entry; $arr = array();
Meet the
parseCalendarFeed function; it takes two parameters: the feed URL, and the number of items we want to get. We start by getting the content from the URL and create a SimppleXmlElement with it. If you inspect that object, you'll see that the events on the caledar are within the
entry element; we'll store that for later use. Finally, we'll created the array that we'll return at the end.
for ($i = 0; $i < count($entries); $i++) { $item = explode("<br />", $entries[$i]->content); array_unshift($item, (string)$entries[$i]->title);
Next, we'll loop over each item in
$entries; we want to get the content element and the title element. There's a problem with the content element, however; it's formatted like this:
When : [date here] <br /> <br /> Event Status: confirmed <br /> Event Description: [description here]
So, we'll use the php explode method to break the it into an array, called
$item, with each line as a member of the array. Then, we'll get the title of the entry and use array_unshift to add it to the front of
$item.
When that's done, we'll have an array that looks like this:
array ( [0] => [event title] [1] => When: [the date] [2] => [3] => Event Status: [the status] [4] => Event Description: [the description] )
foreach($item as $k => $v) { if ($k === 2 || $k === 3) { unset($item[$k]); } else { $temp = explode(":", $v); $item[$k] = (isset($temp[1])) ? trim($temp[1]) : $temp[0]; } }
Now we loop over each member of the
$item array; we don't need members with index 2 or 3, so we'll unset those. For the rest of the items, we'll split them at the comma. We have to use a ternary expression to resset the value, though, because the first item (the title) doesn't have a comma. If there's a second item in the temporary array, we'll set the value in the
$item array to the second part, which holds the info we want. If it doesn't have a second piece (which will be the case for the title), we'll use the first. Now our array looks like this:
array ( [0] => [event title] [1] => [the date] [4] => [the description] )
Perfect . . . except that the indices are incorrect.
$item = array_values($item); $item[1] = explode(" ", substr($item[1], 4, 6)); $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); $item[1][0] = array_search($item[1][0], $months) + 1; $item[1] = implode($item[1], '/'); array_unshift($arr, $item); } // end for $arr = array_slice($arr, 0, $count); return $arr; } // end parseCalendarFeed
To take care of the indices, we use the array_values function we reset them. Now the only thing left is for format the date. We'd like the date to be in the format 'm/d.' The date has an index of 1 in our item array, so we'll set explode that member; but we don't explode the whole member. We get a substring of it, starting at character index 4, and going for 6 characters. This will give us the month name and the day number.
We'll need to compare the month name against another array, so we create the
$months array. Then, we set
$item[1][0] (the month name) to the index of the month name in
$months plus one. We use the function
array_search to get the right index, and add one because the array is zero-based. Finally, we'll implode the array, which joins the members, passing in '/' as the separator. Now our date is correctly formatted. The last thing to do is put it into
$arr; we use
arrayunshift to put it onto the beginning of the array. Once we finish working with all the entries, they will be in the reverse order, which is what we want.
Finally, we'll slice the array so it only containers the number of elements we want. Then we can return it!
We use the
parseCalendarFeed function in our
getSchedule function:
function getSchedule() { $feed = ""; $events = parseCalendarFeed($feed); $html = ""; foreach($events as $event) { $html .= "<li><em>$event[1]</em> $event[0]"; if(isset($event[2])) { $html .= " <small>$event[2]</small></li>"; } else { $html .= "</li>"; } } return $html; }
Inside this function, we store the feed URL and pass it to
parseCalendarFeed; we'll start our
$html string and then loop through each event. This will generate the same HTML structure that we used when prototyping; we have to check for the existence of details (
$event[2]); if they are there, we add them; if not, we close the list item. Once we've looped through every one, we return the string
$html.
To call the calendar into the page, use this in place of the list items we hard-coded:
&ly;?php echo getSchedule(); ?>
Step 5: Admire it with Pride!
And that's it; that's our entire, working, data-pulling, twitter-scrolling status board! Hope you had fun, and let me know what you think. | http://code.tutsplus.com/tutorials/build-an-awesome-status-board--net-10502 | CC-MAIN-2014-15 | refinedweb | 4,425 | 71.44 |
First of all, thanks for a wonderful application. It is a joy to use.
I am trying to create a dynamical list which can be extended when you push a button (to build a pipeline in a later stadium). I accomplished this with the use of session state.
Each row of the list is outputted to the dashboard together with a button to remove this row, see figure and code:
import streamlit as st # Work around to store states across reruns import SessionState state = SessionState.get(rerun = False, prepro_steps=[]) if st.button('Add step'): state.prepro_steps += ['Step added {}'.format(len(state.prepro_steps))] for i,c in enumerate(state.prepro_steps): if st.button('Remove step {}'.format(i)): state.prepro_steps.pop(i) st.text('Step {}: {}'.format(i, c)) st.write('len prepro = {}'.format(len(state.prepro_steps))) st.write(state.prepro_steps)
However when I push a remove button something unwanted is happening: the code of the remove button is only activated when the rerun reaches the button again. So in my case the row below is removed because I use the position in the list (or the remove is postponed if you remove the last row).
You can see this behavior in the figure. Here I pressed the Add step button 4 times and then pressed the Remove step 2 button. In the rerun the for loop uses the intact list. On the third run of the loop, when reaching the third element of the list (second step), the row is first outputted to the dashboard before removing the third element (second step) of the list. The third step (fourth element) is not outputted because the for loop terminates because it has reached the length of the now shortened list. However outside the for loop the second element has been removed and the third element has become the second, as is outputted by the last two lines in the code. Thus the third element (second row) has been removed, however this is not outputted to the dashboard as I was expecting.
Does anybody have a solution or a workaround? | https://discuss.streamlit.io/t/trouble-combining-button-and-session-state/1735 | CC-MAIN-2020-34 | refinedweb | 346 | 64.61 |
SYNOPSIS
#include <ftw.h>
int nftw(const char *path, int (*fn)(const char *, const struct stat *, int, struct FTW *), int depth, int flags);
int nftw64(const char *path, int (*fn)(const char *, const struct stat64 *, int, struct FTW *), int depth, int flags);
DESCRIPTION
The
- FTW_CHDIR
If set,
nftw()changes the current working directory to each directory as it reports file in that directory. If clear, nftw()does not change the current working directory.
- FTW_DEPTH
If set,
nftw()reports all files in a directory before reporting the directory itself. If clear, nftw()reports any directory before reporting the files in that directory.
- FTW_MOUNT
If set,
nftw()only reports files in the same file system as the specified path. If clear, nftw()reports all files encountered during a walk.
- FTW_PHYS
If set,
nftw()performs a physical walk and does not follow symbolic links. If clear, nftw()follows links instead of reporting them, and does not report the same file twice.
For each object in the hierarchy,
- A pointer to a null-terminated character string containing the name of the object
- A pointer to a stat structure containing information about the object,
- An integer flag. Possible values for the flag are:
- FTW_F
For a file.
- FTW_D
For a directory.
- FTW_DP
For a directory for which the contents have already been visited. This condition only occurs if the FTW_DEPTH flag is specified.
- FTW_SL
For a symbolic link. This condition only occurs if the FTW_PHYS flag is specified.
- FTW_SLN
For a symbolic link that does not name an existing file. This condition only occurs if the FTW_PHYS flag is not specified.
- FTW_DNR
For a directory that cannot be read. The user function is not called for any of its descendants.
- FTW_NS
For an object on which
stat()could not be successfully executed. The stat buffer passed to the function is undefined.
- A pointer to an FTW structure. The value of the base member is the offset of the object's file name in the path name passed as the first argument to the function. The value of the level member indicates the depth relative to the root of the walk, where the root level is 0.
The
The tree traversal continues until the tree is exhausted, the user-supplied
function returns a non-zero value, or some error, other than
EACCES, is detected within
The
PARAMETERS
- path
Is the root of the directory hierarchy to be traversed.
- fn
Is the function to be called for each element of the tree.
- depth
Specifies the maximum number of directory streams or file descriptors (or both) that are available for use by
nftw()while traversing the tree. This should be in the range of [1, OPEN_MAX].
- flags
Indicates the flag values, as described in the DESCRIPTION section.
RETURN VALUES
On success,
- EACCES
Search permission is denied for any component of path or read permission is denied for path.
- EINVAL
The value specified for depth, with exceptions
MULTITHREAD SAFETY LEVEL
MT-Safe, with exceptions.
This function is MT-Safe unless the FTW_CHDIR flag is specified.
PORTING ISSUES
Windows current supports neither symbolic links nor mounted file systems, so the FTW_MOUNT and FTW_PHYS flags have no effect.
AVAILABILITY
PTC MKS Toolkit for Professional Developers
PTC MKS Toolkit for Professional Developers 64-Bit Edition
PTC MKS Toolkit for Enterprise Developers
PTC MKS Toolkit for Enterprise Developers 64-Bit Edition
SEE ALSO
- Miscellaneous:
- l64, struct stat
PTC MKS Toolkit 10.3 Documentation Build 39. | https://www.mkssoftware.com/docs/man3/nftw.3.asp | CC-MAIN-2021-39 | refinedweb | 572 | 56.05 |
Let's talk licenses, Holla Forums.
I've been theorizing why a FOSS enthusiast might use a BSD variant over Linux. It dawned on me that the BSD crowd probably doesn't have any specific complaints in the functionality of Linux. I take it that BSD users simply have a particular dislike in the license that Linux is released under?
Is there any license you prefer? Why?
Software Licenses
Let's talk licenses, Holla Forums.
Other urls found in this thread:
gnu.org
BipCot NoGov license
Because it's not FOSS enough for OSI, and makes both BSDMs and GiNdUs assmad.
But they do:
is there a license like GPL but you can't be a jew?
Muh Radeon drivers. Citation not required at least for me.
Apache v2? Maybe.
public domain
like you cant sell software with a pricetag bceuse i fucking hate jews
That would make the software proprietary and not open source.
mentioning jews in your posts doesn't make your lack of knowledge about licenses seem less retarded
You could sell the software on disc and have the disc wrapped in bacon.
...
...
here is a red pill for you
GPL and BSD are both free software licenses.
the fight between them is entirely a wedge issue created to make free software people fight among themselves to hold them back from getting good work done.
ok fuck you jew
Serious question:
If you were a scheming jew, what flaws would you find in the "Do What the Fuck You Want" license?
use copyleft-next
You can use it for anything you want. You can put it in your proprietary software without telling anyone where you got it or giving them the source code. It leaves open all kinds of abuse.
So... what's the point of a "don't do evil shit" license?
If an evil motherfucker already has the source, they're evil, why are they going to care what the license says?
I just don't really understand why this licensing this is such a big deal.
If you find out they're using your source code (if they use enough of it that isn't hard) you can sue them and/or force them to release their own source code and modifications to comply with the license.
Well that's reasonable, then.
It's like social (((justice))). License discarded.
take your homosexual lisp quotes back to the containment board they originated from please
Linux's namespaces ("containers" for you faggot webdevs) are more powerful than BSD's equiv. as they are lightweight and useful for far more than security. I use them on our networking product for some tricky routing as well as in our automated test framework. pf and iptables are equally shit when you try to do anything complicated with them, not sure why that even gets brought up - wasn't until pfsense I'd even heard anyone try to make that argument. QoS is practically non-existent on BSDs as are most new protocols. The main draw is the license for companies that don't want to expose their kernel hacks.
My default go-to is the GNU GPLv3 or AGPL
because those are the ones that try as hard as possible to make sure that software users are free in practice.
There are lots of people and companies who don't give a damn about the freedom talk, they just see this "open sauce" thing as a good leverage to make profit. Requiring them to give freedom to their users really pisses them off
point in question:
Apple loves leveraging BSD software to assemble a proprietary operating system.
Jewgle is very happy to use Linux and shit to build cheap products and Google's own tech infraestructure, but they have a BAN on AGPL software inside their company because they don't like the idea of not being able to use SaaSS as a business model. Indeed, luring retards into using SaaSS like GMail and Google Docs is a big part of their business model
This. The only answer that should matter.
iptables is obsolete and so is the argument of anyone claiming BSD is better because of it.
#!/sbin/nft -fflush rulesettable inet filter { chain input { type filter hook input priority 0 policy drop meta iif lo accept ct state related,established accept ip protocol icmp accept ip6 nexthdr icmpv6 accept tcp dport { domain, bootpc, ntp, http, https, ircd, git } accept udp dport { domain, bootpc, ntp } accept }}
From what I understand, the way it was build was "lets isolate the features we want isolated" whereas jails (or zones) were done in "lets isolate everything and allow what we need". So it might be more lightweight but it's inherently less secure because of this. If you want something lightweight, you have capsicum on FreeBSD and OpenBSD also introduced something like it recently.
With firewalls: yes I know that linux has more features. What I was saying, pf/ipf/ipfw has way better configuration for out-of-the-box tools. Whether you consider that important is another matter.
How is a Linux cgroup with everything isolated less secure than a jail or a zone?
I think the main advantage is the flexibility, not the weight. Firejail is a tool that uses Linux cgroups to run programs in a temporary, virtual home directory and process table, but with access to the rest of the filesystem. That's not a matter of weight compared to BSD, it's something that you just can't do on BSD, as far as I know.
It's just something I heard about the design of it, I haven't studied this stuff extensively. But design philosophy definitely does matter. You could say "there's no reason to think that OpenBSD software is more secure" in exactly the same way, and while there might not be any one obvious way in which it is more secure, the fact that there's a strong focus on security is undeniable and can't be just dismissed as if it didn't matter.
Because in FreeBSD, jails are very well connected with ZFS, which means that you can quickly crate jail with the whole filesystem in it. Of course you'd want to be able to use parts of the normal filesystem for temporary stuff when you can't quickly crate a snapshot of the FS, but that's a non-issue with jails.
The most important thing is that the license is GPL-compatible: gnu.org
That said, i would encourage using either the GPL or AGPL for server software, but your milage may vary.
What is Good, what is Evil?
What?
Fuck off shill. BSD license doesn't require contributing back and makes it vulnerable to being EEE'd by companies like MS and Sony.
Just look at what a walled garden hellhole Android is, and that happened with an even more protective license, just because it didn't account for tivoization.
Sorry, I thought cgroups were more than they actually are. I meant namespaces.
WTFPL.
Anything else is fake and gay.
Licenses are for niggers.
O P I N I O N D I S C A R D E D
P
I
N
I
O
N
D
I
S
C
A
R
D
E
D
The freedom to take freedom away is not desirable.
The best part is that the counterargument is
Of course, this ignores that the purpose of free software is to avoid shit like what is currently going on in the cell phone world. You might as well have an iphone as the device treats you the fucking same. Free software is about users.
You do realise then that some people will eat the disk and then try to sue you for their own stupidity, right?
that image is retarded.
gpl was created by a jew and both microsoft and the bsd license are not.
the merchant should be controlling gpl
Fuck off: GPL is a better indie license, MIT is a better commercial licence, and mozilla is probably the best flagship licence.
Stallman isn't of any particular race because he's a robotic autist.
Or the PS4. You can't install Linux or your own OS on it without having an old firmware version with an exploit. Sony also never has to give back a single line of code to the community. | https://hollaforums.com/thread/581418/technology/software-licenses/2.html | CC-MAIN-2021-21 | refinedweb | 1,402 | 70.23 |
perlmeditation gmax Most distinguished Monks,<br> A recent [id://129454|node] (thanks, [id://18800|jeffa]) offered a very interesting theoretical (and practical) view into database normalization.<br> While I couldn't agree more on the benefits of normalization, I was wondering if there was a different way of tackling the problem from the practical side.<br> Of course, normalization is never going to be "easy." But it could be easier than building a specialized solution for each table.<br> Due to previous experience with these tasks (which I used to solve in C - don't shoot!) I felt that a more general solution is possible, and fiddling around with Perl I came up with a module that can reduce our normalization efforts to something like the following: <br><br> <CODE> #!/usr/bin/perl -w use strict; use Normalizer; my %parameters = ( DSN => "DBI:mysql:music;host=localhost;" . "mysql_read_default_file=$ENV{HOME}/.my.cnf", src_table => "MP3", index_field => "album_id", lookup_fields => "artist,album,genre", lookup_table => "tmp_albums", dest_table => "songs", copy_indexes => 1 ); my $norm = Normalizer->new (\%parameters); $norm->do(); </CODE> The more adventurous could also try a one-liner (Normalization Golf?):<br> <CODE> perl -e 'use Normalizer; Normalizer->snew(qw(localhost music \ MP3 album_id album,artist,genre tmp_albums songs 1 0 0))->do()' </CODE> <readmore> What happens with this script?<br> Having this initial data (database: music, table: MP3), <CODE> +----------+-------------+------+-----+----------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+----------+----------------+ | ID | int(11) | | PRI | NULL | auto_increment | | title | varchar(40) | | MUL | | | | artist | varchar(20) | | MUL | | | | album | varchar(30) | | MUL | | | | duration | time | | | 00:00:00 | | | size | int(11) | | | 0 | | | genre | varchar(10) | | MUL | | | +----------+-------------+------+-----+----------+----------------+ </CODE> Here are the instructions produced by the above lines of perl:<br> <CODE> DROP TABLE IF EXISTS tmp_albums; # create the lookup table CREATE TABLE tmp_albums (album_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, artist varchar(20) not null, album varchar(30) not null, genre varchar(10) not null, KEY artist (artist), KEY album (album), KEY genre (genre)); # populate the lookup table INSERT INTO tmp_albums SELECT DISTINCT NULL, artist,album,genre FROM MP3; DROP TABLE IF EXISTS songs; # create the destination table CREATE TABLE songs (ID int(11) not null auto_increment, title varchar(40) not null, duration time not null default '00:00:00', size int(11) not null, album_id INT(11) NOT NULL, PRIMARY KEY (ID), KEY title (title), KEY album_id (album_id)); # Here is the trick! Using the lookup fields # as foreign keys, we populate the destination # table from source_table JOINed to lookup_table INSERT INTO songs SELECT src.ID, src.title, src.duration, src.size, album_id FROM MP3 src INNER JOIN tmp_albums lkp ON (src.artist =lkp.artist and src.album =lkp.album and src.genre =lkp.genre); </CODE> Don't rush to the CPAN ;-). The <I>Normalizer</I> module is not there (yet) also because I don't know if I should ask for a standalone namespace or under DBIx:: (any piece of advice here will be more than welcome). It is not a short piece of code either. It is <B>968 lines</B> (65% of which are documentation) and I didn't feel like posting all of it in this node.<br> But you are welcome to have a look at it from the following addresses:<br> <a href="">Normalizer.pm (highlighted syntax - 128 KB)</a><br> <a href="">Normalizer.pm (plain script - 38 KB)</a><br> <a href="">Normalizer.pod (documentation - 30 KB)</a><br> <a href="">Normalizer-0.05.tgz (complete package - 33 KB)</a><br> <br> <b>update</b> 2-Feb-2002<br> Now in the CPAN as <a href="">DBSchema-Normalizer</a><br><br> The black magic behind this code is more SQL than Perl. However, Perl makes it easier to collect the necessary pieces of information from the database engine and create the SQL statements. More important, Perl makes a generalized solution feasible.<br> A complete explanation of the algorithm is in the module documentation. The basic concept is to let the database engine work the heavy load, while Perl is directing the operations without wasting any valuable resources.<br> This module deals only with MySQL databases, but the principle should be valid for any RDBMS. If you want to try it risk-free, it is possible to run the script in "simulation mode," producing the SQL without executing it.<br> I hope this is going to be helpful, and I will be glad to receive your comments.<br> <br> <pre> _ _ _ _ (_|| | |(_|>< _| </pre> | http://www.perlmonks.org/index.pl?displaytype=xml;node_id=132513 | CC-MAIN-2015-35 | refinedweb | 737 | 50.77 |
The QAxScript class provides a wrapper around script code. More...
#include <QAxScript>
Inherits QObject..
Calls function, passing the parameters var1, var1, var2, var3, var4, var5, var6, var7 and var8 as arguments and returns the value returned by the function, or an invalid QVariant if the function does not return a value or when the function call failed.
See QAxScriptManager::call() for more information about how to call script functions.
This is an overloaded member function, provided for convenience. member function, provided for convenience.
result contains the script's result. This will be an invalid QVariant if the script has no return value.
This is an overloaded member function, provided for convenience.. | https://doc.qt.io/archives/qtopia4.3/qaxscript.html | CC-MAIN-2019-18 | refinedweb | 111 | 67.65 |
A Data Scientist's Toolbox, Part 3: Mock Your Data!
After we’ve discussed the importance of testing, you probably have the feeling that it’s a good idea, on general grounds, but your code is really tough to test. You have all these dependencies and your app writes to a database, and you have to load your data. So, yea. Not doable. Or so you think.
Well, there are a few tricks you can apply. As for reading data, it’s rather easy, actually. You can use the StringIO package to mock a file object and use that as an argument to the function that reads your data. Let’s assume you have a
.csv
file that’s actually not _C_SV, but rather separated with the vertical bar “|” (or Sheffer Stroke). You want to make sure this is taken into account across the project, so you want to test for it (good idea!). It’s as easy as this:
import pandas as pd import unittest import StringIO def readData(data_file): return pd.read_csv(data_file, sep="\|") class TestReader(unittest.TestCase): def test_gets_separator_right(self): """Make sure we have '\|' as separator.""" mockData = StringIO.StringIO("a\|b\n1\|2\n3\|4") df = readData(mockData) self.assertTrue(all(df.columns.values == ["a", "b"]))
That thing we just did? The one where we used a file object as input rather than a string and then open the file object inside the function? That’s a very good idea when writing code. It’s called flexibility. You don’t really care what object you get as an argument. It just needs to have a
read
function. You could even get input from a REST API or some form of database in the future. This is one of the neat things about testing. Making you code testable usually makes it more modular and flexible.
Speaking of databases. What if we want to mock a database instead of a file? We have to work a bit harder. Sometimes one can just use a local instance of the database. But often it’s better to make a mock object, one that simulates the database (or whatever you need to mock) with limited functionality. This way your tests can run on any machine, even if it has no access to a database of the right kind.
One instructive way to go is to hack your own. Let’s assume you want to store configuration in a MongoDB instance and need to make sure that the
update
function of the right database in the right collection is called. You can do this e.g. thusly.
import unittest from collections import defaultdict class MockDB(object): def __init__(self): self.objects = [] self.calls = defaultdict(int) def update(self, search, newvlas, upsert): self.calls['update'] += 1 class MockMongo(object): def __init__(self, dictgen): self.d = dictgen def __getattr__(self, name): return self.d[name] def __contains__(self, item): return item in self.d def saveOptions(mongo_client, **opts): for k in opts: mongo_client.myapp.settings.update( {'key': k}, {'$set': {'value': opts[k]}}, True) class SaveOptionsTest(unittest.TestCase): def setUp(self): self.db = MockMongo(defaultdict( lambda: MockMongo( defaultdict(lambda: MockDB())))) def test_uses_right_collection(self): saveOptions(self.db, model='svm') self.assertTrue('myapp' in self.db) def test_uses_right_db(self): saveOptions(self.db, model='svm') self.assertTrue('settings' in self.db.myapp) def test_calls_update(self): saveOptions(self.db, model='svm', S=5) self.assertEqual(self.db.myapp.settings.calls['update'], 2)
You see that we have to jump through a bunch of hoops to get the member lookup right, but well. That’s how MongoDB behaves. In a real-world application you would probably want something more industry-grade. You can check the excellent selection of mock frameworks on the python homepage. A mock framework makes the creation of mock objects easy and often gives them some basic functionality, like watching and counting function calls. Happy mocking! | http://data-adventures.com/data%20adventures/2016/04/21/a-data-scientists-toolbox-part-3-mock-your-data.html | CC-MAIN-2018-43 | refinedweb | 648 | 69.28 |
HI,
Is there any way to set a host, certificate and private key file for WS API test object in Katalon?
In Postman those are in the Settings - Certificates
Host
CRT file
KEY file
Passphrase
Thank you.
HI,
Is there any way to set a host, certificate and private key file for WS API test object in Katalon?
In Postman those are in the Settings - Certificates
Host
CRT file
KEY file
Passphrase
Thank you.
Hi,
Mutual TLC is supported only in Enterprice version How to set a certificate for a API request
This one?
Or that one that starts from a command line?
I have tried to solve the issue in the next way
add a key file here
import the .crt file here
…]Katalon_Studio_Engine_Windows_64-7.2.1\jre\lib\security\cacerts
ERROR: Can’t build keystore: [Certificate chain missing]
if I put the .crt file in the Project - Settings - Network - Keystore
and add something like this to a test case
System.setProperty(‘javax.net.ssl.trustStore’, GlobalVariable.ssl_key_file)
System.setProperty(‘javax.net.ssl.trustStorePassword’, GlobalVariable.ssl_key_pathphrase)
request_result = WS.sendRequest(findTestObject(‘API/connection_check’), FailureHandling.STOP_ON_FAILURE)
I will get the next
ERROR: Can’t build keystore: [Private key missing (bad password?)]
Hi @Vitallica,
Please generate a KeyStore file from your cert file and key file, then apply it to client certificate settings. Please follow the documentation here
Thanks, I will try
Is there any chance to set the KeyStore path as a variable?
The Katalon documentation said:
Katalon Studio can be configured to use the Client Certificate for all requests. To sign all the requests from Katalon Studio, specify the full path to your KeyStore file and the KeyStore Password. The recommended key store format is PKCS #12 (.p12).
My company has different environments and keys respectively, so it is really annoying process to change the path every time in the Project Settings Network.
It would be much easier if the path set in the Profile and use a variable in the Network KeyStore.
Thanks. | https://forum.katalon.com/t/katalon-ws-api-request-with-host-certificate-and-private-key/41720 | CC-MAIN-2022-40 | refinedweb | 334 | 63.49 |
effective and graceful pattern matching for original python
Project description
Efficient pattern matching for standard python.
coroutines makes it possible to flatten the function stacks, and code-generator makes it possible to use TCO’s syntax sugars.
from pattern_matching.core.match import when, overwrite from pattern_matching import var, Using from numpy.random import randint with Using(scope=locals(), use_tco=True): @overwrite((var, *var)) def qsort(head, tail): lowers = [i for i in tail if i < head] highers = [i for i in tail if i >= head] return qsort(lowers) + [head] + qsort(highers) @when(var) def qsort(lst): return lst print(qsort(randint(0, 2000, size=(1200, ))))
Pattern-Matching
The library name destruct has been registered at PyPI, so we rename Destruct.py with pattern-matching. The new one could be more accurate.
Install
pip install -U pattern-matching.
Example
- Pattern Matching for functions.
We can overload the functions easily.
from pattern_matching import Match, when, var, T, t, match_err, _, overwrite @when(_ == 1, var[int]) def u_func(res): return res @when(var < 0, _) def u_func(): raise varueError('input should be positive.') @when(var[int] > 1, var) def u_func(now, res): return u_func(now-1, res*now) @when(var[int]) def u_func(now): return u_func(now, 1) u_func(10, 1) # => 3628800
- Explicit pattern matching.
with Match(1, 2, (3, int)) as m: for a, b, c in m.case((var[int], var, var[list])): # not matched print(a, b, c) for typ, in m.case((_, _, (_, var.when(is_type)))): # supposed to match here print(typ) else: print('none matched') # => <class 'int'>
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/pattern-matching/ | CC-MAIN-2018-43 | refinedweb | 289 | 56.35 |
#include <object.h>
#include <object.h>
Inheritance diagram for aeObject:
Definition at line 127 of file object.h.
[virtual]
Add a vertex to this object.
This adds a single vertex to this object.
[pure virtual]
Draw this object.
This is called by aeEngine::Render(). You shouldn't need to call this yourself.
Implemented in aeLine, aeModel, aePolygon, aeQuad, aeTriangle, and aeMD2Object.
Return the radius of the bounding sphere of this object.
Get the object's material.
Get object's name.
Get the origin for this object.
Get a vertex of this object.
Get the number of vertices in this object.
Used to check if this object is currently transparent.
Set the RGBA color of this object.
This accepts an aeColor4 to specify the color. Subsequent AddVertex() calls will add a vertex of this color.
Set the RGB color of this object.
This accepts an aeColor3 to specify the color. Subsequent AddVertex() calls will add a vertex of this color.
The values are from 0.0 to 1.0. Subsequent AddVertex() calls will add a vertex of this color.
Set material for this object.
Set the object rendering mode.
For each derived object type (aeTriangle, aeQuad, aePolygon, aeLine) there is a set of rendering modes which indicate how the object's vertices are to be interpreted when drawing them. Possible modes are:
Set the origin for this object.
Set the texture coordinate for the next vertex(es).
Use this before AddVertex() to add a texture coordinate for that vertex. If you set a texcoord only for the first vertex, that coordinate will be used for all subsequent vertices until you specify a new texture coordinate.
Used to specify whether this object is transparent or not. | http://aeengine.sourceforge.net/documentation/online/pubapi/classaeObject.html | CC-MAIN-2017-13 | refinedweb | 284 | 62.85 |
Another update. Oops, they did it again. In RC.5 routing configuration has been changed. Will update this blog by the end of August of 2016.
This blog was updated on July 24, 2016.
Angular 2 framework (currently in RC.4) offers a simple way to implement client-side navigation for Single-Page Applications (SPA). The new component router (currently v.3.0.0-beta.2) allows you to configure routes, map them to the corresponding components, and arrange user’s navigation in a declarative way. While working on a routing chapter for our book “Angular 2 Development with TypeScript” I created a number of small applications illustrating various routing scenarios:
– Configuring routes in the root component
– Configuring routes in both root and child components
– Passing parameters to routes
– Using routing with both Hash- and History API-based strategies
– Using auxiliary (independent) routes
You can find these sample apps on Github where we host and update all code samples for the book (see the chapter3 folder). But in this blog I’ll do a high-level overview of Angular 2 routing and will show you a basic working example where the routing is configured in the root component of the application.
When you visit any Web page the location bar of your browser shows a URL (see, you already learned something new!). The URL consists of a protocol, domain name, port, and in case of GET requests may have parameters after the question mark:
If you change any character in the above URL and press Enter, this will result in sending a request to the server and page refresh, which is not what we want in SPA. In SPA, we want to be able to change a URL fragment that won’t result in the server request, but would update a portion of the Web page based on the JavaScript code that is already loaded to the browser.
Many years ago browsers started supporting a hash-sign (#) in the URLs, for example:
Any modifications to the right of the hash tag don’t trigger requests to the server, hence we can map these fragments to the client-side component to be rendered in the designated area of the Web page (in Angular 2 it’s identified by the tags <router-outlet></router-outlet>).
Then browsers started implementing HTML5 APIs, which includes History API that allows programmatically support the Back and Forward buttons as well as modify a URL fragment using the pushState() method. The history of all user’s navigations would be
stored on the client.
Angular 2 supports both location strategies using its classes HashLocationStrategy or PathLocationStrategy sparing you from adding the hash sign to the URL or calling pushState(). You just need to choose which strategy to use. I prefer hash-based navigation because a) it’s supported by all the browsers and b) History API-based navigation is unstable at this point.
Now let’s get familiar with the main players of Angular 2 navigation:
* Router – an object that represents the router during the runtime. You can use its methods navigate() or navigateByUrl() to navigate to a route either by the configured route path or by the URL segment respectively.
* RouterOutlet – a directive that serves as a placeholder within your Web page where the router should render the component
* provideRouter – maps URLs to components to be rendered inside the tag <router-outlet>
* RouterLink – a directive to declare a link to a route if the navigation is done using the HTML anchor tags. The RouterLink may contain parameters to be passed to the route’s component
* ActivatedRoute – an object that represents the route(s) that’s currently active
You configure routes for your app in a separate object of type RouterConfig and pass this object to the bootstrap() function. Router configuration is not done on the component level.
In a typical scenario, you’ll be implementing navigation in your application by performing the following steps:
1. Configure your app routes to map the URL segments to the corresponding components and pass the configuration object to bootstrap() as an argument. If some of the components expect to receive input values, you can use route parameters.
2. Add the property directives: [ROUTE_DIRECTIVES] to the @Component annotation. This will allow you to use the custom tag <router-outlet>, a property routerLink et al.
3. Define the viewport where the router will render components using the <router-outlet> tag.
4. Add the HTML anchor tags with bounded [routerLink] properties (square brackets denote property binding), so when the user clicks on the link the router will render the corresponding component. Think of a routerLink as a client-side replacement for the href attribute of the HTML anchor tag.
NOTE: Invoking the router’s methods navigate() or navigateByUrl() is an alternative to using [routerLink] for navigating to a route.
Here’s an illustration of the above steps:
The function provideRoute() takes the routes configuration that represents two URL segments that may be appended to the base URL:
* The empty string in the path means that there’s no additional URL segment after the base URL (e.g.), and the application should display the HomeComponent in the outlet area.
* The product path represents the URL segment product (e.g.), and the application should display the ProductDetailComponent in the outlet.
Let’s illustrate these steps in a sample application. Say we want to create a RootComponent that has two links Home and Product Details at the top of the page. The application should render either HomeComponent or ProductDetailComponent depending on which link the user clicks. The HomeComponent will render the text “Home Component” on the red background, and the ProductDetailComponent will render “Product Detail Component” on cyan.
Initially the Web page should display the HomeComponent as shown below.
After the user clicks on the Product Details link the router should display the ProductDetailComponent as shown on the next screenshot. Note the hash portion in the URL:
The main goal of this exercise is to get familiar with the router, so our components will be very simple. Below is the code of HomeComponent:
import {Component} from 'angular2/core'; @Component({ selector: 'home', template: ' <h1 class="home">Home Component</h1> ', styles: ['.home {background: red}'], }) export class HomeComponent {}
The code of the ProductDetailComponent will look similar, but instead of red the property styles will define the cyan background:
import {Component} from 'angular2/core'; @Component({ selector: 'product', template: ' <h1 class="product">Product Detail Component</h1> ', styles: ['.product {background: cyan}'] }) export class ProductDetailComponent {}
The [RootComponent] will define the routing of this application, and its code is shown next.
import {bootstrap} from '@angular/platform-browser-dynamic'; import {Component} from '@angular/core'; import {LocationStrategy, HashLocationStrategy} from '@angular/common'; import {provideRouter, ROUTER_DIRECTIVES, RouterConfig} from '@angular/router'; // 1 import {HomeComponent} from './components/home'; import {ProductDetailComponent} from './components/product'; @Component({ selector: 'basic-routing', directives: [ROUTER_DIRECTIVES], // 2 template: ` <a [routerLink]="['/']">Home</a> // 3 <a [routerLink]="['/product']">Product Details</a> <router-outlet></router-outlet> // 4 ` }) class RootComponent {} RouterConfig bootstrap(RootComponent, [ provideRouter([ // 5 {path: '', component: HomeComponent}, {path: 'product', component: ProductDetailComponent} ]), {provide: LocationStrategy, useClass: HashLocationStrategy} // 6 ]);
1. First we import all navigation-related directives and classes from @angular/router and @angular/common.
2. Since this component uses router directives we include ROUTER_DIRECTIVES in the annotation @Component.
3. Binding routerLink to routes (see callnote 5) using their paths / and /product.
4. The tag <router-outlet> specifies the area on the page where the router will render one of our components.
5. We’ve configured routes here. The empty URL segment represents the base URL.
6. During the application bootstrap we specify dependencies of the RootComponent in the square brackets.
In the above example we use HashLocationStrategy, which means if we configure the router with the URL segment product, Angular will add /#/product. The browser will treat the segment after the hash sign as an identifier of a specific segment of the Web page.
Note the use of brackets in the <a< tags. The square brackets around routerLink denote property binding, while brackets on the right represent an array with one element (e.g. [‘/’]). We’ll show you examples of array with two or more elements later in this chapter. The second anchor tag has the property routerLink bound to the route named ProductDetail.
In the above example HomeComponent is mapped to the path containing an empty string, which implicitly makes it a default route.
Here we’ve configured routes in the object and passed it as an argument to the provideRouter() function. The value in the routerLink will be matched with the configured path. In our case the <router-outlet> represents the area below the anchors.
The structure of the object that you can pass to provideRouter() is defined in the interface RouteConfig, which is an array of objects implementing the interface Route shown below (the question marks mean that the respective property is optional):
export interface Route { path?: string; pathMatch?: 'full' | 'prefix'; component?: Type | string; redirectTo?: string; outlet?: string; canActivate?: any[]; canDeactivate?: any[]; data?: Data; resolve?: ResolveData; children?: Route[]; }
NOTE: Make sure that the file package.json includes “@angular/router”: “3.0.0-beta.2” in its dependencies section.
Handling 404 errors
If the user will enter a non-existing URL in your application, the router won’t be able to find the matching route and will print the error message on the browser’s console leaving wondering why not any navigation is happening. Consider creating an application component that will be displayed whenever the application can’t find the matching component.
For example, you can create a component named _404Component and configure it with the wild card path **:
provideRouter([ {path: '', component: HomeComponent}, {path: 'product', component: ProductDetailComponent}, {path: '**', component: _404Component} ])
Now, whenever the router can’t match the URL to any component, it’ll render the content of your _404Component instead. The wild card route configuration has to be the last element in the array given to provideRouter(). The router always treats the wild card route as a match and any routes listed after the wild card’s one won’t even be considered.
That’s all for now. Stay tuned for more Angular 2 blogs. My other Angular-related blogs are here. Our next public online Angular 2 workshop starts on September 11, 2016.
14 thoughts on “Angular 2 Router: High-Level Overview”
You forgot to use and in your code sample template.
And you talk about instead of in point 3.
Thanks for your posts, hope next ‘ng2 with typescript’ chapters will arrive soon 🙂
Thank you for noticing. I didn’t forget – if you open the source code in plunker – they are there. WordPress removed these tags from the text somehow. Will fix it.
Manning will post two more chapters in November and then another two in December.
Yakov, maybe you should create a TypeScript User Group (but they did have some TS presentation in Microsoft ones). There is a total absence of these. We do need to have a better version of JavaScript, OO and with more features… I think, even after ES6 it will be true.
>NOTE: In versions prior to Alpha 46 you could manually crete an instance of the route in the @RouteConfig >section, e.g. new Route({path: ‘/’, component: HomeComponent, as: ‘Home’}). This syntax will generate an >error starting from Aplha 46.
that is my problem now. How can I fix it? I removed the “as: ‘Home'” from the routes but now I get the error: Component “MyDemoApp” has no route named “Home”.
Had similar problem with beta-0 today using -> component: HomeComponent, name: ‘Home’ <-
In my case I tried to put your newer plunker files inside of an existing Angular 2 environment, which already had a "bootstrap" on my "main.ts" home page.
I'm trying to embed components that load their own router parameters…
Any help on this would be most grateful 🙂
Updated the plunk to run with beta.0
Updated the code and the plunk to run in Alpha 52 (routerLink instead of router-link and imports for Component and bootstrap).
Thanks for the post Yakov. Very helpful! One area that is a problem for me is how to handle redirect uris which PingFederate as OAuth 2.0 provider will use to redirect the browser to a route in my app. The problem is that Ping uses fragment components to store the access token, etc. For that reason they don’t allow me to configure a redirect uri for a particular client with a fragment already present. So I am using the default PathLocationStrategy, but I notice the # fragment is removed when my route is rendered. Any ideas?
Is your issue related to this bug?
Try using HashLocationStrategy.
“Many years ago browsers started supporting a hash-sign (#) in the URLs, …”
Actually fragments go way back. Originally, the idea was that, after displaying the page, the browser would scan for an <a tag with a name= attribute that matches the frag (without #). I think that still works, but of course things have changed so much. Here's an RFC from 1995 that describes them.
"hash tag" – I think a hash tag is a Twitter thing. These are called Hashes or Fragments. | https://yakovfain.com/2015/11/02/angular-2-router-high-level-overview/ | CC-MAIN-2020-05 | refinedweb | 2,189 | 53.21 |
Blurring Faces with Google Cloud Vision
Why might you want to blur faces in an image? One motivation would be if you are publicly releasing a dataset of imagery: it is common practice to blur faces in order to preserve the privacy of individuals whose faces were captured without their consent.
If you find yourself needing to do this, you could train a face detector yourself or use a pre-trained Haar Cascade model. However, the common standard for preserving privacy in public datsets is “best effort” obfuscation, so you may want a better model. You’re in luck, because Google Cloud Vision provides a very good face detection API.
A full script for blurring imagery via the Cloud Vision API is here. This is the part that conducts the blurring (I also tried Gaussian blur, but linear blur was better at hiding the face in this case):
def blur_image(image_content, faces, output_path): img = Image.open(StringIO(image_content)) img = np.array(img) # RGB/BGR channel flip for PIL-OpenCV compatibility img = img[:, :, ::-1] for face in faces: box = [(bound.x_coordinate, bound.y_coordinate) for bound in face.bounds.vertices] ... roi = img[y:y+h, x:x+w] roi_blurred = cv2.blur(roi, (15,15)) img[y:y+h, x:x+w] = roi_blurred return img
Here is an example of how the blurring looks:
| https://mattdickenson.com/2017/07/21/blurring-faces-cloud-vision/ | CC-MAIN-2021-43 | refinedweb | 221 | 63.49 |
Hello,
I use SALOME for post-processing of electromagnetic dynamic problems solved by an external program, e.g. evolution along time of fields in an electric motor. I would like to see the animation of the fields along time, but the mesh changes, e.g. one part rotates, during time. I am able to create such meshes in MED format, and my fields are also stored in MED format.
I know that MED format permits such features of fields attached to various meshes. My program stores everything in the same MED file, but SALOME (last version) separates the fields according to each mesh (with different names), and animation is not possible. Besides
Could you please confirm to me that SALOME is able to animate such fields, and teach me how to properly create the appropriate MED file ?
Thank you,
Loïc Chevallier.
Hello Loïc
So far SALOME is unable to animate meshes changing with time in VISU module for sure. As about PARAVIS module, please refer to its documentation to be sure, but most probably neither.
Best regards
Thank you for such a quick answer. Some colleagues said to me that successive animation was able to be applied on fields in several already loaded MED files, e.g. the same field but each time step corresponds to one MED file. Of course the timestamp for each field is correct.
I was able to make such an animation and also to select all fields loaded with the same name (see script below). When right-clicking on the selection in order to create the successive animation, my file names are not sorted along time, despite their name is correct, the time stamp for each field is correct, and my MED files are loaded in SALOME according to the the time, i.e. time=2s after time=1s. Also Entry values of fields are sorted according to time, i.e. Entry='0:1:1:3:1' for time=1s, Entry='0:1:2:3:1' for time=2s.
Could you please teach me how to order the list of Fields in animation ?
Best regards,
Loïc chevallier.
P.S. Script to select all fields with the same name (BFIELD, Tesla) in Post-processing mode :
salome.sg.ClearIObjects() # clear all selected objectsall = salome.myStudy.FindObjectByName("BFIELD, Tesla","VISU") # list of all objects, sorted according to their Entry valuefor a in all: id = a.GetID() # get Entry value for each object salome.sg.AddIObject(id) # Make this object selected
print "Number of 'BFIELD, Tesla' selected: ",salome.sg.SelectedCount() # message
I think you can have a full control of animation by using its Python API (see VISU/bin/salome/visu_succcessive_animation.py).
It seems that order of fields depends on order of anAnim.addField(aSObj) calls.
Best Regards
Previously SMESH/MED expert wrote:
I think you can have a full control of animation by using its Python API (see VISU/bin/salome/visu_succcessive_animation.py).
It seems that order of fields depends on order of anAnim.addField(aSObj) calls.
Best Regards
You were write: using successive calls to the addField method does the job of ordering fields as I entered them.
Now the hard part is to get a properly ordered list of fields objects, i.e. by ascending Entry i.e ID.
I made several tests, where I import my MED files in the right order, i.e. first time step, second time step, etc. ID's values are properly ordered, i.e. I get something like:
first field ID: 0:1:1:1:1:3:1second field ID: 0:1:1:2:1:3:1third field ID: 0:1:1:3:1:3:1
...tenth field ID: 0:1:1:10:1:3:1
The first method, based on selecting all these fields -- either manually or automatically based on the field name -- does not work properly. I may get this list of IDs, but it is not sorted, i.e. the order may be: 2, 1, 3... I think this is the way used by the animation feature using GUI.
Using Python, I have tried to sort this array of ID strings, and it works for the numbers from 1 to 9 or 10 to 19, etc. but not for number from 1 to 13, as the order is 10, 11, 12, 13, 1, 2, 3... 9.
Finally I found a way, i.e. getting a list of IDs by a search on field names. Surprisingly, the list of IDs is properly sorted. The relevant part of the attached full script is, for the field named 'BFIELD, Tesla':
import salomefields = salome.myStudy.FindObjectByName('BFIELD, Tesla',"VISU")for field in fields: myAnimation.addField(field)
Best regards.
Legal Information | http://www.salome-platform.org/forum/forum_11/707013009#998592769 | CC-MAIN-2016-44 | refinedweb | 779 | 65.83 |
- Cags's C-Learning Thread
- 30 Aug 2016 04:25:07 pm Permalink
- Last edited by ACagliano on 09 Sep 2016 10:02:56 am; edited 1 time in total
So I decided to get into learning C so I can program for the CE. I have prior experience with some syntactically similar languages (PHP, JS, Java). I'll use this thread to post snippets of my first C project, a rewrite of my Polynomial math tool, and let you all comment/suggest other ways/or answer questions I may have.
To start:
Code:
To start:
Code:
#include <../../include/ce/c/tice.h>
int main(){
/* Variable Declarations */
bool canRoll;
bool canScore;
int comboScores[13];
bool comboScored[13];
/* Code Start */
boot_ClearVRAM();
pgrm_CleanUp();
} | https://www.cemetech.net/forum/viewtopic.php?t=13037&start=0 | CC-MAIN-2022-05 | refinedweb | 121 | 66.88 |
This is a follow up to TypeScript Accessing Other .ts Files this time with 100% more Node.js.
Last time we accessed other
.ts files by reference and by using the module loader (SystemJS)[]. This time we will access multiple
.ts files inside our overly simplified Node.js project.
Somethings to know before hand.
- I don’t really know what I am doing in Node.js
- I used Visual Studio 2015 and the Node.js Tools for Visual Studio 1.1
- Do not consider my structure of a Node.js app as a best practice as I was only trying to demonstrate accessing different
.tsfiles and not create and all encompassing guide to the awesomeness that I am sure Node.js is
- I really don’t know what I am doing in Node.js
Structure
I started with the included NodejSWebApp template that came with the Node.js Tools for Visual studio and modified the
server.ts slightly. I also added two additional
.ts files so we have three TypeScript files we will be working with:
server.ts in the root of the project and
helper.ts with
service.ts in the
services folder
Solution Explorer
Obviously each file must contain something:
helper.ts
export function log(message: string) { message = 'logged: n' + message; console.log(message); }
As you can see
helper.ts just has a function called ‘log’ that logs a message to the console.
service.ts
import helper = require('./helper'); export function doSomething(id: string) { let results = id + Date.now().toString() + 'n'; helper.log(results); return results; }
The
service.ts uses the same
import and
require as we used in TypeScript Accessing Other .ts Files and specify the module to import with a relative path.
server.ts
import http = require('http'); import service = require('./services/service'); let port = process.env.port || 1337 http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); let message = service.doSomething('Hello Worldn'); res.end(message); }).listen(port);
In this last example you can see the
server.ts uses the same
import and
require as before but this time it specifies the folder in the path.
I did have some issues with Visual Studio resolving the path to modules. Once a path was correct the red squiggly error was still showing in the file and the error wouldn’t clear up till I created a new error and cleared it up, usually by removing a semicolon and putting it back.
Now when we run it we should see ‘Hello world’ and the time in our web browser.
And you should see what was logged in the console.
Now ever time the page is refreshed you should see the results get logged as well.
Finally {}
As you can see the
import and
require remained the same as when we used the SystemJS module loader when referencing different files or modules. The main issue I had was getting Visual Studio to stop saying there was an error when it had been fixed.
All source code for this example was added to the Github.com/BrettMN/TypeScriptSamples in the NodejsWebApp folder.
Hope this helps, if not leave a comment and I will try and help as best I can. | https://wipdeveloper.com/typescript-accessing-other-ts-files-take-ii-in-node/ | CC-MAIN-2019-39 | refinedweb | 534 | 69.68 |
CodePlexProject Hosting for Open Source Software
I notice when i delete a content item using
_contentManager.Remove(contentItem)
it does not delete the existing record of whatever parts attached to this content item. For example, the AutoroutePartRecord and TitlePartRecord.
Is there any reason to keep these records? If not i guess i'll need to delete those manually from repository.
That's the design: we only do soft deletes.
If you do want to delete the content part when a content item is being removed, you can write a content handler that overrides the Remove method. From within that method, you could easily remove the part record.
Example:
public class MyPartHandler:ContentHandler
{
private readonly IRepository<MyPartRecord> _repository;
public MyPartHandler(IRepository<MyPartRecord> repository ) {
_repository = repository;
}
protected override void Removed(RemoveContentContext context)
{
var myPart = context.ContentItem.As<MyPart>();
if(myPart != null)
_repository.Delete(myPart.Record);
}
}
thanks! It was giving me problems because one of the column is unique. If the existing record is not deleted, i cant create another new record with the same value.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://orchard.codeplex.com/discussions/350221 | CC-MAIN-2017-47 | refinedweb | 209 | 58.38 |
On Mon, Mar 18, 2013 at 08:08:35AM +0100, Hendrik Leppkes wrote: > On Mon, Mar 18, 2013 at 12:42 AM, Michael Niedermayer <michaelni at gmx.at> wrote: > > On Sun, Mar 17, 2013 at 06:27:28PM -0300, James Almer wrote: > >> lavu/atomic.c is not compiling with gcc when using -march=i386 and w32threads > >> or os2threads because __sync_val_compare_and_swap() is not defined and the > >> fallback implementation currently only supports pthreads. > >> Mingw-w64 has MemoryBarrier() defined even when using -march=i386, so this is > >> not as much of a problem as it is with mingw32. > >> > >> I was able to make it work using the pthreads wrappers from libavcodec, but > >> I'm not sure if this is a proper fix or not since threading is not my field of > >> expertise. > >> > >> I'm attaching two versions of the proposed patch. Both are essentially the > >> same, but one alters the pthreads implementation for the sake of cleaner code. > >> I didn't test with the pthreads wrapper for os2threads because i have no way > >> to do it, but in theory it should work as well. > >> > >> I'll send an actual patch once (and if) one of these is accepted. > >> > >> Regards. > > > >> atomic.c | 27 +++++++++++++++++++-------- > >> 1 file changed, 19 insertions(+), 8 deletions(-) > >> d2f851be5ec4d25c4b655b6a5cef60594edf989e atomic.diff > >> diff --git a/libavutil/atomic.c b/libavutil/atomic.c > >> index 7a701e1..12537ad 100644 > >> --- a/libavutil/atomic.c > >> +++ b/libavutil/atomic.c > >> @@ -22,38 +22,50 @@ > >> > >> #if !HAVE_MEMORYBARRIER && !HAVE_SYNC_VAL_COMPARE_AND_SWAP && !HAVE_MACHINE_RW_BARRIER > >> > >> -#if HAVE_PTHREADS > >> +#if HAVE_THREADS > >> > >> +#if HAVE_PTHREADS > >> #include <pthread.h> > >> +#elif HAVE_W32THREADS > >> +#include "w32pthreads.h" > >> +#elif HAVE_OS2THREADS > >> +#include "os2threads.h" > >> +#endif > >> > >> -static pthread_mutex_t atomic_lock = PTHREAD_MUTEX_INITIALIZER; > >> +static pthread_mutex_t atomic_lock; > >> > >> int avpriv_atomic_int_get(volatile int *ptr) > >> { > >> int res; > >> > >> + pthread_mutex_init(&atomic_lock, NULL); > >> pthread_mutex_lock(&atomic_lock); > >> res = *ptr; > >> pthread_mutex_unlock(&atomic_lock); > >> + pthread_mutex_destroy(&atomic_lock); > > > > one possible solution would look something like: > > > > +static int volatile init; > > > > int avpriv_atomic_int_get(volatile int *ptr) > > { > > int res; > > > > + if(!init) { > > + pthread_mutex_init(&atomic_lock, NULL); > > + init = 1; > > + } > > > > pthread_mutex_lock(&atomic_lock); > > res = *ptr; > > pthread_mutex_unlock(&atomic_lock); > > } > > > > this has 2 issues > > theres a unlikely race on allocation and we dont bother > > destroying the mutex ever > > > > also, a comment from some win32 expert if there is a better way would > > be welcome ... > > > > [...] > > > > -- > > > > > > What i would do (besides calling mingw32 unsupported) is keep the > pthread implementation as-is, and add a second fallback using win32 > mutexes directly. > This way you don't add any of the risk factors to the existing pthread > implementation, which may get used on more "fringe" systems without > atomics, and only use the new implementation for people with outdated > toolchains on windows. > Additionally, the pthread compat layers are in avcodec, and > technically not available to avutil. > > Considering you only need 3 functions, it seems easier to just create > a second block and use > InitializeCriticalSection/EnterCriticalSection/LeaveCriticalSection > from win32 (which are required for w32threads to work, so you can > assume they are present under a #if HAVE_W32THREADS agree > > A bit of a side-topic, but maybe configure should at least warn that > mingw32 is lacking features and builds may be slower or lack features? possibly ... iam no win32 person so this isnt my area but iam happy to apply a a patch making such change if thats what the people using win32: <> | http://ffmpeg.org/pipermail/ffmpeg-devel/2013-March/140842.html | CC-MAIN-2019-18 | refinedweb | 521 | 51.58 |
django-cron 0.3.4
Running python crons in a Django project
Django-cron lets you run Django/Python code on a recurring basis proving.
Retry after failure feature
You can run cron by passing RETRY_AFTER_FAILURE_MINS param.
This will re-runs not next time runcrons is run, but at least RETRY_AFTER_FAILURE_MINS after last failure:
class MyCronJob(CronJobBase): RUN_EVERY_MINS = 60 # every hours RETRY_AFTER_FAILURE_MINS = 5 schedule = Schedule(run_every_mins=RUN_EVERY_MINS, retry_after_failure_mins=RETRY_AFTER_FAILURE_MINS)
Run at times feature
You can run cron by passing RUN_EVERY_MINS or RUN_AT_TIMES params.
This will run job every hour:
class MyCronJob(CronJobBase): RUN_EVERY_MINS = 60 # every hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
This will run job at given hours:
class MyCronJob(CronJobBase): RUN_AT_TIMES = ['11:30', '14:00', '23:15'] schedule = Schedule(run_at_times=RUN_AT_TIMES)
Hour format is HH:MM (24h clock)
You can also mix up both of these methods:
class MyCronJob(CronJobBase): RUN_EVERY_MINS = 120 # every 2 hours RUN_AT_TIMES = ['6:30'] schedule = Schedule(run_every_mins=RUN_EVERY_MINS, run_at_times=RUN_AT_TIMES)
This will run job every 2h plus one run at 6:30.
Allowing parallels runs
By deafult parallels runs are not allowed (for security reasons). However if you want enable them just add:
ALLOW_PARALLEL_RUNS = True
in your CronJob class.
- Note this requires a caching framework to be installed, as per
If you wish to override which cache is used, put this in your settings file:
CRON_CACHE = ‘cron_cache’
Installation
Install django_cron (ideally in your virtualenv!) using pip or simply getting a copy of the code and putting it in a directory in your codebase.
Add django_cron to your Django settings INSTALLED_APPS:
INSTALLED_APPS = [ # ... "django_cron", ]
If you’re using South for schema migrations run python manage.py migrate django_cron or simply do a syncdb.
Write a cron class somewhere in your code, that extends the CronJobBase class. This class will look something like this:
from django_cron import CronJobBase, Schedule class MyCronJob(CronJobBase): RUN_EVERY_MINS = 120 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'my_app.my_cron_job' # a unique code def do(self): pass # do your thing here
Add a variable called CRON_CLASSES (similar to MIDDLEWARE_CLASSES etc.) thats a list of strings, each being a cron class. Eg.:
CRON_CLASSES = [ "my_app.cron.MyCronJob", # ... ]
Now everytime you run the management command python manage.py runcrons all the crons will run if required. Depending on the application the management command can be called from the Unix crontab as often as required. Every 5 minutes usually works for most of my applications.
FailedRunsNotificationCronJob
This example cron check last cron jobs results. If they were unsuccessfull 10 times in row, it sends email to user.
Install required dependencies: ‘Django>=1.5.0’, ‘South>=0.7.2’, ‘django-common>=0.5.1’.
Add ‘django_cron.cron.FailedRunsNotificationCronJob’ to your CRON_CLASSES in settings file.
To set up minimal number of failed runs set up MIN_NUM_FAILURES in your cron class (default = 10). For example:
class MyCronJob(CronJobBase): RUN_EVERY_MINS = 10 MIN_NUM_FAILURES = 3 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'app.MyCronJob' def do(self): ... some action here ...
To set up email prefix, you must add FAILED_RUNS_CRONJOB_EMAIL_PREFIX in your settings file (default is empty). For example:
FAILED_RUNS_CRONJOB_EMAIL_PREFIX = “[Server check]: “
FailedRunsNotificationCronJob checks every cron from CRON_CLASSES
This opensource app is brought to you by Tivix, Inc. ( )
Changelog
0.3.4
- Added CRON_CACHE settings parameter for cache select
- Handle database connection errors
- Upping requirement to Django 1.5+
0.3.3
- Python 3 compatibility.
0.3.2
- Added database connection close.
- Added better exceptions handler.
0.3.1
- Added index_together entries for faster queries on large cron log db tables.
- Upgraded requirement hence to Django 1.5 and South 0.8.1 since index_together is new to Django 1.5
0.3.0
- Added Django 1.4+ support. Updated requirements.
0.2.9
- Changed log level to debug() in CronJobManager.run() function.
0.2.8
- Bug fix
- Optimized queries. Used latest() instead of order_by()
0.2.7
- Bug fix.
0.2.6
- Added end_time to list_display in CronJobLog admin
0.2.5
- Added a helper function ( run_cron_with_cache_check ) in runcrons.py
0.2.4
- Capability to run specific crons using the runcrons management command. Useful when in the list of crons there are few slow onces and you might want to run some quicker ones via a separate crontab entry to make sure they are not blocked / slowed down.
- pep8 cleanup and reading from settings more carefully (getattr).
- Downloads (All Versions):
- 81 downloads in the last day
- 1196 downloads in the last week
- 4973 downloads in the last month
- Author: Sumit Chachra
- Keywords: django cron
- Categories
- Package Index Owner: Tivix
- DOAP record: django-cron-0.3.4.xml | https://pypi.python.org/pypi/django-cron/0.3.4 | CC-MAIN-2015-40 | refinedweb | 750 | 57.47 |
Everything in Python is an object. And what every newcomer to Python should quickly learn is that all objects in Python can be either mutable or immutable.
Lets dive deeper into the details of it? an immutable.
Now comes the question, how do we find out if our variable is a mutable or immutable object. For this we should understand what ?ID? and ?TYPE? functions are for.
ID. Lets look at a simple example
”’ Example 1 ”’>>> x = “Holberton”>>> y = “Holberton”>>> id(x)140135852055856>>> id(y)140135852055856>>> print(x is y) ”’comparing the types”’True”’ Example 2 ”’>>> a = 50>>> type(a)<class: ?int?>>>> b = “Holberton”>>> type(b)<class: ‘string’>
We have now seen how to compare two simple string variables to find out the types and id?s .So using these two functions, we can check to see how different types of objects are associated with variables and how objects can be changed .
Mutable and Immutable Objects
So as we discussed earlier, a mutable object can change its state or contents and immutable objects cannot.
Mutable objects:
list, dict, set, byte array
Immutable objects:
int, float, complex, string, tuple, frozen set [note: immutable version of set], bytes
A practical example to find out the mutability of object types
x = 10x = y
We are creating an object of type int. identifiers x and y points to the same object.
id(x) == id(y)id(y) == id(10)
if we do a simple operation.
x = x + 1
Now
id(x) != id(y)id(x) != id(10)
The object in which x was tagged is changed. object 10 was never modified. Immutable objects doesn?t allow modification after creation
In the case of mutable objects
m = list([1, 2, 3])n = m
We are creating an object of type list. identifiers m and m tagged to the same list object, which is a collection of 3 immutable int objects.
id(m) == id(n)
Now poping an item from list object does change the object,
m.pop()
object id will not be changed
id(m) == id(n)
m and n will be pointing to the same list object after the modification. The list object will now contain [1, 2].
So what have we seen.
Exceptions in immutability.. = (?hol objects are passed to Functions
Its important for us to know difference between mutable and immutable types and how they are treated when passed onto functions .Memory efficiency is highly affected when the proper objects are used.
For example if a mutable object is called by reference in a function, it can change the original variable itself. Hence to avoid this, the original variable needs to be copied to another variable. Immutable objects can be called by reference because its value cannot be changed anyways.
def.
Lets take a look at another example:
def updateNumber(n): print(id(n)) n += 10b = 5print(id(b)) # 10055680updateNumber(b) # 10055680print. | https://911weknow.com/mutable-vs-immutable-objects-in-python | CC-MAIN-2022-40 | refinedweb | 480 | 64.91 |
When building data science and machine learning powered products the research-development-production workflow is not linear like in traditional software development where the specs are known and problems are (mostly) understood beforehand.
There are lots of trial and error involved, including the test and use of new algorithms, trying new data versions (and managing it), packaging the product for production, end-users views and perspectives, feedback loops, and more. These make managing those projects a challenge.
Isolating the development environment from the production systems is a must if you want to assure that your application will actually work. And so putting your ML model development work inside a (docker) container can really help with:
- managing the product development,
- keeping your environments clean (and making it easy to reset it),
- most importantly, moving things from development to production becomes easier.
In this article, we will be discussing the development of Machine Learning (ML) powered products, along with best practices for using containers. We’ll cover the following:
- Machine learning iterative processes and dependency
- Version control at all stages
- MLOps vs DevOps
- Need for identical dev and prod environment
- Essentials of Containers (meaning, scope, docker file and docker-compose etc.)
- Jupyter notebook in containers
- Application development with TensorFlow in containers as microservice
- GPU & Docker
What you need to know
In order to fully understand the implementation of machine learning projects in containers, you should:
- Have a basic understanding of software development with Docker,
- Be able to program in Python,
- Be able to build basic machine learning and deep learning models with TensorFlow or Keras,
- Have deployed at least one machine learning model.
The following links might be useful to get you started if you don’t know Docker, Python or TensorFlow:
Machine learning iterative processes and dependency
Learning is an iterative process. When a child learns to walk, it goes through a repetitive process of walking, falling, standing, walking, and so on – until it “clicks” and it can confidently walk.
The same concept applies to machine learning, and it’s necessary to ensure that the ML model is capturing the right patterns, characteristics and inter-dependencies from given data.
When you are building an ML-powered product or application,you need to be prepared for the iterative process in this approach, especially with machine learning.
This iterative process is not limited to product design alone, but it covers the entire cycle of product development using machine learning.
The right patterns that the algorithm needs to make right business decisions are always hidden in the data. Data scientists and MLOps teams need to put in a lot of effort to build robust ML systems capable of performing this task.
Iterative processes can be confusing. As a rule of thumb, a typical machine learning workflow should consist of at least the following stages:
- Data collection or data engineering
- EDA (Exploratory Data Analysis)
- Data pre-processing
- Feature engineering
- Model training
- Model evaluation
- Model tuning and debugging
- Deployment
For each stage, there is a direct or indirect dependency on other stages.
Here is how I like to view the entire workflow based on levels of system design:
- The Model Level (fitting parameters): assuming that the data has been collected, EDA and basic pre-processing done, the iterative process begins when you have to select the model that fits the problem you are trying to solve. There is no shortcut, you need to iterate through some models to see which works best on your data.
- The Micro Level (tuning hyperparameters): once you select a model (or set of models), you begin another iterative process at the micro level, with the aim to get the best model hyperparameters.
- The Macro Level (solving your problem): the first model you build for a problem will rarely be the best possible, even if you tune it perfectly with cross-validation. That’s because fitting model parameters and tuning hyperparameters are only two parts of the entire machine learning problem-solving workflow. At this stage, there is a need to iterate through some techniques for improving the model on the problem you are solving. These techniques include trying other models, or ensembling.
- The Meta Level (improving your data): While improving your model (or training the baseline) you may see that the data that you are using is of poor quality (for example, mislabeled) or that you need more observation of a certain type (for example, images taken at night). In those situations improving your datasets and/or getting more data becomes very important. You should always keep the dataset as relevant as possible to the problem you are solving.
These iterations will always lead to lots of changes in your system, so version control becomes important for efficient workflow and reproducibility.
Version control at all stages
Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later. Because of the iterative processes involved in the development of a ML-powered product, versioning has become crucial to the success of the product, and future maintenance or optimization.
Files in your ML workflow, and systems such as notebooks, datasets, scripting files – they all need versioning.
There are many tools and best practises for versioning these files depending on your team’s preferences. I’ll share what works best for me.
Generally, you will use version control systems such as Git, Apache Subversion (SVC), or Concurrent Version Systems (CVS). But using only one of these systems might not be the best for machine learning projects, because of the kind of files used in the ML workflow. It’s best to add other useful tools for efficient versioning of each file.
Data Versioning: most companies store data in a database or cloud storage / buckets, like the Amazon S3 bucket or Google Cloud Storage, where data can be pulled when needed.
Pulling a sample to best represent the problem you are trying to solve might be iterative, and it becomes important to version the data used to train a machine learning model.
There is a limit to the volume and size of file you can push to a version control platform and sometimes, the data you will be working with comes in gigabytes, so it’s not the best way to approach this.
With tools like DVC and Neptune, data versioning becomes easier. Below are some useful links to get you started with data version control:
Notebook Versioning: Jupyter, Colab notebooks generate files that may contain metadata, source code, formatted text, and rich media.
Unfortunately, this makes these files poor candidates for conventional version control solutions, which work best with plain text. The problem with these notebooks is that they are human-readable JSON .ipynb files. It is uncommon to edit the JSON source directly because the format is so verbose. It’s easy to forget required punctuation, unbalance brackets like {} and [], and corrupt the file.
More troublesome, Jupyter source code is often littered with cell output stored as binary blobs. Little changes in the notebook, such as rerunning with new data, will look like a significant change in the version control commit logs.
Some built-in solutions to effectively keep track of the file convert the notebook to HTML, or to a Python file. External tools that you can use for this are nbdime, ReviewNB, Jupytext and Neptune, to mention a few.
My choice is Neptune, because it can integrate with Jupyter and JupyterLab as an extension. Version control is just one of Neptune’s features. The team, project, and user management features make this more than a version control tool, but the software’s lightweight footprint may make it a compelling candidate regardless.
EDITOR’S NOTE
Your entire project can be versioned using version control systems, and this becomes even easier with containers, which we’ll soon discuss.
MLOps vs DevOps
Before we dive into containers for machine learning with TensorFlow, let’s quickly go through the similarities and differences between MLOps and DevOps.
MLOps (Machine Learning Operations) aims to manage the deployment of all types of machine learning (deep learning, federated learning, etc) in large-scale production environments.
DevOps (Development and Operations) is a set of practices that combines software development and IT operations at large scale. It aims to make development cycles shorter, increase deployment velocity, and create dependable releases.
DevOps principles also apply to MLOps, but there are some aspects of machine learning workloads that require a different focus or implementation.
Having in mind the basic ML workflow we discussed earlier, we can pinpoint the following differences in MLOps and DevOps:
- Team Skills: an MLOps team has research scientists, data scientists, and machine learning engineers who serve the same role as a software engineer in a DevOps team. The ML engineers have the essential skills of a software engineer, combined with data science expertise.
- Development: DevOps is linear, and MLOps is more experimental in nature. The team needs to be able to manipulate model parameters and data features, and retrain models frequently as the data changes. This requires more complex feedback loops. Also, the team needs to be able to track operations for reproducibility without impeding workflow reusability.
- Testing: in MLOps, testing requires additional methods beyond what is normally done in DevOps. For example, MLOps requires tests for data validation, model validation, testing of model quality, model integration and differential tests.
- Deployment : the deployment process in MLOps is similar to DevOps, but it depends on the type of ML system you’re deploying. This becomes easier if the designed ML system is decoupled from the entire product cycle, and acts as an external unit to the software.
- Production: a production machine learning model is continuous and can be more challenging than traditional software in production. The intelligence can degrade with time as user data changes. MLOps needs model monitoring and auditing to avoid the unexpected.
Need for identical development and production environment
In software engineering there are typically two stages of product development – development and production.This can be reduced to one when cloud-native is the choice for both development and production, but the majority of ML apps are developed on local PCs before being pushed to cloud.
The production environment is the reproduction of the development environment, with a focus on the key dependencies for smooth product performance.
Reproducing the environment in MLOps, or manually keeping track of these dependencies can be challenging because of the iterative processes involved in the workflow.
For Python developers, tools such as Pip and Pipenv are often used to bridge this gap, but containers are a better way to keep things cleaner.
Essentials of Containers in MLOps
A container is a standard unit of software that packages code and all its dependencies, so the application runs quickly and reliably from one computing environment to another.
With containers, there is no need for selective cloud or any computing environment configuration for production, because they can run almost everywhere.
Using containers to separate project environments makes it flexible for ML teams to test-run new packages, modules and framework versions, without breaking the entire system, or having to install every tool on a local host.
Think of a container as a virtual machine. They have a lot in common, but function differently because containers virtualize the operating system instead of hardware. Containers are more portable and efficient.
Containers are an abstraction at the app layer that packages code and dependencies together. Multiple containers can run at the same machine, and share the OS kernel with other containers, each running as isolated processes in user space.
Containers take up less space than VMs, because virtual machines are an abstraction of physical hardware, turning one server into many servers. Each VM includes a full copy of an operating system, the application, necessary binaries and libraries.
While there are many container running tools, we’ll focus on Docker.
A container is a great way to do research and experimentation, with flexibility to add data analytics and machine learning tools (like jupyter notebook and jupyter lab). Docker containers on development hosts are a great tool for model development, as trained models can be saved and turned into self-contained images, and used as a microservice.
This eliminates the risk of having to delete an entire virtual environment, or reinstall the operating system if crashed by bad packages or frameworks. With containers, all that is needed is to delete or rebuild the image.
One key thing that is worth noting is that the container file system goes away when the image is removed or stopped.
Follow the guides below to get Docker installed on your local machine if you don’t have it. Depending your host operating system, you can download it via these links:
Once installed, you can type “docker” in your terminal to check if your host machine recognises the command.
The output should look similar to this:
Jupyter notebook in containers
Being able to run a jupyter notebook on docker is great for data scientists, because you can do research and experimentation with or without directly interfacing the host machine.
Jupyter is designed to be accessed through a web browser interface, which is powered by a built-in web server. It is best run with official images (which include ipython & conda), standard python libraries, all required jupyter software and modules, and additional data science and machine learning libraries. The development environment can be set up by just pulling an official image.
To get started, let’s pull the official Jupyter TensorFlow image, which we’ll use as our development environment in this project. You can look through the list of images and their content on the official Jupyter site.
When we first run this command, the image gets pulled and cashed upon subsequent running. We can run this command directly on the terminal, but I prefer to run it via docker compose, since we’ll be running multiple-container applications that work together. With this, typos can be avoided.
Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.
The project compose file is shown in the figure below.
We defined two services (tensorflow and tf_model_serving). Focusing on the highlighted part (tensorflow service to use the jupyter/tensorflow-notebook image), let’s explain each of the tags:
- Image: this is used to specify the docker image to be used for the service. In our case, we have specified the official tensorflow jupyter notebook.
- Ports: we use this to map the host machine port to the container port. In this case, since jupyter runs on port 8888 by default, we have mapped this to port 8888 on the local host, but feel free to change the localhost port if 8888 has already been used by another service.
- Volumes: with this, we can bind-mount a local host directory to our working directory in the container. This is very useful to save intermediate files such as model artefacts to bind localhost directory, since container files get removed once it stops running. In this case, we have bind-mounted the host notebook folder to projectDir (project directory on the running container notebook).
- Environment: the official jupyter image can be run as a jupyter notebook or jupyter lab. With the environment tag, we can specify our preferred choice. Setting the “JUPYTER_ENABLE_LAB” to yes indicates that we have decided to run jupyter as a lab and not notebook.
To run a service using docker compose, we can run “docker-compose up <service name>”. For the TensorFlow jupyter service, we run “docker-compose up tensorflow”. This command pulls the image from docker hub for the first time:
Subsequent running of the command runs the cashed imaged directly, without the need to pull again just as shown below.
We can access this notebook via the web url displayed in the terminal as highlighted above, and intermediate logs are shown.
Now that the notebook is up and running, we can carry out our research and experimentation on the ML-powered product we’re working on. Any package that is not included by default can be installed using “!pip install <package name>” in any of the code cells. To check installed packages, you can run “!pip freeze”.
Application development with TensorFlow in containers
For this project, we will develop an automated image classification solution for photographs of marine invertebrates taken by researchers in South Africa, and serve the model with Tensorflow serving. You can read more about the problem and the provided dataset on ZindiAfrica.
I won’t be going deep into how to build or optimize the model, but I’ll work you through how to get it saved in the TensorFlow serving format, and serve in a container as a microservice.
You can work through the notebook for clarification on how the model was built with TensorFlow via the GitHub link at the end of this article. Some of images in the 137 classes are shown below:
Once the model is built and trained on these images with satisfying evaluations, we can load the .h5 keras model saved during training and save it in the format required by TensorFlow serving as shown below:
import time from tensorflow.keras.models import load_model ts = int(time.time()) loadmodel = load_model('model.h5') loadmodel.save(filepath=f'/home/jovyan/projectDir/classifier/my_model/{ts}', save_format='tf')
This will create some artifacts needed for serving just as shown in the figure below:
TensorFlow Serving makes it easy and efficient to expose a trained model via a model server. It provides flexible APIs that can be easily integrated with an existing system.
This is similar to how you would have used frameworks like Flask or Django to expose the saved model, but TensorFlow Serving is more powerful and a better choice for MLOps, as there is a need to keep track of model version, code separation and efficient model serving.
To know more about why I chose to use this over other traditional frameworks, check the “Building Machining Pipelines” book.
Model Serving Architecture
The goal is to build and deploy this as a microservice, using containers as a REST API which can be consumed by a bigger service, like the company website. With TensorFlow serving, there are two options to API endpoints – REST and gRPC.
- REST: REpresentational State Transfer is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other. It defines a communication style on how clients communicate with web services. Clients using REST communicate with the server using standard HTTP methods like GET, POST, and DELETE. The payloads of the requests are mostly encoded in JSON.
- gRPC: open-source remote procedure call system, initially developed at Google in 2015. It is preferred when working with extremely large files during inference, because It provides low-latency communication and smaller payloads than REST.
Model Serving Architecture
While the two APIs (REST and gRPC) are available for consumption, the focus is on the REST API.
I simulate this using client code in a container jupyter notebook. To achieve this, we can embed our saved model in a custom docker image built on top of the official TensorFlow serving image.
Client requests can be balanced or evenly distributed across a number of TensorFlow Serving replicas (4 for our use case), using a single node balancer with docker swarm or kubernetes.
I will use docker swarm to orchestrate both our client notebook and the custom image since it is part of my installed docker application.
In the docker compose yml file, we will need to add the TensorFlow Serving service to it just as shown below:
Let’s quickly work through the tags for the tf_model_serving service
- Image: our custom serving docker image – tf_serving – will be built and tagged classifier_model.
- Build: the compose file for tensorflow_model_serving service has a build option which defines context and name of the docker file to use for building. In this case, we have it named Dockerfile with the following docker commands in it:
This file will be used by the docker compose file to build the custom serving image.
FROM: Used to specify the base image to be used. This will be pulled from docker hub if this is the first time you are pulling the image.
COPY: Used to tell docker what to copy from our host machine to the image being built. In our case, we are copying the saved model in the ./notebooks/classifier into the /models/ directory in the custom TensorFlow serving image.
ENV: MODEL_NAME=my_model tells TensorFlow serving where to look for the saved model upon request.
- Deploy: With this tag, we can specify the number of replicas for load balancing (4 in our case). Setting endpoint_mode to vip makes this container accessible in service discovery by Virtual IP. The containers provisioned in docker swarm mode can be accessed in service discovery via a Virtual IP (VIP), and routed through the docker swarm ingress overlay network, or via a DNS round robin (DNSRR).
To build this custom serving image, run the command “docker-compose build <service name> “ (in our case, “docker-compose build tf_model_serving”) in your terminal as shown below:
After the custom image has been built, we can use docker swarm to start up the services listed in the docker compose file using the commands below:
“docker swarm init”
“docker stack deploy -c <docker compose file> <stack name> . in our case,
“docker stack deploy -c docker-compose.yml tf”
With this, docker will create a virtual network which allows all containers to communicate with each other by name.
To check the logs each containers, we can run the command below
“docker service logs <any of the service names above>.
Running “docker service logs tf_tf_model_serving” will show the logs:
Now that the server is on, we can simulate how this will be consumed as a microservice using the client code notebook in the running jupyter notebook, as shown in the model architecture.
To access the notebook web url, we can run service log on it:
“docker service logs tf_tensorflow”
Running in a browser should give something similar to this:
I kept 10 random images from the dataset in a folder to test the API from the notebook. These images are shown below:
Each has been reshaped into 224*224 size, just like I did while training the model. Before sending a request to the API, let’s quickly construct the api endpoint just as shown in the code snippet below:
tf_service_host = 'tf_model_serving' model_name = 'my_model' REST_API_port = '8501' model_predict_url = 'http://'+tf_service_host+':'+REST_API_port+'/v1/models/'+model_name+':predict'
You will notice that this is generic and the general format may look like: http://{HOST}:{PORT}/v1/models/{MODEL_NAME}:{VERB}
- HOST: The domain name and IP address of your model server or service name. In our case, we have declared this as “tf_service_host” which can serve as our host.
- PORT: This is the server port for the url, for REST API, the port is 8501 by default as seen in the architecture above.
- MODEL_NAME: This is the name of the model we are serving. We set this “my_model” while configuring.
- VERB: This can be: classify, regress or predict, based on the model signature. In our case, we use “predict”.
We can have a prediction function with which we can pre-process input images from clients into the required format (“JSON”) before sending it to the API.
def model_predict(url,image): request_json = json.dumps({"signature_name": "serving_default", "instances": image.tolist()}) request_headers = {"content-type": "application/json"} response_json = requests.post(url, data=request_json, headers=request_headers) prediction = json.loads(response_json.text)['predictions'] pred_class = np.argmax(prediction) confidence_level = prediction[0][pred_class] return (pred_class,confidence_level)
In the code snippet above, the first line – “json.dump” – is used to declare JSON data payload which is the format required by the API.
The instance parameter is set to the image we want to classify. In line 3, we send a post request to the server passing the url, json file, and the headers.
We then get the prediction out of the return json info with the key “prediction”. Since we have 137 classes in the dataset, we can get the exact predicted class using numpy argmax function, and also obtain the model prediction confidence level. These two were returned as Python tuples.
Invoking this function on the 10 test data with for loop as shown below:
predicted_classes = [] for img in test_data: predicted_classes.append(model_predict(url = model_predict_url, image=np.expand_dims(img,0))) This will return [(0, 0.75897634), (85, 0.798368514), (77, 0.995417), (120, 0.997971237), (125, 0.906099916), (66, 0.996572495), (79, 0.977153897), (106, 0.864411), (57, 0.952410817), (90, 0.99959296)]
We can structure the result as shown below:
for pred_class,confidence_level in predicted_classes: print(f'predicted class= {Class_Name[pred_class]} with confidence level of {confidence_level}') With the output predicted class= Actiniaria with confidence level of 0.75897634 predicted class= Ophiothrix_fragilis with confidence level of 0.798368514 predicted class= Nassarius speciosus with confidence level of 0.995417 predicted class= Salpa_spp_ with confidence level of 0.997971237 predicted class= Solenocera_africana with confidence level of 0.906099916 predicted class= Lithodes_ferox with confidence level of 0.996572495 predicted class= Neolithodes_asperrimus with confidence level of 0.977153897 predicted class= Prawns with confidence level of 0.864411 predicted class= Hippasteria_phrygiana with confidence level of 0.952410817 predicted class= Parapagurus_bouvieri with confidence level of 0.99959296
GPU and Docker
Docker is a great tool to create containerized machine learning and data science environments for research and experimentation, but it will be great if we can leverage GPU acceleration (if available on a host machine) to speed things up, especially with deep learning.
GPU-accelerated computing works by assigning compute-intensive portions of an application to the GPU, providing a supercomputing level of parallelism that bypasses costly, low-level operations employed by mainstream analytics systems.
The use of GPU on host for data science projects depends on two things:
- GPU support host machine
- GPU support packages and software
Since docker isolates containers from a host to a large extent, giving containers access to GPU-accelerated cards is a trivial task to achieve.
At the time of writing this article, docker community officially supports GPU acceleration for containers running on Linux hosts. While there are workarounds for windows and mac OS hosts, achieving this could be a very difficult task.
One way to know if your running Tensoflow jupyter container has access to GPU is with the code snippet below:
tf.config.experimental.list_physical_devices('GPU') print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Even though my host machine has GPU support, I have not been able to leverage on this because I’m running this on macOS.
Nevertheless, docker is the easiest way to run TensorFlow with GPU support. Click here to set up a TensorFlow docker image with GPU support on a Linux host.
Conclusion
Here is the Github link I promised to the project we worked on. Check it out!
Thank you for reading this tutorial, I hope it was helpful. | https://neptune.ai/blog/data-science-machine-learning-in-containers | CC-MAIN-2020-50 | refinedweb | 4,538 | 51.78 |
Source Code for Search Engine Project in java - Java Beginners
Source Code for Search Engine Project in java Hello Sir ,I want Java Project for Search Engine(like google),How I can Make it,Plz Give Me Complete Source Code Of Search Engine Project in Java. Hi Friend,
Please
Java is an opensource program or not? why???
Java is an opensource program or not? why??? Java is an open source program or not.. why
Building Search Engine Applications Using Servlets !
using Java Servlets. You can Download
the source code of search... application.
Search Engine Code and Updates
The source code... these days.
This search engine shows you how to use Java Servlets
simple java search engine i have already downloaded the project simple java search engine.but i am not able to run it.can anyone help me.i have....
ABSTRACT
Title : Simple Search Engine
System Specification:
The system on which
regarding designing of web search engine - Development process
regarding designing of web search engine we want to design a web search engine in java. so, how to get started with our coding...can i get sample code for web crawlers or similar requirements... help us
struts opensource framework
struts opensource framework i know how to struts flow ,but i want struts framework open source code
Developing Search Engine in Java
Developing Search Engine in Java
In this section we will discuss about the search engine, and then show you
how you can develop your own search engine for your website
Recommendation engine code
Recommendation engine code recommendation engine code in java
java source code - Java Beginners
java source code hello Sir,
Im a beginner in java.im greatly confused, so plz send me the source code for the following concept:
Telephone... and phone number for N subscribers and perform the following operations :
1. Search
Java source code
Java source code How are Java source code files named
java source code
java source code java source code to create mail server using struts2
Source Code for Implementing Search Feature in JSF/JSP using Servlet - Java Beginners
Source Code for Implementing Search Feature in JSF/JSP using Servlet How do I write the source code to implement search feature in JSF/JSP using... Table
Id
Name
Dept
DOB
Date
Search By Name, Dept, DOB
Id Name Dept
source code
source code how to use nested for to print char in java language?
Hello Friend,
Try the following code:
class UseNestedLoops{
public static void main(String[] args){
char[][] letters = { {'A', 'B'}, {'C','D
request for java source code
request for java source code I need source code for graphical password using cued-click points enabled with sound signature in java and oracle 9i as soon as possible... Plz send to my mail
Open Source Game Engine
of the engine source, you must make your source code available for others to use under...;
Open Source Game Development
A 3D game engine is a complex collection of code...Open Source Game Engine
Genesis3D Open Source Engine
Genesis3D
Java Source code
Java Source Code for text chat application using jsp and servlets Code for text chat application using jsp and servlets
Download Search Engine Code its free and Search engine is developed in Servlets
web server.
To test your search engine key... engine should work.
Download Search Engine
Problem with Java Source Code - Java Beginners
Problem with Java Source Code Dear Sir I have Following Source Code ,But There is Problem with classes,
plz Help Me.
package mes.gui;
import...){
super(390,300,"", new String[] {"Add","Save","Search","Edit","Cancel
Java Source code - Java Beginners
Java Source code Write a Multi-user chat server and client
search engine build by lucene and eclipse
search engine build by lucene and eclipse Hi,
here is the code...);
frame.setTitle("SEARCH ENGINE");
frame.setSize(500, 400);
frame...());
btnsrc = new JButton("Search");
label = new JLabel("Query
Search Engine
Search Engine I have gone through the below mentioned link document to create search engine and fetch the data from mysql database.But i am getting errors.
Error: Notice
Open Source Workflow Engines in Java
, the Java XPDL Open Source Workflow Engine you get a complete workflow solution... Business engine is a flexible, modular, standards-compliant Open Source Java...Open Source Workflow Engines in Java
The Open For Business Project: Workflow
Java source code - Java Beginners
Java source code Write a small record management application for a school. Tasks will be Add Record, Edit Record, Delete Record, List Records. Each Record contains: Name(max 100 char), Age, Notes(No Maximum Limit). No database
save links clicked in search engine results
save links clicked in search engine results hello
i need to access search engine results in my program(any search engine).ie suppose i give... code.here's the code:
<form action="">
Open Source Jobs
Open Source Jobs
Open Source Professionals
Search firm... transfers.
Open Source Job Schedulers in Java
On some... engine enforces a site-wide corporate layout. As true Open Source software, OpenCms
Open Source Full Text Search Engines written in Java
source code program - Java Beginners
source code program I need the source code for a program that converts temperatures from celsius to fahrenheit and vice versa, as well as converting kilometers to miles and vice versa using Java "classes". Hi
Open Source Metaverses
Open Source Metaverses
OpenSource Metaverse Project
The OpenSource Metaverse Project provides an open source metaverse engine along the lines....
The OpenSource Metaverse Project was created because a strong demand exists, and large
Need Java Source Code - JDBC
Need Java Source Code I have a textfield for EmployeeId in which the Id, for eg: "E001" has to be generated automatically when ever i click... be implemented. Hi friend,
Please send me code because your posted
Building Search Engine Applications Using Servlets !
Source Code cls - Java Beginners
Source Code cls Dear RoseIndia Team,
Thanks for your prompt reply to my question about alternate to cls of dos on command line source code.
I have two submissions.
1. Instead of three lines if we simply write
reg : the want of source code
reg : the want of source code Front End -JAVA
Back End - MS Access
Hello Sir, I want College Student Admission Project in Java with Source code...) Available Seats
and etc.
plz Give Me Full Source code with Database
calendra.css source code - Java Beginners
calendra.css source code hello i need the source code... and year are getting displayed Hi Friend,
Try the following code...;
cursor: pointer;
}
You can also download the code from the following link
B+ tree JAVA source code for implementing Insertion and Deletion - Java Beginners
B+ tree JAVA source code for implementing Insertion and Deletion Can anyone plz mail de B+ tree JAVA source code for implementing Insertion...("Search value is: " + root.Search(24));
System.out.println("Search value
SEARCH AND SORT
SEARCH AND SORT Cam any one provide me the code in java that :
Program to search for MAX,MIN and then SORT the set using any of the Divide and conquer method
Hibernate Search
enterprise applications in Java technology.
Hibernate search integrates with the Java... engine capabilities. In Hibernate Search, both the object-relational mapping capacity... search engine capability to Hibernate search.
Automatic insertion
Help on this java code for online library search
Help on this java code for online library search I have written the following java code for simple library book search. but its having some errors ... please help me on this code.
import java.sql.*;
import java.awt.
Welcome to Free search engine secrets: webmaster's guide to search engine
engines, so each search engine submission is your most cost effective form... their search engine placement.
If you... and experience the Search Engine World.
Here I am assuming
Open Source Content Management
code for open-source CMSes is freely available so it is possible to customize...Open Source Content Management
Introduction to Open Source Content Management Systems
In this article we'll focus on how Open Source and CMS combine
Search engine for email
Search engine for email Build a search engine which will look at your email inbox and sort your email into 5 or more bins according to some criteria (e.g. date, email address, text of the email
search and sort techniques in java
search and sort techniques in java Hi i attened an interview recently... they asked to write all searching and sorting technique codes in java.. i... any utility methods .....i could answer few but not all..i need datalied code
Linear search in java
Linear search in java
In this section we will know, what is linear... or a string in array.
Example of Linear Search in Java:public class LinearSearch... and executing the
above program.
Download Source Code
Google Desktop Search
capabilities, this plug-in uses the Google Desktop Search Engine instead... speed up the
search by selecting just an extension to search for (like java... Google Desktop Search
linear search - Java Beginners
linear search How do i use a linear search for a 2 dimensional hard... friend,
Code to solve the problem :
public class LinearSearch
{
// Search "array" for the specified "key" value
public static
JAVA: Recusrion, Binary Search
JAVA: Recusrion, Binary Search I want to learn about Binary Search... is resolved, it is removed from the list.
Search appointments by owner and by date.
Search medical records by animal name, owner, and animal kind (like show all
download java source code for offline referral
download java source code for offline referral how can i download complete java tutorial from rose india so that i can refer them offline
Binary Search!!! - Java Beginners
Binary Search!!! Hi Sir,
My question is quite simple. im only... error.
Thanks.
The code is below:
import javax.swing.*;
public class... = Integer.parseInt(searchKeyText);
position = search(searchKey, arrayList, 0
View source code of a html page using java ..
View source code of a html page using java .. I could find the html source code of a web page using the following program,
i could get the html code
Screen scrapper tool java source code
Screen scrapper tool java source code From where can i dload the souce code for this screen scrapper tool ?
Please let me know.
Thanks
Open Source software written in Java
Code Coverage
Open Source Java Collections API...Open Source software written in Java
Open Source Software or OSS for short is software which is available with the source code. Users can read, modify
about search engine
about search engine Hi i am novice in jsp. i am developing web site in that i want to search product by its name and display it by its image with description,so want some help.
Thank you
Open Source Project Management
resources management (HR), provider & freelance database, search engine... template engine enforces a site-wide corporate layout. As true Open Source software...Open Source Project Management
Open Source Project Management
Create test engine - Java Beginners
Create test engine How can create a test engine dat generates questions randomly using javax.swing in java
source code - Java Server Faces Questions
source code hi deepak i need a program's source code in javascript which will response to mouse event.
with description of onmouseout nd onmouseover...
waiting 4 ur reply Hi friend,
Code for onmouseout nd
Open Source Code
number of items in those categories.
Java 2 source code release
With the release of Sun's Java 2 source code comes the unveiling...) source code, find out how this new model differs from previous Java source
Open Source Browser
in Java. It serves a dual purpose of being an experimental
code base for trying..., the name of the public release, only exists as C++ source code. You have... contains a subset of the early source code from Communicator 5.0. Therefore, it has
)price.jsp:
<%@page language="java" import ="java.sql.*" %>
<%
String code...shoping items billng source code Hi, I am doing a project on invoice making, I am unable to make code for the billing, I have a n jsp page "invc.jsp
Need source code - Swing AWT
Need source code Hai, In java swing, How can upload and retrieve the images from the mysql database? Hi Friend,
To upload and insert image in database, try the following code:
import java.sql.*;
import
Open Source JVM
. It features a state-of-the-art and efficient
interpreter engine. Its source code...Open Source JVM
Java Virtual Machine or JVM
for short is a software execution engine to run the java programs. Java Virtual
Machine is also known
java source code to create mail server using struts2
java source code to create mail server using struts2 java source code to create mail server using struts2
Binary Search in Java
Binary Search in Java
In this section, we are going to search an element from an array using Binary Search. The advantage of a binary search over a linear search is astounding for large numbers. It can be done either recursively
Java Array Binary Search example
Java Array Binary Search
It is a method for searching the array element... example demonstrates how to do a binary search on the Java array object... the binary search algorithm.
It returns the index of the found element
Finding searching phrase of a search engine
Finding searching phrase of a search engine how to find out searching phrase of a search engine..? like, if visitors enter the keyword to google, is is any possible to get that keyword
Hibernate Criteria Case Insensitive Search.
it in the same folder where you are going to save your source code.
Now create Persistent...Hibernate Criteria Case Insensitive Search. How to use Case Insensitive Search in Hibernate?
The Case Insensitive ignores the case
i need attendce management system source code in java
i need attendce management system source code in java i need attendance management system source code in java
Open Source E-mail
code for complete control.
POPFile: Open Source E-Mail... is considering making its Java Enterprise System server software open-source, John...Open Source E-mail Server
MailWasher Server Open Source
JSP Search Example code
as:
Download Source Code...
JSP Search - Search Book Example
Search Book Example
In this tutorial we
Open Source e-commerce
with the source code freely available for alteration and customization. Using an open source shopping cart as the engine behind your site gives you a thoroughly... code and J2EE best practices.
Open Source E
Search Engine Interface
Search Engine Interface
In this section we will describe about the search and index interface of our
search engine. For searching and displaying the result we
Open Source Directory
Open Source Directory
Open Source Java Directory
The Open Source Java... architecture includes source code for both directory client access and directory servers... unveiled the Red Hat Directory Server and simultaneous release of the source code
Open Source HTML
;
Open Source HTML Parsers in Java
NekoHTML is a simple HTML... element tags.
Open Source Search Engines
Open source search engines allow participants to make changes and contribute
Path of source code
Description:
This example demonstrate how to get the path of your java program file. The
URI represents the abstract pathname and URL construct from
URI.
Code:
import java.io.
Open Source Blog
discoveries in our search for open source workflow management tools. For tools that we find interesting, we download the code, try to execute the engine, or even get our...Open Source Blog
About Roller
Roller is the open source blog server
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/76086 | CC-MAIN-2016-07 | refinedweb | 2,600 | 62.07 |
We will look into two important python object functions that are very helpful in debugging python code by logging useful information regarding the object.
Table of Contents
Python __str__()
This method returns the string representation of the object. This method is called when
print() or
str() function is invoked on an object.
This method must return the String object. If we don’t implement __str__() function for a class, then built-in object implementation is used that actually calls __repr__() function.
Python __repr__()
Python __repr__() function returns the object representation in string format. This method is called when
repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.
What’s the difference between __str and __repr__?
If both the functions return strings, which is supposed to be the object representation, what’s the difference?
Well, the __str__ function is supposed to return a human-readable format, which is good for logging or to display some information about the object. Whereas, the __repr__ function is supposed to return an “official” string representation of the object, which can be used to construct the object again. Let’s look at some examples below to understand this difference in a better way.
Python __str__ and __repr__ examples
Let’s look at a built-in class where both __str__ and __repr__ functions are defined.
>>> import datetime >>> now = datetime.datetime.now() >>> now.__str__() '2020-12-27 22:28:00.324317' >>> now.__repr__() 'datetime.datetime(2020, 12, 27, 22, 28, 0, 324317)'
It’s clear from the output that __str__() is more human friendly whereas __repr__() is more information rich and machine friendly and can be used to reconstruct the object. In fact, we can use repr() function with eval() to construct the object.
>>> now1 = eval(repr(now)) >>> now == now1 True
Both of these functions are used in debugging, let’s see what happens if we don’t define these functions for a custom object.
class Person: def __init__(self, person_name, person_age): self.name = person_name self.age = person_age p = Person('Pankaj', 34) print(p.__str__()) print(p.__repr__())
Output:
<__main__.Person object at 0x10ff22470> <__main__.Person object at 0x10ff22470>
As you can see that the default implementation is useless. Let’s go ahead and implement both of these methods.
class Person: def __init__(self, person_name, person_age): self.name = person_name self.age = person_age def __str__(self): return f'Person name is {self.name} and age is {self.age}' def __repr__(self): return f'Person(name={self.name}, age={self.age})' p = Person('Pankaj', 34) print(p.__str__()) print(p.__repr__())
Output:
Person name is Pankaj and age is 34 Person(name=Pankaj, age=34)
Earlier we mentioned that if we don’t implement __str__ function then the __repr__ function is called. Just comment the __str__ function implementation from the Person class and
print(p) will print
{name:Pankaj, age:34}.
Summary
Both __str__ and __repr__ functions return string representation of the object. The __str__ string representation is supposed to be human-friendly and mostly used for logging purposes, whereas __repr__ representation is supposed to contain information about object so that it can be constructed again. You should never use these functions directly and always use str() and repr() functions.
Sorry, but this is an awful article.
The difference between __repr__ and __str__ is that __repr__ is meant for developers (eg. debugging) and __str__ is used for users.
You didn’t explain this simple difference and instead wrote many very or slightly wrong things –
You write in the summary “__str__ must return string object whereas __repr__ can return any python expression.” which is wrong! – __repr__ needs to return string as well, as you showed earlier!
You use class variables and override them with instance variable, why? thats just not needed and beginners will think it is needed (perhaps you think its necessary?)
You call the dunder methods directly (eg `p.__str__()`) instead of using the proper builtins (`str(p)` and `repr(p)`)
You use camelCase arguments when the python style is snake_case (underscores)
You write there is no fallback for missing __repr__ but you clearly show the fallback (Python shows the type and id in hex). Not having a fallback would be something like raising NotImplementedError.
There is a convention (but not really necessary) to have repr return a *string* that looks like the constructor for the object, so one can copy paste the repr outout to get identical copy.
eg. a proper example would be:
“`
class Person:
def __init__(name, age):
self.name = name
self.age = age
def __repr__(self):
return f”””Person(name=”{self.name}”, age={self.age})””” # developer friendly
def __str__(self):
return f”{self.name} is {self.age} years old” # use friendly
“`
I don’t normally bash random people for being wrong, but this article is at the top of the Google search results for repr vs str in python, and a lot of beginners will read this.
1. None of these methods are to be used directly by users. The article just shows the difference between them, don’t suggest to use it in the code.
2. __repr__ can return anything, as shown in the code where it’s returning dict. BUT, when we call the repr() function, it calls __repr__, and that time, it has to return the string. I think you didn’t get this very minute difference.
3. This article is not meant to explain class and instance variables, it’s kept simple so that everyone can easily understand and don’t get into the complexities of the code. Please refer to this for class variables:
4. I agree that the variable names should use underscores, not camel case. I will fix it.
5. The meaning of “fallback” is that if “this” is missing, I will use “that”. When __str__ is missing, __repr__ is used. But, if __repr__ is missing, it doesn’t look for any other method.
Finally, I don’t usually reply to junk comments but it looked like you have good knowledge of Python. I hope my answer clarifies all your doubts.
Thank you for replying and thank you for posting my comment as is, I appreciate both very much.
1. The same way as x.__len__() is meant to be used by using the builtin len(x), then x.__repr__ and x.__str__ are meant to be used by str(x) and repr(x). It very much requires some mention in an introductory article about this.
For completeness, you can mention __format__ and what happens when you do print(x) or f”{x:bla}”, as that is where these methods will be called implicitly, but really talking about methods __repr__/__str__ without mentioning the builtin repr/str is missing an important part of the story of these methods.
2. __repr__ can return anything, *just as much as __str__ can return anything*. both act exactly the same way in this regard. It’s only when they will be used by Python (eg. to convert to a string by a str/print/format functions) or by the debugger (repr is used eg. to show the value of a variable when stopped in breakpoint) THEN it will throw an exception – there is no difference between repr and str in this matter. Again, I can implement __str__ to return a dictionary and call it just fine with x.__str__(). but print(x) will fail. It is the same for both __str__ and __repr__, you should not return anything other the str types from them, or else they will crash when used, just like you can return a dictionary from __len__ it will work if you call x.__len__() but it will crash when you use len(x).
3. Exactly, so why complicate the example and write class variables that you will not use? you can delete them from your example and it will not change anything. Beginners reading this will use it as an example so it better not confuse them.
As you understand, I’m not new to Python, I’ve been developing in it for 12 years now and read quite a few books about it. A colleague of mine who is new to Python was confused about the difference between __str__ and __repr__ and I was horrified to see him write __repr__ method that returned dictionary instead of a string, which apparently he learned from this article.
Again, I appreciate your reply and that you posted my comment, when it was easy to delete and ignore. It shows great character and I salute you for this. I am not writing this to have an ego war with a stranger on the internet. I am writing this with hope that you will edit your article, for the sake of new developers reading.
1. I got your point, added a small section not to use these methods directly.
2. I got the point and confusion created by the wording of the article, I have removed some unwanted sections and made is more clear now.
3. You are right, I didn’t look at the example more clearly. I have edited the code to remove unwanted variables.
Thanks for your comments, it helped in making the article better. I will look forward to your comments in the future too.
PS: We don’t spam even if you type your real email id, I have met some good folks through some of the comments left by them on the blog. Once a very popular person from the Java area left a comment, later on, we got connected over Twitter and we became good friends. 🙂
Thanks for updating the article, I think it is perfect now
and added my real email in case you want to continue the dialog in private 🙂
Awesome. I will look forward to your comments in other articles too. And thanks for providing the real email id, will connect with you soon. 🙂
“Sorry, but this is an awful article.”
What an awful way to start a comment. I hope one day you’ll be as passionate about manners as you are about programming.
Hi Pankaj – I still dont understand the difference between the __str__ and __repr__. From your notes you mentioned Python __repr__() function returns the object representation. It could be any valid python expression such as tuple, dictionary, string etc, whereas __str__() represent string representation of the Object.
I tried added an expression (return “{firstName:” + self.fname + “, lastName:” + self.lname + “, age:” + str(self.age) + “}”) in __str__() method and returned it to main function, it didnt throw any error. When both __str__() and __repr__() can return only strings or string expressions i am not sure what exactly is the difference. Any inputs would be helpful
Jagan __str__() and __repr__() are almost similar
Diff is to return or print only strings str() can be used but if you are going to use any expression for example str(value[-1]) the string can’t process this input values so at that kind of situations repr() is used it can handle string and also expressions
Who is responsible for calling the __repr__() and __str__()
No one, it is implicit
QUOTE: I used str() to create __str__()
Good article. Thanks!
Very useful. Thanks.
This is really helpful article for me… | https://www.journaldev.com/22460/python-str-repr-functions | CC-MAIN-2021-21 | refinedweb | 1,884 | 73.17 |
written by Eric J. Ma on 2019-12-15 | tags: dashboarding python data science data visualization software development
This blog post is also available on my collection of essays.
As Pythonista data scientists, we are spoiled for choice when it comes to developing front-ends for our data apps. We used to have to fiddle with HTML in Flask (or Plotly's Dash), but now, there are tools in which "someone wrote the HTML/JS so I didn't have to".
Let me give a quick tour of the landscape of tools as I've experienced it in 2019.
Previously, I had test-driven
Voila.
The key advantage I saw back then was that in my workflow,
once I had the makings of a UI present in the Jupyter notebook,
and just needed a way to serve it up
independent of having my end-users run a Jupyter server,
then Voila helped solve that use case.
By taking advantage of existing the
ipywidgets ecosystem
and adding on a way to run and serve the HTML output of a notebook,
Voila solved that part of the dashboarding story quite nicely.
In many respects,
I regard Voila as the first proper dashboarding tool for Pythonistas.
That said, development in a Jupyter notebook didn't necessarily foster best practices (such as refactoring and testing code). When my first project at work ended, and I didn't have a need for further dashboarding, I didn't touch Voila for a long time.
Later, Panel showed up.
Panel's development model allowed a more modular app setup,
including importing of plotting functions defined inside
.py files
that returned individual plots.
Panel also allowed me to prototype in a notebook and see the output live
before moving the dashboard code into a source
.py file.
At work, we based a one-stop shop dashboard for a project on Panel, and in my personal life, I also built a minimal panel app that I also deployed to Heroku. Panel was definitely developed targeting notebook and source file use cases in mind, and this shows through in its source development model.
That said, panel apps could be slow to load, and without having a "spinner" solution in place (i.e. something to show the user that the app is "doing something" in the background), it sometimes made apps feel slow even though the slowness was not Panel's fault really. (My colleagues and I pulled out all the tricks in our bag to speed things up.)
Additionally, any errors that show up don't get surfaced to the app's UI, where developer eyeballs are on - instead, they get buried in the browser's JavaScript console or in the Python terminal where the app is being served. When deployed, this makes it difficult to see where errors show up and debug errors.
Now, Streamlit comes along, and some of its initial demos are pretty rad. In order to test-drive it, I put together this little tutorial on the Beta probability distribution for my colleagues.
Streamlit definitely solves some of the pain points that I've observed with Panel and Voila.
The most important one that I see is that errors are captured by Streamlit and bubbled up to the UI, where our eyeballs are going to be when developing the app. For me, this is a very sensible decision to make, for two reasons:
Firstly, it makes debugging interactions that much easier. Instead of needing to have two interfaces open, the error message shows up right where the interaction fails, in the same browser window as the UI elements.
Secondly, it makes it possible for us to use the error messages as a UI "hack" to inform users where their inputs (e.g. free text) might be invalid, thereby giving them informative error messages. (Try it out in the Beta distribution app: it'll give you an error message right below if you try to type something that cant be converted into a float!)
The other key thing that Streamlit provides as a UI nice-ity is the ability to signal to end-users that a computation is happening. Streamlit does this in three ways, two of which always come for free. Firstly, if something is "running", then in the top-right hand corner of the page, the "Running" spinner will animate. Secondly, anything that is re-rendering will automatically be greyed out. Finally, we can use a special context manager to provide a custom message on the front-end:
import streamlit as st with st.spinner("Message goes here..."): # stuff happens
So all-in-all, Streamlit seems to have a solution of some kind for the friction points that I have observed with Panel and Voila.
Besides that, Streamlit, I think, uses a procedural paradigm, rather than a callback paradigm, for app construction. We just have to think of the app as a linear sequence of actions that happen from top to bottom. State is never really an issue, because every code change and interaction re-runs the source file from top to bottom, from scratch. When building quick apps, this paradigm really simplifies things compared to a callback-based paradigm.
Finally, Streamlit also provides a convenient way to add text to the UI
by automatically parsing as Markdown any raw strings unassigned to a variable
in a
.py file and rendering them as HTML.
This opens the door to treating a
.py file as a
literate programming document,
hosted by a Python-based server in the backend.
It'd be useful especially in teaching scenarios.
(With
pyiodide bringing the PyData stack to the browser,
I can't wait to see standalone
.py files rendered to the DOM!)
Now, this isn't to say that Streamlit is problem-free. There are still rough edges, the most glaring (as of today) in the current release is the inability to upload a file and operate on it. This has been fixed in a recent pull request, so I'm expecting this should show up in a new release any time soon.
The other not-so-big-problem that I see with Streamlit at the moment is the procedural paradigm - by always re-running code from top-to-bottom afresh on every single change, apps that rely on long compute may need a bit more thought to construct, including the use of Streamlit's caching mechanism. Being procedural does make things easier for development though, and on balance, I would not discount Streamlit's simplicity here.
As I see it, Streamlit's devs are laser-focused on enabling devs to very quickly get to a somewhat good-looking app prototype. In my experience, the development time for the Beta distribution app took about 3 hours, 2.5 of which were spent on composing prose. So effectively, I only used half an hour doing code writing, with a live and auto-reloading preview greatly simplifying the development process. (I conservatively estimate that this is about 1.5 times as fast as I would be using Panel.)
Given Streamlit, I would use it to develop two classes of apps: (1) very tightly-focused utility apps that do one lightweight thing well, and (2) bespoke, single-document literate programming education material.
I would be quite hesitant to build more complex things; then again, for me, that statement would be true more generally anyways with whatever tool. In any case, I think bringing UNIX-like thinking to the web is probably a good idea: we make little utilities/functional tools that can pipe standard data formats from to another.
A design pattern I have desired is to be able to serve up a fleet of small, individual utilities served up from the same codebase, served up by individual server processes, but all packaged within the same container. The only way I can think of at the moment is to build a custom Flask-based gateway to redirect properly to each utility's process. That said, I think this is probably out of scope for the individual dashboarding projects.
The ecosystem is ever-evolving, and, rather than being left confused by the multitude of options available to us, I find myself actually being very encouraged at the development that has been happening. There's competing ideas with friendly competition between the developers, but they are also simultaneously listening to each other and their users and converging on similar things in the end.
That said, I think it would be premature to go "all-in" on a single solution at this moment. For the individual data scientist, I would advise to be able to build something using each of the dashboarding frameworks. My personal recommendations are to know how to use:
ipywidgetsin a Jupyter notebook
.pyfiles
.pyfiles.
These recommendations stem mainly from the ability to style and layout content without needing much knowledge of HTML. In terms of roughly when to use what, my prior experience has been that Voila and Streamlit are pretty good for quicker prototypes, while Panel has been good for more complex ones, though in all cases, we have to worry about speed impacting user experience.
From my experience at work, being able to quickly hash out key visual elements in a front-end prototype gives us the ability to better communicate with UI/UX designers and developers on what we're trying to accomplish. Knowing how to build front-ends ourselves lowers the communication and engineering barrier when taking a project to production. It's a worthwhile skill to have; be sure to have it in your toolbox!
I send out a monthly newsletter with tips and tools for data scientists. Come check it out at TinyLetter.
If you would like to receive deeper, in-depth content as an early subscriber, come support me on Patreon! | https://ericmjl.github.io/blog/2019/12/15/a-review-of-the-python-data-science-dashboarding-landscape-in-2019/ | CC-MAIN-2020-29 | refinedweb | 1,636 | 59.84 |
Using AWS Textract in an automatic fashion with AWS Lambda
During the last AWS re:Invent, back in 2018, a new OCR service to extract data from virtually any document has been announced. The service, called Textract, doesn’t require any previous machine learning experience, and it is quite easy to use, as long as we have just a couple of small documents. But what if we have millions of PDF of thousands of page each? Or what if we want to analyze documents loaded by users?
In that case, we need to invoke some asynchronous APIs, poll an endpoint to check when it has finished working, and then read the result, which is paginated, so we need multiple APIs call. Wouldn’t be super cool to just drop files in an S3 bucket, and after some minutes, having their content in another S3 bucket?
Let’s see how to use AWS Lambda, SNS, and SQS to automatize all the process!
Overview of the process
This is the process we are aiming to build:
- Drop files to an S3 bucket;
- A trigger will invoke an AWS Lambda function, which will inform AWS Textract of the presence of a new document to analyze;
- AWS Textract will do its magic, and push the status of the job to an SNS topic, that will post it over an SQS topic;
- The SQS topic will invoke another Lambda function, which will read the status of the job, and if the analysis was successful, it downloads the extracted text and save to another S3 bucket (but we could replace this with a write over DynamoDB or others database systems);
- The Lambda function will also publish the state over Cloudwatch, so we can trigger alarms when a read was unsuccessful.
Since a picture is worth a thousand words, let me show a graph of this process.
While I am writing this, Textract is available only in 4 regions: US East (Northern Virginia), US East (Ohio), US West (Oregon), and EU (Ireland).
I strongly suggest therefore to create all the resources in just one region, for the sake of simplicity. In this tutorial, I will use
eu-west-1.
S3 buckets
First of all, we need to create two buckets: one for our raw file, and one for the JSON file with the extracted test. We could also use the same bucket, theoretically, but with two buckets we can have better access control.
Since I love boring solutions, for this tutorial I will call the two buckets
textract_raw_files and
textract_json_files. If necessary, official documentation explains how to create S3 buckets.
Invoke Textract
The first part of the architecture is informing Textract of every new file we upload to S3. We can leverage the S3 integration with Lambda: each time a new file is uploaded, our Lambda function is triggered, and it will invoke Textract.
The body of the function is quite straightforward: = 'arn:aws:iam::123456789012:role/TextractRole' # This role is managed by AWS def handler(event, _): for record in event['Records']: bucket = record['s3']['bucket']['name'] key = unquote_plus(record['s3']['object']['key']) print(f'Document detection for {bucket}/{key}') textract_client.start_document_text_detection( DocumentLocation={'S3Object': {'Bucket': bucket, 'Name': key}}, NotificationChannel={'RoleArn': ROLE_ARN, 'SNSTopicArn': SNS_TOPIC_ARN})
You can find a copy of this code hosted over Gitlab.
As you can see, we receive a list of freshly uploaded files, and for each one of them, we ask Textract to do its magic. We also ask it to notify us, when it has finished its work, sending a message over SNS. We need therefore to create an SNS topic. It is well explained how to do so in the official documentation.
When we have finished, we should have something like this:
We copy the ARN of our freshly created topic and insert it in the script above in the variable
SNS_TOPIC_ARN.
Now we need to actually create our Lambda function: once again the official documentation is our friend if we have never worked with AWS Lambda before.
Since the only requirement of the script is
boto3, and it is included by default in Lambda, we don’t need to create a custom package.
At least, this is usually the case :-) Unfortunately, while I am writing this post,
boto3 on Lambda is at version
boto3-1.9.42, while support for Textract landed only in
boto3-1.9.138.
We can check which version is currently on Lambda from this page, under
Python Runtimes: if
boto3 has been updated to a version
>= 1.9.138, we don’t have to do anything more than simply create the Lambda function.
Otherwise, we have to include a newer version of
boto3 in our Lambda function.
But fear not! The official documentation explains how to create a deployment package.
We need also to link an IAM role to our Lambda function, which requires some additional permission:
- AmazonTextractFullAccess: this gives access also to SNS, other than Textract
- AmazonS3ReadOnlyAccess: if we want to be a bit more conservative, we can give access to just the
textract_raw_filesbucket.
Of course, other than that, the function requires the standard permissions to be executed and to write on Cloudwatch: AWS manages that for us.
We are almost there, we need only to create the trigger: we can do that from the Lambda designer! From the designer we select S3 as the trigger, we set our
textract_raw_files bucket, and we select
All object create events as Event type.
If we implemented everything correctly, we can now upload a PDF file to the
textract_raw_files, and over Cloudwatch we should be able to see the log of the Lambda function, which should say something similar to
Document detection for textract_raw_files/my_first_file.pdf.
Now we only need to read the extracted text, all the hard work has been done by AWS :-)
Read data from Textract
AWS Textract is so kind to notify us when it has finished extracting data from PDFs we provided: we create a Lambda function to intercept such notification, invoke AWS Textract and save the result in S3.
The Lambda function needs also to support pagination in the results, so the code is a bit longer:
import json import boto3 textract_client = boto3.client('textract') s3_bucket = boto3.resource('s3').Bucket('textract_json_files') def get_detected_text(job_id: str, keep_newlines: bool = False) -> str: """ Giving job_id, return plain text extracted from input document. :param job_id: Textract DetectDocumentText job Id :param keep_newlines: if True, output will have same lines structure as the input document :return: plain text as extracted by Textract """ max_results = 1000 pagination_token = None finished = False text = '' while not finished: if pagination_token is None: response = textract_client.get_document_text_detection(JobId=job_id, MaxResults=max_results) else: response = textract_client.get_document_text_detection(JobId=job_id, MaxResults=max_results, NextToken=pagination_token) sep = ' ' if not keep_newlines else '\n' text += sep.join([x['Text'] for x in response['Blocks'] if x['BlockType'] == 'LINE']) if 'NextToken' in response: pagination_token = response['NextToken'] else: finished = True return text def handler(event, _): for record in event['Records']: message = json.loads(record['Sns']['Message']) job_id = message['JobId'] status = message['Status'] filename = message['DocumentLocation']['S3ObjectName'] print(f'JobId {job_id} has finished with status {status} for file {filename}') if status != 'SUCCEEDED': return text = get_detected_text(job_id) to_json = {'Document': filename, 'ExtractedText': text, 'TextractJobId': job_id} json_content = json.dumps(to_json).encode('UTF-8') output_file_name = filename.split('/')[-1].rsplit('.', 1)[0] + '.json' s3_bucket.Object(f'{output_file_name}').put(Body=bytes(json_content)) return message
You can find a copy of this code hosted over Gitlab.
Again, this code has to be published as a Lambda function. As before, it shouldn’t need any special configuration, but since it requires
boto3 >= 1.9.138 we have to create a deployment package, as long as AWS doesn’t update their Lambda runtime.
After we have uploaded the Lambda function, from the control panel we set as trigger
SNS, specifying as
ARN the
ARN of the
SNS topic we created before - in our case,
arn:aws:sns:eu-west-1:123456789012:AmazonTextract.
We need also to give the IAM role which executes the Lambda function new permissions, in addition to the ones it already has. In particular, we need:
- AmazonTextractFullAccess
- AmazonS3FullAccess: in production, we should give access to just the
textract_json_filesbucket.
This should be the final result:
And that’s all! Now we can simply drop any document in a supported format to the
textract_raw_files bucket, and after some minutes we will find its content in the
textract_json_files bucket! And the quality of the extraction is quite good.
Known limitations
Other than being available in just 4 locations, at least for the moment, AWS Textract has other known hard limitations:
- The maximum document image (JPEG/PNG) size is 5 MB.
- The maximum PDF file size is 500 MB.
- The maximum number of pages in a PDF file is 3000.
- The maximum PDF media size for the height and width dimensions is 40 inches or 2880 points.
- The minimum height for text to be detected is 15 pixels. At 150 DPI, this would be equivalent to 8-pt font.
- Documents can be rotated a maximum of +/- 10% from the vertical axis. Text can be text aligned horizontally within the document.
- Amazon Textract doesn’t support the detection of handwriting.
It has also some soft limitations that make it unsuitable for mass ingestion:
- Transactions per second per account for all Start (asynchronous) operations: 0.25
- Maximum number of asynchronous jobs per account that can simultaneously exist: 2
So, if you need it for anything but testing, you should open a ticket to ask for higher limits, and maybe poking your point of contact in AWS to speed up the process.
That’s all for today, I hope you found this article useful! For any comment, feedback, critic, write to me on Twitter (@rpadovani93)
or drop an email at
riccardo@rpadovani.com.
Regards,
R. | https://rpadovani.com/aws-textract | CC-MAIN-2019-30 | refinedweb | 1,626 | 50.36 |
RODeco 1.0
RODeco a read only function decorator
Use Cases
---------
Let's say you're using a python module, and you don't like an inner working.
This module allows you to override any function inside a module, at run-time, as long it is not a builtin.
Afterwards, any call to this function, by anyone (you, or the module itself), will use what you defined.
Example
-------
import os
os.path.basename('./test') # Will output "test"
import RODeco
@RODeco.RODeco(os.path.basename, "_old_basename")
def newbasename(s):
return "~/" + _old_basename(s)
os.path.basename('./test') # Will output "~/test"
- Downloads (All Versions):
- 4 downloads in the last day
- 34 downloads in the last week
- 40 downloads in the last month
- Author: Lucas Philippe, Marc-Etienne Barrut
- Download URL:
- License: GPLv3
- Package Index Owner: Arzaroth
- DOAP record: RODeco-1.0.xml | https://pypi.python.org/pypi/RODeco/1.0 | CC-MAIN-2015-11 | refinedweb | 139 | 62.78 |
package podmain;
import org.bukkit.craftbukkit.v1_12_R1.CraftWorld;
import net.minecraft.server.v1_12_R1.EntityBoat;
public class CustomBoat...
Alright guys so the plugin is finished I will now be cleaning it up and running some final tests, it should be done by Friday.
Apparently I can't send .jar files, any other way I can get it to you? Maybe I can share it through Google drive?
Hey. I have the code, do you still need it?
Just saw this today, I like your idea and will be working on it ASAP. Would you also want the armor to be crafted?
Separate names with a comma. | https://dl.bukkit.org/search/99659115/ | CC-MAIN-2020-29 | refinedweb | 105 | 79.56 |
In this article, you’ll find all Python keywords with examples that will help you understand each keyword.
After reading this article, you’ll learn:
- How to get the list of all keywords
- Understand what each keyword is used for using the help() function
- the keyword module
Table of contents
- Get the List of Keywrods
- Understand Any keyword
- How to Identify Python Keywords
- Keyword Module
- Types of Keywords
- Value Keywords: True, False, None.
- Operator Keywords: and, or, not, in, is
- Conditional Keywords: if, elif, else
- Iterative and Transfer Keywords: for, while, break, continue, else
- Structure Keywords: def, class, with, as, pass, lambda
- Import Keywords: import, from, as
- Returning Keywords: return, yield
- Exception-Handling Keywords: try, except, raise, finally, else, assert
- Variable Handling Keywords: del, global, nonlocal
- Asynchronous Programming Keywords: async, await
What is keyword in Python?
Python keywords are reserved words that have a special meaning associated with them and can’t be used for anything but those specific purposes. Each keyword is designed to achieve specific functionality.
Python keywords are case-sensitive.
- All keywords contain only letters (no special symbols)
- Except for three keywords (
True,
False,
None), all keywords have lower case letters
Get the List of Keywrods
As of Python 3.9.6, there are 36 keywords available. This number can vary slightly over time.
We can use the following two ways to get the list of keywords in Python
- keyword module: The keyword is the buil-in module to get the list of keywords. Also, this module allows a Python program to determine if a string is a keyword.
help()function: Apart from a keyword module, we can use the
help()function to get the list of keywords
Example: keyword module
import keyword print(keyword.kwlist)
Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
All the keywords except,
True,
False, and
None, must be written in a lowercase alphabet symbol.
Example 2: The
help() function
help("keywords")
Output:
Here is a list of the Python keywords. Enter any keyword to get more help. False break for not None class from or True continue global pass __peg_parser__ def if raise and del import return as elif in try assert else is while async except lambda with await finally nonlocal yield
Note:
You cannot use any of the above keywords as identifiers in your programs. If you try to do so, you will get an error. An identifier is a name given to an entity, For example, variables name, functions name, or class name.
Understand Any keyword
The python
help() function is used to display the documentation of modules, functions, classes, keywords.
Pass the keyword name to the
help() function to get to know how to use it. The
help() function returns the description of a keyword along with an example.
Let’s understand how to use the
if keyword.
Example:
print(help('if'))
Output:
The "if" statement ****************** The "if" statement is used for conditional execution: if_stmt ::= "if" assignment_expression ":" suite ("elif" assignment.
How to Identify Python Keywords
Keywords are mostly highlighted in IDE when you write a code. This will help you identify Python keywords while you’re writing a code so you don’t use them incorrectly.
An integrated development environment (IDE) is software or a code editor for building applications that combine standard developer tools into a single graphical user interface (GUI). An IDE typically consists of a source editor, syntax highlighting, debugger, and build tools.
Python provides an IDLE that comes with Python installation. In IDLE, keywords are highlighted in a specific color. You can also use third-party editors such as Python IntelliJ IDEA or eclipse ide.
Image
Another way is if you are getting a syntax error for any identifier declaration, then you may be using a keyword as an identifier in your program.
Keyword Module
Python keyword module allows a Python program to determine if a string is a keyword.
iskeyword(s): Returns
True if
s is a keyword
Example:
import keyword print(keyword.iskeyword('if')) print(keyword.iskeyword('range'))
Output:
As you can see in the output, it returned True because ‘if’ is the keyword, and it returned False because the range is not a keyword (it is a built-in function).
Also, keyword module provides following functions to identify keywords.
keyword.kwlist:It return a sequence containing all the keywords defined for the interpreter.
keyword.issoftkeyword(s): Return
Trueif s is a Python soft keyword. New in version 3.9
keyword.softkwlist: Sequence containing all the soft keywords defined for the interpreter. New in version 3.9
Types of Keywords
All 36 keywords can be divided into the following seven categories.
Value Keywords:
True,
False,
None.
True and
False are used to represent truth values, know as boolean values. It is used with a conditional statement to determine which block of code to execute. When executed, the condition evaluates to
True or
False.
Example:
x = 25 y = 20 z = x > y print(z) # True
Operator Keywords:
and,
or,
not,
in,
is
- The logical
andkeyword returns
Trueif both expressions are True. Otherwise, it will return.
False.
- The logical
orkeyword returns a boolean
Trueif one expression is true, and it returns
Falseif both values are
false.
- The logical
notkeyword returns boolean
Trueif the expression is
false.
See Logical operators in Python
Example:
x = 10 y = 20 # and to combine to conditions # both need to be true to execute if block if x > 5 and y < 25: print(x + 5) # or condition # at least 1 need to be true to execute if block if x > 5 or y < 100: print(x + 5) # not condition # condition must be false if not x: print(x + 5)
Output:
15 15
The
is keyword returns return
True if the memory address first value is equal to the second value. Read Identity operators in Python.
Example:
is keyword
# is keyword demo x = 10 y = 11 z = 10 print(x is y) # it compare memory address of x and y print(x is z) # it compare memory address of x and z
Output:
False
True
The
in keyword returns
True if it finds a given object in the sequence (such as list, string). Read membership operators in Python
Example:
in Keyword
my_list = [11, 15, 21, 29, 50, 70] number = 15 if number in my_list: print("number is present") else: print("number is not present")
Output:
number is present
Conditional Keywords:
if,
elif,
else
In Python, condition keywords act depending on whether a given condition is true or false. You can execute different blocks of codes depending on the outcome of a condition.
See: Control flow in Python
Example:
x = 75 if x > 100: print('x is greater than 100') elif x > 50: print('x is greater than 50 but less than 100') else: print('x is less than 50')
Output:
x is greater than 50 but less than 100
Iterative and Transfer Keywords:
for,
while,
break,
continue,
else
Iterative keywords allow us to execute a block of code repeatedly. We also call it a loop statements.
while: The while loop repeatedly executes a code block while a particular condition is true.
for: Using for loop, we can iterate any sequence or iterable variable. The sequence can be string, list, dictionary, set, or tuple.
Example:
print('for loop to display first 5 numbers') for i in range(5): print(i, end=' ') print('while loop to display first 5 numbers') n = 0 while n < 5: print(n, end=' ') n = n + 1
Output:
for loop to display first 5 numbers 0 1 2 3 4 while loop to display first 5 numbers 0 1 2 3 4
break,
continue, and
pass: In Python, transfer statements are used to alter the program’s way of execution in a certain manner. Read break and continue in Python.
Structure Keywords:
def,
class,
with,
as,
pass,
lambda
The
def keyword is used to define user-defined funtion or methods of a class
Example:
def keyword
# def keyword: create function def addition(num1, num2): print('Sum is', num1 + num2) # call function addition(10, 20)
Output:
Sum is 30
Jessa 19
The pass keyword is used to define as a placeholder when a statement is required syntactically.
Example:
pass keyword
# pass keyword: create syntactically empty function # code to add in future def sub(num1, num2): pass
class keyword is sued to define class in Python. Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects“. An object-oriented paradigm is to design the program using classes and objects
Example:
class keyword
# create class class Student: def __init__(self, name, age): self.name = name self.age = age def show(self): print(self.name, self.age) # create object s = Student('Jessa', 19) # call method s.show()
Output:
Jessa 19
with keyword is used when working with unmanaged resources (like file streams). It allows you to ensure that a resource is “cleaned up” when the code that uses it finishes running, even if exceptions are thrown.
Example: Open a file in Python uisng the
with statement
# Opening file with open('sample.txt', 'r', encoding='utf-8') as fp: # read sample.txt print(fp.read())
Import Keywords:
import,
from,
as
In Python, the
import statement is used to import the whole module.
Example: Import Python datetime module
import datetime # get current datetime now = datetime.datetime.now() print(now)
Also, we can import specific classes and functions from a module.
Example:
# import only datetime class from datetime import datetime # get current datetime now = datetime.now() print(now)
Returning Keywords:
return,
yield
- In Python, to return value from the function, a
returnstatement is used.
yieldis a keyword that is used like
return, except the function will return a generator. See yield keyword
Example:
def addition(num1, num2): return num1 + num2 # return sum of two number # call function print('Sum:', addition(10, 20))
Output:
Sum: 30
Exception-Handling Keywords:
try,
except,
raise,
finally,
else,
assert
An exception is an event that occurs during the execution of programs that disrupt the normal flow of execution (e.g., KeyError Raised when a key is not found in a dictionary.) An exception is a Python object that represents an error.
Read Exception handling in Python
Variable Handling Keywords:
del,
global,
nonlocal
- The
delkeyword is used to delete the object.
- The
globalkeyword is used to declare the global variable. A global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file.
- Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.
Example:
price = 900 # Global variable def test1(): # defining 1st function print("price in 1st function :", price) # 900 def test2(): # defining 2nd function print("price in 2nd function :", price) # 900 # call functions test1() test2() # delete variable del price
Asynchronous Programming Keywords:
async,
await
The
async keyword is used with
def to define an asynchronous function, or coroutine.
async def <function>(<params>): <statements>
Also, you can make a function asynchronous by adding the
async keyword before the function’s regular definition.
Python’s
await keyword is used in asynchronous functions to specify a point in the function where control is given back to the event loop for other functions to run. You can use it by placing the
await keyword in front of a call to any
async function:
await <some async function call> # OR <var> = await <some async function call>
See: Coroutines and Tasks | https://pynative.com/python-keywords/ | CC-MAIN-2021-39 | refinedweb | 1,936 | 59.33 |
BOXING AND UNBOXING IN C#
VALUE TYPES AND REFERENCE TYPES
- Value types are the primitive data types in C# which consist of the data at its own location in memory whereas reference types are the non-primitive data types in C# which consist of a pointer to another memory location holding the data.
- For value types, memory is allocated on the stack data structure. On the other hand, for reference types memory is allocated on the heap data structure.
- All the predefined data types under the libraries of our language which comes under the value type category like int (Int32), float, bool (Boolean) are implemented as structures whereas all the predefined data types under the reference type category like string and object are implemented as classes.
NOTE:- It should be noted that all the primitive data types are value type except string and object which are reference types.
BOXING AND UNBOXING
The terms ‘boxing’ and ‘unboxing’ can be very easily understood if we correlate it with real times. For instance, boxing stuff in real-time would result in larger stuff because of the addition of packaging. Analogous to this, boxing in C# results in the transformation of a smaller data type (i.e. a subtype) to a larger data type (i.e. a supertype). Similarly, unboxing stuff results in smaller stuff because of the deduction of packaging. Likewise, unboxing in C# refers to the conversion of a larger data type(i.e. a supertype) into a smaller data type (i.e. a subtype).
In other words, we can say that boxing is a process that leads to the conversion from value type to reference type, and unboxing is a process that leads to the conversion from a reference type to a value type.
An important point to remember is that boxing can be implicit but unboxing is always necessarily explicit.
CODE FOR BOXING
Let us implement the following code to get a much better idea about boxing.
using System; class Demo { static void Main() { int i = 12; object obj = i ; i = 5; Console.Writeline(i); Console.Writeline(obj); Console.Readline(); } }
EXPLANATION :
In the above code, we have an integer variable i which is of value type and is implicitly converted to the object variable obj which is of reference type. Here a smaller data type i.e. a subtype is converted to a larger data type i.e. a supertype hence, the above code is an example of boxing.
CODE FOR UNBOXING
using System; class Demo1 { static void Main() { object obj = 10; int i = Convert.ToInt32(obj); Console.Writeline(i); Console.Readline(); } }
EXPLANATION :
In the above code, we have an object variable obj which is of reference type, and since it cannot be implicitly converted to the integer value so it is done explicitly using Convert.ToInt32() . Here a larger data type i.e. a super type is converted to a smaller data type i.e. a sub type hence, the above code is an example of unboxing.
CONCLUSION :
In this article, we learned about boxing and unboxing understanding the value types and reference types in C#. | https://tutorialslink.com/Articles/BOXING-AND-UNBOXING-IN-Csharp/1412 | CC-MAIN-2021-39 | refinedweb | 517 | 52.19 |
.
Well, that was no good. I poked a bit at extending the default timeout period, but really that was only a partial solution. Who knows how long it might take to encode the image on a slow computer? So I started poking at what it would take to make the jpeg encoding asynchronous. Sadly, actionscript and flex do not have the concept of just saying "hey go do this and get back to me when your done." This is probably because actionscript is single threaded - everything just runs on the browser's main thread.
Above we have a small sample app showing off the asynchronous jpeg encoder that we are going to build in this tutorial. You see the spinning lag meter? Right now, it is probably spinning nice and smooth. This is because flex has plenty of cpu cycles to update the spinning circle. When there isn't enough cpu time available, that animation will start to look choppy, as Flex will only be able to update it once every few hundred milliseconds, possibly longer. If there are no spare cycles, the circle will freeze and stop spinning altogether. If you hit "Normal Encode", that is probably exactly what will happen, and your entire browser will freeze along with it. That is because by clicking "normal encode", you told flex to encode the image displayed in the sample app (which is a 2800x2100 pixels) as a jpeg. If your computer is slow like mine, you will eventually get the "script timeout" error, and the encoding will never finish.
On the right hand side, however, is the button to trigger the asynchronous jpeg encoding. When you click that, the app won't freeze and the circle will keep spinning (although not quite as smoothly). You will also get a progress bar that shows the progress of the encoding. By moving the "pixels per iteration" slider bar to the right, you will increase the speed of the encoding, but decrease the responsiveness of the interface, and if you move the slider to the left, you get the opposite effect. A little farther down I will explain how that is accomplished.
So how do you even go about making something like this asynchronous? As
I said above, we only have one thread to work with, so it is all
hopeless, right? Not quite - there are ways to act like a multi-threaded
system, such as using something like
setTimeout. You can use
setTimeout to emulate threading - essentially do a little work, but
then you queue more work for the future (not immediately). The app then
has a chance to breathe and deal with things like UI input during the
pauses between work items.
It was here that I ran up against another issue. How was I going to break the act of encoding a large jpeg into manageable little pieces? Well, there is no way to do that from outside the jpeg encoding object, so I went into the Flex source code and found the jpeg encoder. And this is where the real meat of this article starts.
Below we have the problem loop in the original jpeg encoder:
for (var ypos:int = 0; ypos < height; ypos += 8) { for (var xpos:int = 0; xpos < width; xpos += 8) { RGB2YUV(sourceBitmapData, sourceByteArray, xpos, ypos, width, height);); } }
This loop can take a long time on large images - or at least on my computer it does. So the essential idea here is that we don't want to do this whole loop at once. We want to process the image a chunk at a time, giving the rest of the app time to work between chunks. So how do we do this? Well, we write a function that can process the loop a chunk at a; } } setTimeout(AsyncLoop, 10, xpos, ypos); }
This
AsyncLoop function takes a
xpos and
ypos into the image, and
starts processing from that point. But it only loops
PixelsPerIter
times. After it has processed that many chunks, it leaves the loop, and
calls
setTimeout on
AsyncLoop. In this setTimeout call, it hands the
current x and y position in the image - so when the function is called
again, it starts up in the right place.
By setting a 10 millisecond timeout, the application will have time to
do other things before it gets back to processing this image data. The
PixelsPerIter value is very important - it determines how responsive
the application is during the image processing. If
PixelsPerIter is 1,
the application will seem perfectly responsive. But it will also take a
long time for a large image to encode, because the encoding is pausing
for 10 milliseconds between event chunk. If you set the value to, say,
10000, the app will become unresponsive, because it is taking multiple
seconds to process data before it responds to any UI input. Playing
around, I've found that 128 is a pretty good value - the app slows down
a little bit, and it takes under 2 minutes to encode a 2880x2880 jpeg.
So what do we do here when we are done processing the pixels? Well we do
a
setTimeout to
FinishEncode, and return out of
AsyncLoop.
FinishEncode holds all the code that was later than the main loop in
the original encode); }
Ok, well, that makes sense, but how to we signal the rest of the application that the encoding has completed? Its not like we can just wait for a function call to return. Because the encoding is asynchronous, the original encode call will return immediately - long before the actual encoding is finished. So instead, we use an event. In this case, I created my own event, because I wanted the event object to hold the encoded image:
public class JPEGAsyncCompleteEvent extends Event { public static const JPEGASYNC_COMPLETE:String = "JPEGAsyncComplete"; public var ImageData:ByteArray; public function JPEGAsyncCompleteEvent(data:ByteArray) { ImageData = data; super(JPEGASYNC_COMPLETE); } }
To use this event on the new jpeg encoding class, we add an attribute at
the top of the class, and make the class extend
EventDispatcher:
[Event(name=JPEGAsyncCompleteEvent.JPEGASYNC_COMPLETE, type="JPEGAsyncCompleteEvent")] public class JPEGAsyncEncoder extends EventDispatcher { ...
And now to fire the event, we add a
dispatchEvent call to the
FinishEncode JPEGAsyncCompleteEvent(byteout)); }
I also wanted to add a progress event, so that I could show a progress bar to the user as the jpeg was encoding. To do this, I added another event to the class:
{ ...
And with this progress event, I added a bunch of logic to the
AsyncLoop code to fire the progress event at appropriate points:
private function AsyncLoop(xpos:int, ypos:int):void { for(var i:int=0; i < Chunks); }
That piece of code actually uses a bunch of fields that I added to the class to keep track of total progress, so that the progress event gets fired only about once a percent or so.
Those are pretty much all the changes that I needed to make (barring the couple added fields). Below you can see the entirety of what I did to the code. I put "...." where code from the original jpeg encoder class would be - there is a lot of it, so I didn't want to paste it all here:
{ ...... private var DCY:Number = 0; private var DCU:Number = 0; private var DCV:Number = 0; private var SrcWidth:int = 0; private var SrcHeight:int = 0; private var Source:Object = null; private var TotalSize:int = 0; private var PixelsPerIter:int = 128; private var PercentageInc:int = 0; private var NextProgressAt:int = 0; private var CurrentTotalPos:int = 0; private var Working:Boolean = false; ..... public function set PixelsPerIteration(val:int):void { PixelsPerIter = val; } public function get ImageData():ByteArray { return byteout; } public function encodeByteArray(raw:ByteArray, width:int, height:int):Boolean { return internalEncode(raw, width, height); } public function encode(image:BitmapData):Boolean { return internalEncode(image, image.width, image.height); } private function internalEncode(newSource:Object, width:int, height:int):Boolean { if(Working) return false; Working = true; Source = newSource; SrcWidth = width; SrcHeight = height; TotalSize = width*height; PercentageInc = TotalSize/100; NextProgressAt = PercentageInc; CurrentTotalPos = 0; setTimeout(StartEncode, 10); return true; } private function StartEncode():void { // Initialize bit writer byteout = new ByteArray(); bytenew = 0; bytepos = 7; // Add JPEG headers writeWord(0xFFD8); // SOI writeAPP0(); writeDQT(); writeSOF0(SrcWidth, SrcHeight); writeDHT(); writeSOS(); DCY = 0; DCV = 0; DCU = 0; bytenew = 0; bytepos = 7; this.dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, 0, TotalSize)); setTimeout(AsyncLoop, 10, 0, ProgressEvent(ProgressEvent.PROGRESS, false, false, TotalSize, TotalSize)); this.dispatchEvent(new JPEGAsyncCompleteEvent(byteout)); Working = false; } ....... }
The methods
internalEncode,
encode, and
encodeByteArray replace
methods in the original jpeg encoder class. Everything else shown above
is an addition. I added all of those fields show at the top because
unlike the original encoder (where almost everything was done in a
single function call), I needed to remember things across function
calls.
One thing to note, this encoder does not implement
IImageEncoder like
the original jpeg encoder does. This is because that interface expects
the
encode and
encodeByteArray to return a byte array containing the
encoded image. Obviously, since this class does all the encoding
asynchronously, it can't return the byte array straight out of the
original call, because the encoding hasn't actually been done yet.
Instead, the functions return a boolean. If the call to encode returns
false, it is because this instance of the class is already encoding an
image - so it can't start encoding another one yet.
So we have this awesome asynchronous jpeg encoder class. How do we use it? Well, lets take a look at some sample code:
private function startEncode(imageBitmapData:BitmapData):void { var encoder:JPEGAsyncEncoder = new JPEGAsyncEncoder(80); encoder.PixelsPerIteration = 128; encoder.addEventListener(JPEGAsyncCompleteEvent.JPEGASYNC_COMPLETE, encodeDone); encoder.addEventListener(ProgressEvent.PROGRESS, encodeProg); encoder.encode(imageBitmapData); } private function encodeProg(event:ProgressEvent):void { var percentage:String = ((event.bytesLoaded / event.bytesTotal)*100) + "%"; //Display the percentage somewhere } private function encodeDone(event:JPEGAsyncCompleteEvent):void { var data:ByteArray = event.ImageData; //Do something with the encoded image }
And there you go. Thats all you need to use this asynchronous jpeg encoder class. You can grab the source code for the whole example above here, and feel free to use it for whatever you want.
Source Files:
Dude... your a life saver!!!!!!!!!!!!!! This should be a default library included in flex
Thnx a lot for this tutorial :)
hi... we are testing the flex application using qtp repeatedly i am getting the error 1502.... i didnt use any loops. and passing single set of user name and password.... kindly help me to get out of this issue
Hey Great tutorial!! But I am not getting the same quality as I get from Synchronous JPEG encoder. My Application is taking snapshot of movie clip and pasting into pdf using alive pdf When I use ImageSnapshot.captureImage(source,250,new JPEGEncoder(),true) it gives me better quality campare to imageSnap:BitmapData = ImageSnapshot.captureBitmapData(source) and pass this bitmap data in asnycronous JPEG encoder
I guess due to conversion of movie clip into bitmap, quality of image degrades. AnyBody knows how can i get the same quality as i got frm Synchronous JPEG encoder
Superb tutorial, very clever! Thank you & well done :D
Great tutorial, thanks! How to abort the enocding progress after it started? Can you help me with that?
Sarah
This is simply amazing, many thanks for such a great tool.
hi,
i am suing this code to generate multiple screen shots so i have to manage all completed encodings is there any way to manage at once....
thanks
Wow...What a tutorial..great. Thanks for sharing the knowledge.
Hi, is the "missing" cleartimeout was an issue after all ?
Thanks for this solution, however if you want to save the encoded jpg with FileReference.save it won't work, as FP10 throws a security exception if you call fr.save from anywhere except a onClick function. So I can't save my jpg after encoding it using your asynchronous encoder, since I cannot call the fr.save until the encoder is complete and there is no way to know it's complete except by the complete event it throws. Any idea how to get around this?
I would just listen to the complete event and then enable a download button. You can show a progress bar so the user knows that something is happening. You could even be a little bit more intrusive by popping up a window saying it's encoding is complete and they can download it now.
Yes, it looks like having two buttons for the user to click is the way to go. A "prepare download" button to start the encoding, and then a save button can appear when it's ready to be saved.
Had problems posting a long "ThankYou" post (hashcash issue O_o), so here's the short one: You Guys are Awsome!
Asynchronicity is nice, but the encoding time still seems very slow versus something like 'Shrink-O-Matic' or 'ImageSizer'. Anyone know what those apps are doing differently?
I am not really sure what is different. They certainly could be using their own encoding. Also, have you tried running this code in AIR? I don't know if that makes a performance difference or not.
awesome!! thanks! :)
hi all, i want to capture a application screenshot and i tried to encode with the asynchronous encoder . i had taken the screenshot with Timer control (400 ms ) . still it has some hangover(maybe memory leakage ). kindly help me out
hi boss why you posted with your company information.. they are going to kick off you...
Could you explain why you are doing this , thanks.
Yeah we originally wrote this code because we found encoding a large image (10000 x 7500) was taking well forever and would actually lock up the browser. This allows the browser and the rest of the flex application to update itself and allow for user interaction to happen while encoding. Not to mention we can show a progress bar during the encoding.
i just want to set the record straight on my earlier comment.
after reading all over about the memory leaks in flashplayer, and my relative inexperience, I freaked out and was convinced something was wrong in the the jpeg encoding itself, that little bits of memory were being used each time encoding.
In fact, the problem wasn't with the async encoder...it was actually a problem with some of the code I had lifted for grabbing a list of files from the users filesystem into flash.
It seems the fileReferenceList object was storing not only the information to reference the file (like the file name and location) but it was also storing the *entire contents of the file* as it was uploaded into flash. This property is read only so there was way to delete it.
The odd thing is that I wasn't able to see this happening in profiler...it wasn't registering as a big user of memory, and I think this is because the data is somehow cached by the browser.
Regardless, I just wanted to write that the jpeg async encoder was NOT the source of my woes. My app can now upload and resize 1000's of 21 megapixel images without a hitch.
Thanks again for this tip!
(Now if anyone knows how to perserve the exif data...)
Hi, how did you fix your issue with the filereference ?
thanks
SOLVED. I was not doing the bd.dispose() method. Thanks,
Mark
Hi,
and thanks for this class. It works great but, when batching/resizing a lot of images (with a resize external class), I experience memory leaks that in the end cause the application to crash. I tried all the (very few) garbage collection techniques I know, but as of know memory can easily bypass my 2Gb of RAM simply resizing 10 digital camera photos to 320x240,640x480 and encoding them.
Any ideas?
Thanks in advance,
Mark
Using this very usefull class since Flash 9 I run into one major problem now, using Flash 10: Security policy of Flash 10 requires real user action (click or key press) to upload the async encoded jpg.
Calling upload function inside of "function encodeDone()" doesn't really upload the encoded *.jpg anymore now, because calling that from complete handler isn't the required first call of upload function...
... and because it isn't really a result of an user action.
May be I misunderstand some here... Are there any notes, or expiriences about that available? Some helpfull hints to this problem?
Anyway, many thanks for JPEGAsyncEncoder...
-- Regards from Germany Endur Unixman
Have fixed that by my self using application/octet-stream instead of multipart/form-data. Had to change our server sided perl too to match this.
-- Thanks Endur
I'm also having the memory problems Dennis noted when running a batch of images. The bitstrings seem to pile up in the memory profiler, and loiter around.
The virtual memory only my system keeps increasing while this is running until eventually the app crashes.
As for Seme1's comment about the image quality problems...I also had the same problem when I downsized the bitmaps before encoding. The image smoothing noted by "2am" didn't work to fix this. I also tried using a special biLinear and BiCubic sampling class, which also didn't work.
The fix for this was to apply a blur filter BEFORE the bitmap is resized. The amount of blur must be adjusted according to the initial image size.
Any help with the loitering bitstrings would be a big help.
Thanks all and thanks again for this extremely useful class.
Good stuff :)
Brilliant work man...
Downloading the code...
Great work! Thank you veeeeeeeery much.
Just wanted to say thanks for a really brilliant solution to a very annoying problem. The code works like a charm (no modification required on my part). I wanted an easy way for my wife to upload images to our family site via an Adobe AIR application that auto resizes the images on drop, but was having trouble with the image loading using the JPEGEncoder (as it was freezing up the app until it was completed). Your class fixed the problem and even allowed me to add progress bars to each image load. Love it! Thanks again.
Thanks for the nice and detailed tutorial. Hats off..! :-)
Has anyone found a fix for the memory leak in this Class? I love this Encoder and am using it in a project but after encoding multiple images the memory keeps building up… I currently running it in debug and trying to figure it out where the leak is. If I find anything I will post it here.
I used the term Memory Leak in my last post. What I really mean is the loiterring objects in memory. The fact that after you are done encoding a JPEG the memory usage doesn’t go back down.
Do you know if the memory issue is just for this async version of the jpeg encoder, or is it also a problem with the regular Flex one?
Maybe the memory issues are related to the setTimeout() call. Usually a corresponding clearTimeout() should be called. From the docs:
"If you intend to use the clearTimeout() method to cancel the setTimeout() call, be sure to assign the setTimeout() call to a variable (which the clearTimeout() function will later reference). If you do not call the clearTimeout() function to cancel the setTimeout() call, the object containing the set timeout closure function will not be garbage collected."
Hmm, that's interesting. From what I understood, you only needed to call clearTimeout if you wanted to cancel the pending call. I'll have to run some tests at some point and find out.
I am trying to use this to process a bunch of images, and I’m noticing that a bunch of BitString objects are hanging around and don’t seem to be garbage collected.
If I do a single image (3888×2592 which has been resized to 150×100), there are 65882 instances left in memory that don’t seem to get garbage collected.
If I do multiple images, then there are bigger issues, as each image causes about the same number of instances left in memory.
Hey,
Any idea if jpeb compression works with better speed in FP10?
What would it take to get you to write a tutorial showing how to integrate this with AlivePDF? I’ve tried unsuccessfully all day long and need some expert help. Pleeeeeeeease? :D
Nice, thank you.
But what on earth is “a bunch of logic” ?!?
I have noticed that the quality of the images produced by the JPEGAsynencoder does not match that of other encoders available (i.e. php's built in image compression functions from the gd library)
Any explanation ? or hints/workarounds for improving the quality of compressed images by JPEGAsyncEncoder ??
Please have a look at the following samples:
original image: Size: 110KB
Image encoded with JPEGAsync: Size:46.7KB
Image encoded with Php's built-in functions (gd library): Size:33.4KB Much smoother than the JPEGAsync version.. and smaller too
In the images I posted in my previous comment,, Please pay attention to the white board in the picture. In one image ,, the word "hotmail" can be easily read,, while this is not the case in the other.
I tried increasing the quality measure to 80 and 100 (as an argument passed to JPEGAsyncEncoder) and it only resulted in increasing the file size.. The picture did not get any smoother..
Hmm, yeah, that is a big quality difference.
In any case, I don't actually know how the code behind the JPEG encoder works - when I wrote this asyc encoder, I just took the bulk of the code from Flex. You might want to try encoding that image with the regular Flex JPEG encoder, and see if it has the same issues - I bet it does.
May I ask how you are creating the encoded image and saving it using the JPEGAsyncEncoder? I am quite curious because I haven't noticed any quality issues especially like the ones you have.
Thanks again for the fast response..
Below is the whole code I have :
Basically, fileList is an array storing several files (all images). They are collected by a drag and drop function.
Then,, I have:
Inside saveTheFile,, I have:
This is the last bit that writes the images after being encoded
ok, I missed these two lines,,
they are right above the line: var bd = new air.BitmapData(600,tmploader[i].content.height);
It looks to me that you are resizing the image before you encode it (the lines where you set the height and width). I'm not sure what algorithm is being used underneath the covers to do the resize, but I bet it is that algorithm that is causing the artifacts you see in the encoded image.
‘Imagesmoothing’ is disabled by default… You can enable it by using the parameters when calling the ‘draw’ function.
Example:
Thanks for the AsyncJPEGEncoder! Works like a charm. Using it to encode multiple images in a loop as well.
good article, good idea to overcome single threaded structure of flash. for these kind of problems, there is a function named callLater, which calls the function after the screen is drawn. So instead of using a timer, you could use callLater which would be more consistent&efficient.
Hello, thanks for this incredible class, i've been using in a personal project and i have a problem to free the memory that i use. I use it to encode 6 images and in the process i put the byteArray in 6 global variables, so then i pass them to MySQL to store them. But i've notice with the profiling that the memory doesn't free after the process. If you have any clue, please let me know, thanks very much in advance for your time. Sory about my english, is not my native language. Agustin
I too have memory issues with the code when being executed on multiple images How can I free the memory ?
So you are running it multiple times in a row?
This code resides in a function that is being called in a for loop multiple times (once for each image:)
tmploader is simply a loader (air.loader()). I am using Javascript/HTML by the way for my lack of knowledge in FLEX, and its lack of support for my language.
Thanks in advance for your help.
Hi, Thank you for this! I was about to write something very similar when I ran across yours. I'm using it in the latest version of the CleVR Stitcher and would like to mention you in the credits. How would you like to be credited? Incidentally, the Stitcher uses the same method for fake threading, and it's an absolute nightmare to keep track of. We have literally dozens of different loops that are broken up like this! Oh how I wish there were an easier way. Regards,
Matt
Hi there:
I'm working on a project in Flash MX 2004 for a client and I'm having a problem that is similar to the one that you described in your tutorial. Unfortunately setTimeout is not supported in MX04 and setInterval requires quite a bit of tricky garbage collection. Do you have any recommendations for what I might be able to do in MX04 to faux-multithread? The application I'm working on is targeted for FlashPlayer 7.
This article is great! This helped me solve a huge problem. I had to iterate through several thousand items in a datagrid and the operation was timing out. Not anymore! Thank you very much for posting this!
Thanks, Blake Eaton
Just want to say that this is an awesome tutorial!
Indeed a gr8 way to work on images, but what about charts. asyncEncoder.encode(Bitmap(img.content).bitmapData); for charts we cant get .content, There we get a bitmap as
But this is not giving advantages of async encoding, Screen still hangs and timeout is reached. let me know if u have any solution/workaround | http://tech.pro/tutorial/722/flex-tutorial-an-asynchronous-jpeg-encoder | CC-MAIN-2014-15 | refinedweb | 4,354 | 63.39 |
The dbus problems are due to missing scm credentials sendmsg scm creds and socket credentials pflocal socket credentials for local sockets. There was also a problem with short timeout in select, but that has been solved in Debian by setting a minimum timeout of 1ms.
- IRC, freenode, #hurd, 2011-11-26
- IRC, freenode, #hurd, 2011-12-16
- IRC, freenode, #hurd, 2011-12-20
- IRC, freenode, #hurd, 2013-07-17
- IRC, freenode, #hurd, 2013-09-02
- IRC, freenode, #hurd, 2013-09-04
- IRC, freenode, #hurd, 2013-09-11
- IRC, freenode, #hurd, 2013-09-12
- IRC, freenode, #hurd, 2013-10-16
- IRC, freenode, #hurd, 2013-10-22
- IRC, freenode, #hurd, 2013-11-03
- IRC, freenode, #hurd, 2013-11-13
- IRC, freenode, #hurd, 2013-11-15
- IRC, freenode, #hurd, 2014-01-17
- IRC, freenode, #hurd, 2014-01-30
IRC, freenode, #hurd, 2011-11-26
<antrik> BTW, how much effort is necessary to fix dbus? <pinotree> basically, have pflocal know who's the sender (pid/uid/gid/groups) in the socket send op
IRC, freenode, #hurd, 2011-12-16
<braunr> pinotree: what's the problem with dbus ? <pinotree> braunr: select() returning 0 changed fd's with very short (eg < 1ms) timeouts when there are actually events;
<pinotree> and missing socket credentials
<braunr> oh <braunr> which socket creds interface ? <pinotree> bsd, i.e. with SCM_CREDENTIALS payload for cmsg on {recv,send}msg() <braunr> ok <braunr> SCM_RIGHTS too ? <braunr> the select issue seems weird though <pinotree> hm no, that's for passing fd's to other processes <braunr> is it specific to pflocal or does dbus use pfinet too ? <pinotree> iirc on very short timeouts the application has no time waiting for the reply of servers <braunr> i see <pinotree> braunr: <braunr> thanks <pinotree> (the interesting messages are from #53 and on) <braunr> 2000 eh ... :) <braunr> hm i agree with neal, i don't understand why the timeout is given to the kernel as part of the mach_msg call
IRC, freenode, #hurd, 2011-12-20
<braunr> hm, i don't see any occurrence of SCM_CREDENTIALS in dbus <braunr> only SCM_RIGHTS <pinotree> braunr: yes, that one <braunr> oh <braunr> i thought you said the opposite last time <pinotree> dbus/dbus-sysdeps-unix.c, write_credentials_byte and _dbus_read_credentials_socket (with #define HAVE_CMSGCRED) <braunr> hm <braunr> which version ? <braunr> i don't see anything in 1.4.16 <pinotree> 1.4.16 <braunr> grmbl <braunr> ah, i see <braunr> SCM_CREDS <pinotree> if you want, i have a simplier .c source with it <braunr> no i'm just gathering info <pinotree> ok <braunr> what's the deal with SCM_CREDS and SCM_CREDENTIALS ? <braunr> bsd vs sysv ? <braunr> oh, <braunr> so we actually do want both SCM_CREDS and SCM_RIGHTS for debus <braunr> dbus <pinotree> SCM_RIGHTS is a different matter, it is for passing fd's <braunr> yes <braunr> but it's used by dbus <braunr> so if we can get it, it should help too <pinotree> there's a preliminary patch for it done by emilio time ago, and iirc it's applied to debian's glibc <braunr> ah, he changed the libc <braunr> right, that's the only sane way <pinotree> iirc roland didn't like one or more parts of it (but i could be wrong) <braunr> ok
IRC, freenode, #hurd, 2013-07-17
<teythoon> btw pinotree, what happened to your efforts to make dbus work? <pinotree> not much, my initial patch was just a crude hack, a better solution requires more thinkering and work <teythoon> yes, ive seen that <teythoon> but that was only a tiny patch against the libc, surely there must be more to that? <pinotree> not really <teythoon> and the proper fix is to patch pflocal to query the auth server and add the credentials? <pinotree> possibly <teythoon> that doesn't sound to bad, did you give it a try? <pinotree> not really, got caught in other stuff
IRC, freenode, #hurd, 2013-09-02
<gnu_srs1> something is wrong with libc0.3 since the switch to 2.17. dbus does not run any longer when rebuilt <gnu_srs1> the latest build of dbus was with 2.13: libc0.3-dev: already installed (2.13-38) <pinotree> debug it <gnu_srs1> Yes, I will. Maybe somebody could rebuild it and verify my findings? <pinotree> gnu_srs1: your finding is "doesn't work", which is generic and does not help without investigation <gnu_srs1> just rebuild it and: e.g. ./build-debug/bus/dbus-daemon --system (--nofork) <pinotree> gnu_srs1: please, debug it <gnu_srs1> I have partially already. But maybe the problems only shows on my box. I'll rebuild on another box before continuing debugging. <pinotree> gnu_srs1: are you, by chance, running a libc or something else with your scm_creds work? <gnu_srs1> I did, but I've backed to 2.17-92 right now. <gnu_srs1> sane problem with dbus on another box, something's fishy:-( <gnu_srs1> braunr: any good way to find out if the dbus problems are with libpthread? Setting a breakpoint with libc0.3-dbg installed. <braunr> gnu_srs1: i don't know
See glibc, Missing interfaces, amongst many more,
SOCK_CLOEXEC.
IRC, freenode, #hurd, 2013-09-04
<gnu_srs> Hi, looks like dbus requires abstract socket namespace: #undef HAVE_ABSTRACT_SOCKETS What's missing? <pinotree> uh? <pinotree> abstract unix sockets are a Linux feature, and surely it is not mandatory for dbus <gnu_srs> Looks like dbus exits if they are not supported: <gnu_srs> dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED, "Operating system does not support abstract socket namespace\n"); _dbus_close (listen_fd, NULL); 1061 return -1; <pinotree> that is enclosed in a if (abstract) <pinotree> and that parameter is set to true in other places (eg dbus/dbus-server-unix.c) only when HAVE_ABSTRACT_SOCKETS is defined <pinotree> so no, abstract sockets are not mandatory <gnu_srs> Well this code is executed e.g. when running emacs remotely in X. Have to dig deeper then to see why. <pinotree> maybe it could have to do the fact that your dbus server is running in linux and runs by default using such sockets type <pinotree> but yes, you need to dig better <gnu_srs> pinotree: You are right. when running natively the problem is: <pinotree> *drums* <gnu_srs> Manually: Process /usr/lib/at-spi2-core/at-spi-bus-launcher exited with status 1 <pinotree> eh? <gnu_srs> Error retrieving accessibility bus address: org.freedesktop.DBus.Error.Spawn.ChildExited: ^ <pinotree> most probably that service does not start due to the lack of socket credentials which affects dbus <pinotree> uninstall or disable those additional services, they are not your problem <gnu_srs> credentials is enabled. which services to remove? <pinotree> dunno
IRC, freenode, #hurd, 2013-09-11
<gnu_srs> Hi, looks like frebsd had (2008) the same problem as hurd when sending credentials over PF_INET: <gnu_srs> <gnu_srs> Since the dbus code is about the same now (2013), maybe they added support? <gnu_srs> The next message in the thread confirms that the dbus code is invalid, does anybody have pointers? <pinotree> from what i've seen so far, socket credentials are done only for local sockets (ie PF_UNIX) <pinotree> i don't see how things like uid/gid/pid of the socket endpoint can have anything to do with AF_INET <pinotree> and socket credentials in dbus are used only in the [local] socket transport, so there's no issue
IRC, freenode, #hurd, 2013-09-12
<gnu_srs> pinotree: Yes, there is an issue with dbus and AF_INET, see test/corrupt.c: tests /corrupt/tcp and /corrupt/byte-order/tcp:-/ <pinotree> gnu_srs: what's wrong with those? they are just testing the connection over a tcp socket <pinotree> as said above, socket credentials shouldn't be used in such cases <gnu_srs> They are, see also test/relay.c: /relay and /limit tests:-( <pinotree> how are they? <pinotree> please be more specifc... <gnu_srs> Just run the tests yourself with DBUS_VERBOSE=1 <pinotree> you are claiming there is a problem, so please specify what is the actual issue <gnu_srs> DBUS_VERBOSE=1 build-debug/test/test-relay <pinotree> you are claiming there is a problem, so please specify what is the actual issue <gnu_srs> same with test-corrupt <gnu_srs> look at the verbose output: Failed to write credentials: Failed to write credentials byte: Invalid argument <gnu_srs> coming from pfinet since PF_INET is used. <pinotree> check what it does on linux then <pinotree> put an abort() at the start of the read/write socket credential functions in dbus-sysdeps-unix.c and see whether it is triggered also on linux <gnu_srs> SO_PEERCRED is used for linux and LOCAL_CREDS is used for kfreebsd, so we are on our own here:-/ <pinotree> and linux' SO_PEERCRED works also on AF_INET sockets? i'd doubt it <gnu_srs> <pinotree> yes, i know the difference, but please read what i asked again <gnu_srs> I'll check to be sure... <braunr> gnu_srs: user credentials are not supposed to be passed through an AF_INET socket <braunr> how hard is that to understand ? <gnu_srs> OK, linux use send since CMSGCREDS is not defined to write credentials. Working on how they are received. <gnu_srs> braunr: I do understand, but the dbus code tries to do that for Hurd:-( <pinotree> then it should do that on linux too <pinotree> (since the local socket credentials code is isolated in own functions, and they are called only for the unix transport) <gnu_srs> Happiness:-D, almost all dbus tests pass! <gnu_srs> 17(17) dbus tests pass:) <braunr> gnu_srs: hopefully your patch does things right <gnu_srs> which patch <braunr> adding credentials through unix socket <braunr> isn't that what you're doing ? <gnu_srs> the mail to MLs is from the stock installed packages. <braunr> ? <gnu_srs> the test reports are with the SCM_CREDS patches, but I stumbled on the SCM_RIGHTS issues reported to MLs <gnu_srs> no patches applied, just test the attached file yourself. <braunr> so what's your work about ? <gnu_srs> I'm working on SCM_CREDS, yes, and created patches for dbus, glib2.0 and libc. <gnu_srs> the mail was about some bug in the call to io_restrict_auth in sendmsg.c: without any of my patches applied (another image) <teythoon> gnu_srs: you have to give us more context, how are we supposed to know how to find this sendmsg.c file? <pinotree> (it's in glibc, but otherwise the remark is valid) <pinotree> s/otherwise/anyway/
IRC, freenode, #hurd, 2013-10-16
<braunr> gnu_srs: how could you fail to understand credentials need to be checked ? <gnu_srs> braunr: If data is sent via sendmsg, no problem, right? <braunr> gnu_srs: that's irrelevant <gnu_srs> It's just to move the check to the receive side. <braunr> and that is the whole problem <braunr> it's not "just" doing it <braunr> first, do you know what the receive side is ? <braunr> do you know what it can be ? <braunr> do you know where the corresponding source code is to be found ? <gnu_srs> please, describe a scenario where receiving faulty ancillary data could be a problem instead <braunr> dbus <braunr> a user starting privileged stuff although he's not part of a privileged group of users for example <braunr> gnome, kde and others use dbus to pass user ids around <braunr> if you can't rely on these ids being correct, you can compromise the whole system <braunr> because dbus runs as root and can give root privileges <braunr> or maybe not root, i don't remember but a system user probably <pinotree> "messagebus" <gnu_srs> k! <braunr> see <braunr> IRC, freenode, #hurd, 2013-07-17 <braunr> <teythoon> and the proper fix is to patch pflocal to query the auth server and add the credentials? <braunr> <pinotree> possibly <braunr> <teythoon> that doesn't sound to bad, did you give it a try?
IRC, freenode, #hurd, 2013-10-22
<gnu_srs> I think I have a solution on the receive side for SCM_CREDS :) <gnu_srs> A question related to SCM_CREDS: dbus use a zero data byte to get credentials sent. <gnu_srs> however, kfreebsd does not care which data (and credentials) is sent, they report the credentials anyway <gnu_srs> should the hurd implementation do the same as kfreebsd? <youpi> gnu_srs: I'm not sure to understand: what happens on linux then? <youpi> does it see zero data byte as being bogus, and refuse to send the creds? <gnu_srs> linux is also transparent, it sends the credentials independent of the data (but data has to be non-null) <youpi> ok <youpi> anyway, what the sending application writes does not matter indeed <youpi> so we can just ignore that <youpi> and have creds sent anyway <braunr> i think the interface normally requires at least a byte of data for ancilliary data <youpi> possibly, yes <braunr> To pass file descriptors or credentials over a SOCK_STREAM, you need to send or <braunr> receive at least one byte of non-ancillary data in the same sendmsg(2) or <braunr> recvmsg(2) call. <braunr> but that may simply be linux specific <braunr> gnu_srs: how do you plan on implementing right checking ? <gnu_srs> Yes, data has to be sent, at least one byte, I was asking about e.g. sending an integer <braunr> just send a zero <braunr> well <braunr> dbus already does that <braunr> just don't change anything <braunr> let applications pass the data they want <braunr> the socket interface already deals with port rights correctly <braunr> what you need to do is make sure the rights received match the credentials <gnu_srs> The question is to special case on a zero byte, and forbid anything else, or allow any data. <braunr> why would you forbid <braunr> ? <gnu_srs> linux and kfreebsd does not special case on a received zero byte <braunr> same question, why would you want to do that ? <gnu_srs> linux sends credentials data even if no SCM_CREDENTIALS structure is created, kfreebsd don't <braunr> i doubt that <gnu_srs> To be specific:msgh.msg_control = NULL; msgh.msg_controllen = 0; <braunr> bbl <gnu_srs> see the test code: <braunr> back <braunr> why would the hurd include groups when sending a zero byte, but only uid when not ? <gnu_srs> ? <braunr> 1) Sent credentials are correct: <braunr> no flags: Hurd: OK, only sent ids <braunr> -z Hurd: OK, sent IDs + groups <braunr> and how can it send more than one uid and gid ? <braunr> "sent credentials are not honoured, received ones are created" <gnu_srs> Sorry, the implementation is changed by now. And I don't special case on a zero byte. <braunr> what does this mean ? <braunr> then why give me that link ? <gnu_srs> The code still applies for Linux and kFreeBSD. <gnu_srs> It means that whatever you send, the kernel emits does not read that data: see <gnu_srs> socket.h: before struct cmsgcred: the sender's structure is ignored ... <braunr> do you mean receiving on a socket can succeed with gaining credentials, although the sender sent wrong ones ? <gnu_srs> Looks like it. I don't have a kfreebsd image available right now. <gnu_srs> linux returns EPERM <braunr> anyway <braunr> how do you plan to implement credential checking ? <gnu_srs> I'll mail patches RSN
IRC, freenode, #hurd, 2013-11-03
<gnu_srs> Finally, SCM_CREDS (IDs) works:) I was on the right track all the time, it was just a small misunderstanding. <gnu_srs> remains to solve the PID check <youpi> gnu_srs: it should be a matter of adding proc_user/server_authenticate <gnu_srs> there are no proc_user/server_authenticate RPCs? <gnu_srs> do you mean adding them to process.defs (and implement them)? <youpi> gnu_srs: I mean that, yes
IRC, freenode, #hurd, 2013-11-13
<gnu_srs> BTW: I have to modify the SCM_RIGHTS patch to work together with SCM_CREDS, OK? <youpi> probably <youpi> depends on what you change of course
IRC, freenode, #hurd, 2013-11-15
<gnu_srs> Hi, any ideas where this originates, gdb? warning: Error setting exception port for process 9070: (ipc/send) invalid destination port <braunr> gnu_srs: what's process 9070 ? <gnu_srs> braunr: It's a test program for sending credentials over a socket. Have to create a reproducible case, it's intermittent. <gnu_srs> The error happens when running through gdb and the sending program is chrooted: <gnu_srs> -rwsr-sr-x 1 root root 21156 Nov 15 15:12 scm_rights+creds_send.chroot
IRC, freenode, #hurd, 2013-11-16
<gnu_srs> Hi, I have a problem debugging a suid program, see <gnu_srs> I think this reveals a gnumach/hurd bug, it makes things behave strangely for other programs. <gnu_srs> How to get further on with this? <gnu_srs> Or can't I debug a suid program as non-root? <pochu> gnu_srs: if gdb doesn't work for setuid programs on hurd, I suppose you could chmod -s the binary you're trying to debug, login as root and run it under gdb <gnu_srs> pochu: When logged in as root the program works, independent of the s flag setting. <pochu> right, probably the setuid has no effect in that case because your effective uid is already fine <pochu> so you don't hit the gdb bug in that case <pochu> (just guessing) <gnu_srs> It doesn't work in Linux either, so it might be futile. <gnu_srs> trying <pochu> hmm that may be the expected behaviour. after all, gdb needs to be priviledged to debug priviledged processes <gnu_srs> Problem is that it was just the suid properties I wanted to test:( <braunr> gnu_srs: imagine if you could just alter the code or data of any suid program just because you're debugging it
IRC, freenode, #hurd, 2013-11-18
<gnu_srs> Hi, is the code path different for a suid program compared to run as root? <gnu_srs> Combined with LD_PRELOAD? <teythoon> gnu_srs: afaik LD_PRELOAD is ignored by suid programs for obvious security reasons <gnu_srs> aha, thanks:-/ <braunr> gnu_srs: what's your problem with suid ? <gnu_srs> I made changes to libc and tried them out with LD_PRELOAD=... test_progam. It worked as any user (including root), <gnu_srs> but not with suid settings. Justus explained why not. <braunr> well i did too <braunr> but is that all ? <braunr> i mean, why did you test with suid programs in the first place ? <gnu_srs> to get different euid and egid numbers <gnu_srs> hi, anybody seen this with eglibc-2.17-96: locale: relocation error: locale: symbol errno, <gnu_srs> version GLIBC_PRIVATE not defined in file libc.so.0.3 with link time reference <teythoon> yes, I have <teythoon> but afaics nothing did break, so I ignored it
IRC, freenode, #hurd, 2013-11-23
<gnu_srs> Finally 8-) <gnu_srs> Good news: soon both SCM_CREDS _and_ SCM_RIGHTS is supported jointly. RFCs will be sent soon.
IRC, freenode, #hurd, 2013-12-05
<gnu_srs> I have a problem with the SCM_CREDS patch and dbus. gamin and my test code runs fine. <gnu_srs> the problem with the dbus code is that it won't work well with <gnu_srs> auth_user_authenticate in sendmsg and auth_server_authenticate in recvmsg. <gnu_srs> Should I try to modify the dbus code to make it work? <youpi> unless you manage to prove that dbus is not following the posix standard, there is no reason why you should have to modify dbus <gnu_srs> I think the implementation is correct, <gnu_srs> but auth_user_authenticate hangs sendmsg until auth_seerver_authenticate is executed in recvmsg. <gnu_srs> and dbus is not doing that, so it hangs in sendmsg writing a credentials byte. <gnu_srs> well the credentials byte is definitely non-posix. <gnu_srs> I found a bug related to the HURD_DPORT_USE macro too:-( <youpi> ah, yes, auth_user_authenticate might be synchronous indeed, let me think about it <gnu_srs> Nevertheless, I think it's time to publish the code so it can be commented on:-D <youpi> sure <youpi> publish early, publish often
IRC, freenode, #hurd, 2014-01-17
<gnu_srs> youpi: as a start all our requested dbus changes are now committed, and in Debian unstable <youpi> good :)
IRC, freenode, #hurd, 2014-01-30
<pochu> dbus has some known problems <pere> known fixes too? <pochu> <gnu_srs> pochu: Maybe that page should be updated: <youpi> gnu_srs: well, maybe you can do it : <youpi> ) | http://www.gnu.org/software/hurd/open_issues/dbus.html | CC-MAIN-2017-39 | refinedweb | 3,279 | 74.83 |
nima 1.0.5
Nima runtime for flutter.
Nima-Flutter #
Flutter runtime written in Dart with SKIA based rendering.
Installation #
Add
nima as a dependency in your pubspec.yaml file.
Exporting for Flutter #
Export from Nima with the Export to Engine menu. In the Engine drop down, choose Generic.
Adding Assets #
Once you've exported your character file. Add the .nima file and and the .png atlas files to your project's Flutter assets.
Make sure the .png files are at the same level as the.nima file. If you renamed your .nima file, make sure to rename your assets accordingly.
In the future we may opt to package the images into the .nima file as we do for WebGL. Let us know if you're in favor of this!
Example #
Take a look at the provided example application for how to use the NimaActor widget with an exported Nima character.
Usage #
The easiest way to get started is by using the provided NimaActor widget. This is a stateless Flutter widget that allows for one Nima character with one active animation playing. You can change the currently playing animation by changing the animation property's name. You can also specify the mixSeconds to determine how long it takes for the animation to interpolate from the previous one. A value of 0 means that it will just pop to the new animation. A value of 0.5 will mean it takes half of a second to fully mix the new animation on top of the old one.
import 'package:nima/nima_actor.dart'; class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return new NimaActor("assets/Hop", alignment:Alignment.center, fit:BoxFit.contain, animation:"idle"); } }
Advanced Usage #
For more advanced usage such as creating views with multiple Nima characters, multiple active animations, and controllers, please refer to the internals of nima_actor.dart to get acquainted with the API. We'll be posting more detailed tutorials and documentation regarding the inner workings of the API soon.
Contributing #
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request.
License #
See the LICENSE file for license rights and limitations (MIT). | https://pub.dev/packages/nima | CC-MAIN-2020-40 | refinedweb | 390 | 50.73 |
Created on 2007-12-10 19:13 by noam, last changed 2014-03-07 21:30 by eric.snow. This issue is now closed..
I like this; but I don't have time for a complete thourough review.
Maybe Tim can lend a hand?
If Tim has no time, I propose that if it works correctly without leaks
on at least Windows, OSX and Linux, we check it in, and worry about more
review later.
Crys, can you test this on Windows and see if it needs any project file
updates? I'll check OSX. Linux works and I see no leaks.
Applied in r59457
I had to add checks for _M_X64 and _M_IA64 to doubledigits.c. The rest
was fine on Windows.
Noam, perhaps you can help with this? We checked this in but found a
problem: repr(1e5) suddenly returns '1.0'. Can you think of a cause for
this?
I don't know, for me it works fine, even after downloading a fresh SVN
copy. On what platform does it happen?
I've disabled the new repr() in trunk and py3k until somebody has sorted
out the build problems. I've removed doubledigits.c from Makefile.in and
disabled the code with #ifdef Py_BROKEN_REPR in floatobject.c.
> On what platform does it happen?
Linux on x86.
It seems find on PPC OSX.
This suggests it could be a byte order bug.
I also use linux on x86. I think that byte order would cause different
results (the repr of a random float shouldn't be "1.0".)
Does the test case run ok? Because if it does, it's really strange.
There is nothing you can do to repr() that's sufficient by itself to
ensure eval(repr(x)) == x.
The other necessary part is correctly rounded float /input/ routines.
The 754 standard does not require correctly rounding input or output
routines. It does require that eval(repr(x)) == x provided that repr(x)
produce at least 17 significant digits (not necessarily correctly
rounded, but "good enough" so that eval(repr(x)) == x). That's why
Python produces 17 significant digits. While there's no guarantee that
all platform I/O routines are good enough to meet the 754 requirement,
most do, and what Python's repr() actually does is the strongest that
/can/ be done assuming no more than full 754 conformance.
Again, this cannot be improved cross-platform without Python supplying
both output and input routines. Burger's output routines supply only
half of what's needed. An efficient way to do the other half (correctly
rounding input) was first written up by Clinger. Note that neither the
Burger/Dybvig output code nor the Clinger input code are used much in
practice anymore; David Gay's code is usually used instead for "go fast"
reasons:
Clinger also endorses Gay's code:
However, as the Python list link says, Gay's code is "mind-numbingly
complicated".
There is no easy cross-platform solution, where "cross-platform" means
just "limited to 754 platforms".
I've written a small C program for auto config that checks the
endianness of IEEE doubles. Neil has promised to add something to
configure.in when I come up with a small C program. It *should* do the
right thing on a BE platform but I can't test it.
Tim, does Python run on a non IEEE 754 platform? Should the new repr()
be ripped out? I hate to break Python for scientists just to silence
some ignorants and unexperienced newbies.
Again, without replacing float input routines too, this is /not/ good
enough to ensure eval(repr(x)) == x even across just 100%-conforming 754
platforms.
It is good enough to ensure (well, assuming the code is 100% correct)
eval(repr(x)) == x across conforming 754 platforms that go /beyond/ the
standard by also supplying correctly rounding input routines. Some
platform C libraries do, some don't. For example, I believe glibc does
(and builds its I/O code on David Gay's, mentioned before), but that
Microsoft's does not (but that Microsoft's do meet the 754 standard,
which-- again --isn't strong enough for "shortest output" to round-trip
correctly in all cases).
Oh, this is sad. Now I know why Tcl have implemented also a decimal to
binary routine.
Perhaps we can simply use both their routines? If I am not mistaken,
their only real dependency is on a library which allows arbitrary long
integers, called tommath, from which they use a few basic functions.
We can use instead the functions from longobject.c. It will probably
be somewhat slower, since longobject.c wasn't created to allow
in-place operations, but I don't think it should be that bad -- we are
mostly talking about compile time.
The Tcl code can be fonund here:
What Tim says gives another reason for using that code - it means that
currently, the compilation of the same source code on two platforms can
result in a code which does different things.
Just to make sure - IEEE does require that operations on doubles will do
the same thing on different platforms, right?
It's really a shame. It was a nice idea ...
Could we at least use the new formating for str(float) and the display
of floats? In Python 2.6 floats are not displayed with repr(). They seem
to use yet another hook.
>>> repr(11./5)
'2.2'
>>> 11./5
2.2000000000000002
>>> str(11./5)
'2.2'
I think that for str(), the current method is better - using the new
repr() method will make str(1.1*3) == '3.3000000000000003', instead of
'3.3'. (The repr is right - you can check, and 1.1*3 != 3.3. But for
str() purposes it's fine.)
But I actually think that we should also use Tcl's decimal to binary
conversion - otherwise, a .pyc file created by python compiled with
Microsoft will cause a different behaviour from a .pyc file created by
python compiled with Gnu, which is quite strange.
If I think about it some more, why not get rid of all the float
platform-dependencies and define how +inf, -inf and nan behave?
I think that it means:
* inf and -inf are legitimate floats just like any other float.
Perhaps there should be a builtin Inf, or at least math.inf.
* nan is an object of type float, which behaves like None, that is:
"nan == nan" is true, but "nan < nan" and "nan < 3" will raise an
exception. Mathematical operations which used to return nan will raise
an exception (division by zero does this already, but "inf + -inf"
will do that too, instead of returning nan.) Again, there should be a
builtin NaN, or math.nan. The reason for having a special nan object
is compatibility with IEEE floats - I want to be able to pass around
IEEE floats easily even if they happen to be nan.
This is basically what Tcl did, if I understand correctly - see item 6
in .
Noam Raphael wrote:
> * nan is an object of type float, which behaves like None, that is:
> "nan == nan" is true, but "nan < nan" and "nan < 3" will raise an
> exception.
No, that's not correct. The standard defines that nan is always unequal
to nan.
False
>>> float("inf") == float("inf")
True
>>> float("inf") == -1*float("-inf")
True
The float module could gain three singletons nan, inf an neginf so you
can do
True
Christian
That's right, but the standard also defines that 0.0/0 -> nan, and
1.0/0 -> inf, but instead we raise an exception. It's just that in
Python, every object is expected to be equal to itself. Otherwise, how
can I check if a number is nan?
I propose that we add three singletons to the float implementation:
PyFloat_NaN
PyFloat_Inf
PyFloat_NegInf
The singletons are returned from PyFloat_FromString() for "nan", "inf"
and "-inf". The other PyFloat_ method must return the singletons, too.
It's easy to check the signum, special and nan/inf status of an IEEE
double with a struct.
I've already started to work on a way to create nan, inf and -inf cross
platform conform. Right now float("nan"), float("inf") and float("-inf")
works on Linux but doesn't work on Windows. We could also add four
methods to math:
signum(float) -> 1/-1, finity(float) -> bool, infinite(float), nan(float)
Here is my work in progress:
#define Py_IEEE_DBL *(double*)&(ieee_double)
#if defined(LITTLE_ENDIAN_IEEE_DOUBLE) && !defined(BIG_ENDIAN_IEEE_DOUBLE)
typedef struct {
unsigned int m4 : 16;
unsigned int m3 : 16;
unsigned int m2 : 16;
unsigned int m1 : 4;
unsigned int exp : 11;
unsigned int sign : 1;
} ieee_double;
#define Py_IEEE_NAN Py_IEEE_DBL{0xffff, 0xffff, 0xffff, 0xf, 0x7ff, 0}
#define Py_IEEE_INF Py_IEEE_DBL{0, 0, 0, 0, 0x7ff, 0}
#define Py_IEEE_NEGINF Py_IEEE_DBL{0, 0, 0, 0, 0x7ff, 1}
#elif !defined(LITTLE_ENDIAN_IEEE_DOUBLE) && defined(BIG_ENDIAN_IEEE_DOUBLE)
typedef struct {
unsigned int sign : 1;
unsigned int exp : 11;
unsigned int m1 : 4;
unsigned int m2 : 16;
unsigned int m3 : 16;
unsigned int m4 : 16;
} ieee_double;
#define Py_IEEE_NAN Py_IEEE_DBL{0, 0x7ff, 0xf, 0xffff, 0xffff, 0xffff}
#define Py_IEEE_INF Py_IEEE_DBL{0, 0x7ff, 0, 0, 0, 0}
#define Py_IEEE_NEGINF Py_IEEE_DBL{1, 0x7ff, 0, 0, 0, 0}
#else
#error Unknown or no IEEE double implementation
#endif
(1) Despite Tim's grave language, I don't think we'll need to write our
own correctly-rounding float input routine. We can just say that Python
won't work correctly unless your float input routine is rounding
correctly; a unittest should detect whether this is the case. I expect
that more recent C runtimes for Windows are correct.
(1a) Perhaps it's better to only do this for Python 3.0, which has a
smaller set of platforms to support.
.
(3) Detecting NaNs and infs in a platform-independent way is tricky,
probably beyond you (I know it's beyond me). (Of course, producing
standardized output for them and recognizing these as input is easy, and
that should definitely be done.)
(4) Looks like we've been a bit too hasty checking this in. Let's be
extra careful for round #2.
Guido van Rossum wrote:
> .
We can also use the much slower version and check if x > DBL_MAX for
+Inf, x < -DBL_MAX for -Inf and x != x for NaN.
Christian
> > .
No, traditionally Python has just used whatever C's double provides.
There are some places that benefit from IEEE 754, but few that require
it (dunno about optional extension modules).
> > .
Only for IEEE 754 though.
> We can also use the much slower version and check if x > DBL_MAX for
> +Inf, x < -DBL_MAX for -Inf and x != x for NaN.
Of course the latter isn't guaranteed to help for non-IEEE-754
platforms -- some platforms don't have NaNs at all!
> Of course the latter isn't guaranteed to help for
> non-IEEE-754 platforms -- some platforms don't have
> NaNs at all!
ISTM, that years of toying with Infs and Nans has not
yielded a portable, workable solution. I'm concerned
that further efforts will contort and slow-down our
code without benefit. NaNs in particular are a really
difficult case because our equality testing routines
have a fast path where identity implies equality. I don't
think NaNs can be correctly implemented without breaking
that fast path which appears throughout the code base
(even inside the code for dictobject.c; otherwise, how
could you lookup a NaN value).
I recommend punting on the subject of NaNs. Attempting
to "fix" it will necessarily entail introducing a
number of little atrocities that just aren't worth it.
IMO, Practicality beats purity on this one.
The decimal module provides full support for NaNs.
While it is slow, it may be sufficient for someone who
isn't happy with the way float handles them.
[Raymond]
> ...
> NaNs in particular are a really
> difficult case because our equality testing routines
> have a fast path where identity implies equality.
Works as intended in 2.5; this is Windows output:
1.#INF
>>> nan = inf - inf
>>> nan # really is a NaN
-1.#IND
>>> nan is nan # of course this is true
True
>>> nan == nan # but not equal anyway
False
[Guido]
> ... We can just say that Python
> won't work correctly unless your float input routine is rounding
> correctly; a unittest should detect whether this is the case.
Sorry, but that's intractable. Correct rounding is a property that
needs to be proved, not tested. Processors aren't fast enough to test
all (roughly) 2**64 possible doubles in reasonable time, and there's
only one way to get all of them right (correct rounding). There are
many ways to get at least one of them wrong, and short of proof only
exhaustive testing can determine whether at least one is wrong. There
is no "smoking gun" specific test case, either -- different flawed
routines will fail on different inputs.
> I expect that more recent C runtimes for Windows are correct.
Based on what? Unless MS says so somewhere, it's very hard to know.
Vern Paxson and David Hough developed a test program in the early
90's, based on an excruciatingly difficult algorithm I invented for
finding "hard cases", and the code they wrote still appears to be
available from the places Vern mentions in this brief msg:
That code doesn't guarantee to find a failing correct-rounding case if
one exists, but did find failures reasonably efficiently on many
platforms tested at the time.
Guido van Rossum wrote:
> No, traditionally Python has just used whatever C's double provides.
>
> There are some places that benefit from IEEE 754, but few that require
> it (dunno about optional extension modules).
I asked Thomas Wouter about IEEE 754:
"""
I don't know of any system with FPU that does not support 754 semantics.
and all intel CPUs since the 486 have FPUs.
"""
During the discussion we found only one system that has supported Python
in the past but doesn't have IEEE 754 doubles. Pippy (Python for PalmOS)
has no floats at all since the hardware doesn't haven a FPU.
>.
The problem could either be related to SMP or to the mixed mode. Please
try to bind the Python process to one CPU with schedtool or schedutils.
> Only for IEEE 754 though.
> Of course the latter isn't guaranteed to help for non-IEEE-754
> platforms -- some platforms don't have NaNs at all!
Do you know of any system that supports Python and floats but doesn't
have IEEE 753 semantics? I'm asking out of curiosity.
Christian
> Do you know of any system that supports Python and floats but doesn't
have IEEE 753 semantics?
(Assuming you meant 754.)
I'm pretty sure the VAX doesn't have IEEE FP, and it used to run Unix
and Python. Ditto for Crays -- unsure if we still support that though.
What about Nokia S60?
Tim probably knows more.
> Correct rounding is a property that needs to be proved, not tested.
I take it your position is that this can never be done 100% correctly so
it shouldn't go in? That's disappointing, because the stream of
complaints that "round is broken" won't stop (we had two of these in the
bug tracker just this month).
I really want to address this without having to either change
interactive mode to use something besides repr() or changing repr() to
drop precision (assuming correctly rounding input).
We can fix the roundtripping in marshal and pickle and the like by
explicitly using "%.17g" % x instead of repr(x). Scientists who worry
about roundtripping can also do this (though are there any scientists
who work on platforms that don't have correctly-rounding input routines?).
We can also fix it by adopting the Tcl string-to-float code.
[Guido]
> I take it your position is that this can never be done 100% correctly
No. David Gay's code is believed to be 100% correctly-rounded and is
also reasonably fast in most cases. I don't know of any other "open"
string<->float code that achieves both (& expect that's why glibc
adopted Gay's code as its base). I don't know anything about Tcl's
code here, except that, unlike Gay's code, it appears that Tcl's code
also tries to cater to non-754 platforms. It's also easy to be 100%
correct if you don't care about speed (but that's factors of 1000s
slower than Gay's code).
If you care about guaranteeing eval(repr(x)) == x for binary floats,
sorry, there's no way to do it that satisfies all of {cheap, easy,
fast, correct}. If you don't care about guaranteeing eval(repr(x)) ==
x, then it's dead easy to do any number of "wrong" things instead.
For example, much easier and faster than anything discussed here would
be to use the float str() implementation instead. "Produce the
shortest possible output that reproduces the same input" is a
genuinely difficult task (for both output and input) when speed
matters, but it's not really what people are asking for when they see
0.10000000000000001. They would be just as happy with str(x)'s output
instead: it's not people who know a lot about floats who are asking
to begin with, it's people who don't know much at all.
It's not a coincidence that the whole idea of "shortest possible
output" came from the Scheme world ;-) That is, "formally correct at
any price".
> so it shouldn't go in?
What shouldn't go in is something that doesn't solve "the problem",
whatever that's thought to be today. Changing repr() to do
shortest-possible output is not, by itself, a solution /if/ the
problem is thought to be "getting rid of lots of zeroes or nines while
preserving eval(repr(x)) == x". Slows things down yet isn't enough to
guarantee eval(repr(x)) == x. This is just going in circles.
> That's disappointing, because the stream of complaints that "round is broken" won't stop (we
> had two of these in the bug tracker just this month).
I don't care about complaints from people who use binary floating
point without understanding it; they should use the decimal module
instead if they're unwilling or unable to learn. Or give up on
eval(repr(x)) == x for binary floats and then it's all much easier --
although people using binary floats naively will get burned by
something subtler then.
A sufficient response to "round() is broken" complaints is to point to
the Tutorial appendix that specifically discusses "round() is broken"
complaints.
I'd be willing to require eval(repr(x)) == x only for platforms whose
float input routine is correctly rounding. That would make the current
patch acceptable I believe -- but I believe you think there's a better
way in that case too? What way is that?
Also, I'd rather not lock out non-IEEE-754 platforms, but I'm OK with
dropping the above roundtripping invariant there.
If I understand correctly, there are two main concerns: speed and
portability. I think that they are both not that terrible.
How about this:
* For IEEE-754 hardware, we implement decimal/binary conversions, and
define the exact behaviour of floats.
* For non-IEEE-754 hardware, we keep the current method of relying on
the system libraries.
About speed, perhaps it's not such a big problem, since decimal/binary
conversions are usually related to I/O, and this is relatively slow
anyway. I think that usually a program does a relatively few
decimal/binary conversions.
About portability, I think (from a small research I just made) that
S90 supports IEEE-754. This leaves VAX and cray users, which will have
to live with a non-perfect floating-point behaviour.
If I am correct, it will let 99.9% of the users get a deterministic
floating-point behaviour, where eval(repr(f)) == f and
repr(1.1)=='1.1', with a speed penalty they won't notice.
Sounds okay, except that I think that for some folks (e.g. numeric
Python users) I/O speed *does* matter, as their matrices are very
large, and their disks and networks are very fast.
If I were in that situation I would prefer to store the binary
representation. But if someone really needs to store decimal floats,
we can add a method "fast_repr" which always calculates 17 decimal
digits.
Decimal to binary conversion, in any case, shouldn't be slower than it
is now, since on Gnu it is done anyway, and I don't think that our
implementation should be much slower.
> If I were in that situation I would prefer to store the binary
> representation. But if someone really needs to store decimal floats,
> we can add a method "fast_repr" which always calculates 17 decimal
> digits.
They can just use "%.17g" % x
> Decimal to binary conversion, in any case, shouldn't be slower than it
> is now, since on Gnu it is done anyway, and I don't think that our
> implementation should be much slower.
Sure.
I've tracked my problem to the GCC optimizer. The default optimizer
setting is -O3. When I edit the Makefile to change this to -O1 or -O0
and recompile (only) doubledigits.c, repr(1e5) starts returning
'100000.0' again. -O2 behaves the same as -O3.
Now, don't immediately start pointing fingers to the optimizer; it's
quite possible that the code depends on behavior that the C standard
doesn't actually guarantee. The code looks quote complicated.
This is with GCC 4.0.3..
However, I don't think I'm going, in the near future, to add a decimal
to binary implementation -- the Tcl code looks very nice, but it's
quite complicated and I don't want to fiddle with it right now.
If nobody is going to implement the correctly rounding decimal to
binary conversion, then I see three options:
1. Revert to previous situation
2. Keep the binary to shortest decimal routine and use it only when we
know that the system's decimal to binary routine is correctly rounding
(we can check - perhaps Microsoft has changed theirs?)
3. Keep the binary to shortest decimal routine and drop repr(f) == f
(I don't like that option).
If options 2 or 3 are chosen, we can check the 1e5 bug.
>?
> However, I don't think I'm going, in the near future, to add a decimal
> to binary implementation -- the Tcl code looks very nice, but it's
> quite complicated and I don't want to fiddle with it right now.
Fair enough. And the glibc code is better anyway, according to Tim.
(Although probably even more complex.)
> If nobody is going to implement the correctly rounding decimal to
> binary conversion, then I see three options:
> 1. Revert to previous situation
That would be sad since we're so close.
>.
> 3. Keep the binary to shortest decimal routine and drop repr(f) == f
> (I don't like that option).
It would mean that on platforms with unknown-correct rounding *input*
the *output* would be ugly again. I wouldn't mind so much if this was
only VAX or Cray; but if we had to do this on Windows it'd be a real
shame.
> If options 2 or 3 are chosen, we can check the 1e5 bug.
First you'll have to reproduce it -- I can't afford to spend much
quality time with gdb, especially since I don't understand the source
code at all. Though you may be able to pinpoint a possible candidate
based on the characteristics of the error -- it seems to have to do
with not placing the decimal point correctly when there are trailing
zeros.
2007/12/13, Guido van Rossum <report@bugs.python.org>:
>
> >?
No. It may be a kind of an oops, but currently it just won't compile
on platforms which it doesn't recognize, and it only recognizes 754
platforms.
>
> >.
>
The program for testing floating point compatibility is in
To run it, on my computer, I used:
./configure -target Conversions -platform IntelPentium_cpp
make
./IeeeCC754 -d -r n -n x Conversion/testsets/d2bconvd
less ieee.log
This tests only doubles, round to nearest, and ignores flags which
should be raised to signal inexact conversion. You can use any file in
Conversions/testsets/d2b* - I chose this one pretty randomly.
It turns out that even on my gcc 4.1.3 it finds a few floats not
correctly rounded. :(
Anyway, it can be used to test other platforms. If not by the
executable itself, we can pretty easily write a python program which
uses the test data.
I don't know what exactly the errors with gcc 4.1.3 mean - is there a
problem with the algorithm of glibc, or perhaps the testing program
didn't set some flag?
Ok, I think I have a solution!
We don't really need always the shortest decimal representation. We just
want that for most floats which have a nice decimal representation, that
representation will be used.
Why not do something like that:
def newrepr(f):
r = str(f)
if eval(r) == f:
return r
else:
return repr(f)
Or, in more words:
1. Calculate the decimal representation of f with 17 precision digits,
s1, using the system's routines.
2. Create a new string, s2, by rounding the resulting string to 12
precision digits.
3. Convert the resulting rounded string to a new double, g, using the
system's routines.
4. If f==g, return s2. Otherwise, return s1.
It will take some more time than the current repr(), because of the
additional decimal to binary conversion, but we already said that if
speed is extremely important one can use "'%f.17' % f". It will
obviously preserve the eval(repr(f)) == f property. And it will return a
short representation for almost any float that has a short representation.
This algorithm I will be glad to implement.
What do you think?
This is what I was thinking of before, although I'd use "%.16g"%f and
"%.17g"%f instead of str(f) and repr(f), and I'd use float() instead
of eval().
I suspect that it doesn't satisfy Tim Peters though, because this may
depend on a rounding bug in the local platform's input function.
It's not a question of bugs. Call the machine writing the string W and
the machine reading the string R. Then there are 4 ways R can get back
the double W started with when using the suggested algorithm:
1. W and R are the same machine. This is the way that's most obvious.
The rest apply when W and R are different machines (by which I really
mean both use 754 doubles, but use different C libraries for
double<->string conversions):
2. W and R both do correct-rounding string->double. This is obvious too
(although it may not be obvious that it's /not/ also necessary that W
do correct-rounding double->string).
3. W and R both conform to the 754 standard, and W did produce 17
significant digits (or fewer if trailing zeroes were chopped). This one
is neither obvious nor non-obvious: that "it works" is something the
754 standard requires.
4. W produced fewer than 17 significant digits, and W and/or R do not do
correct rounding. Then it works, or fails, by luck, and this has
nothing to do whether the double<->string algorithms have bugs. There
are countless ways to code such routines that will fail in some cases --
doing correct rounding in all cases is the only way that won't fail in
some cases of producing fewer than 17 significant digits (and exactly
which cases depend on all the details of the specific
non-correct-rounding algorithms W and/or R implement). ;-)
BTW, about: passing that test
does not guarantee the platform does correct rounding. It uses a fixed
set of test cases that were in fact obtained from running the algorithm
I invented for efficiently finding "hard" cases in the early 90s (and
implemented by Vern Paxson, and then picked up by the authors of the
test suite you found). It's "very likely" that an implementation that
doesn't do correct rounding will fail on at least one of those cases,
but not certain. Exhaustive testing is impossible (too many cases).
I think that we can give up float(repr(x)) == x across different
platforms, since we don't guarantee something more basic: We don't
guarantee that the same program doing only floating point operations
will produce the same results across different 754 platforms, because
in the compilation process we rely on the system's decimal to binary
conversion. In other words, using the current repr(), one can pass a
value x from platform A platform B and be sure to get the same value.
But if he has a python function f, he can't be sure that f(x) on
platform A will result in the same value as f(x) on platform B. So the
cross-platform repr() doesn't really matter.
I like eval(repr(x)) == x because it means that repr(x) captures all
the information about x, not because it lets me pass x from one
platform to another. For communication, I use other methods.
Tim Peters wrote:
> ;-)
Time is right.
The only way to ensure that it works on all platforms is a full and
mathematical correct proof of the algorithm and all functions used by
the algorithms. In the mean time *we* are going to release Python 40k
while *you* are still working on the proof. *scnr* :)
I like to propose a compromise. The patch is about making the
representation of a float nicer when users - newbies and ordinary people
w/o mathematical background - work on a shell or do some simple stuff.
They want a pretty and short representation of
2.2
>>> "My value is %s" % (11./5.)
'My value is 2.2'
The latter already prints 2.2 without the patch but the former prints
2.2000000000000002 on my machine. Now here comes the interesting part.
In 2.6 the shell uses PyObject_Print and the tp_print slot to print a
float. We can overwrite the str() and tp_print slot to use the new
algorithm while keeping the old algorithm for repr().
Unfortunately the tp_print slot is no longer used in Python 3.0. It
could be resurrected for this purpose (object.c:internal_print()).
str(1.) -> new code
repr(1.) -> old and good representation
>>> 1. -> new code
Christian
ISTM shorter repr's are inherently misleading and will make it more
harder to diagnose why 1.1 * 3 != 3.3 or why round(1.0 % 0.1, 1) == 0.1
which is *very* far-off of what you might expect..
FWIW, I prefer the current 17 digit behavior, its speed, its cross-754
round-trip guarantees, and it psychological cues about exactness.
2007/12/18, Raymond Hettinger <report@bugs.python.org>:
>.
Currently, repr(1.3) == '1.3', suggesting that it is exactly
represented, which isn't true. I think that unless you use an
algorithm that will truncate zeros only if the decimal representation
is exact, the suggested algorithm is less confusing than the current
one, in that it doesn't suggest that 1.3 is exactly stored and 1.1
isn't.
Right, there are plenty of exceptions to the suggestion of exactness.
Still, I find the current behavior to be more helpful than not
(especially when trying to explain the examples I gave in the previous
I'm concerned that the tone of the recent discussion shows a strong
desire to just get something checked-in despite dubious benefits and
despite long standing invariants.
It is a bit cavalier to declare "we can give up float(repr(x)) == x
across different platforms." Our NumPy friends might not be amused. If
a PEP on this were circulated, I'm sure we would receive some frank and
specific feedback.
Likewise, I find it questionable that shorter reprs are helpful. Is
there any evidence supporting that assertion? My arguments above
suggest short reprs are counter-productive because they mask the cause
of problems that might otherwise be self-evident. Of course, it's
possible that both could be true, short reprs may help in some cases
(by masking oddities) and may hurt in other cases (by masking the
underlying cause of an oddity or by making a false psychological
suggestion).
About the educational problem. If someone is puzzled by "1.1*3 !=
3.3", you could always use '%50f' % 1.1 instead of repr(1.1). I don't
think that trying to teach people that floating points don't always do
what they expect them to do is a good reason to print uninteresting
and visually distracting digits when you don't have to.
About the compatibility problem: I don't see why it should matter to
the NumPy people if the repr() of some floats is made shorter. Anyway,
we can ask them, using a PEP or just the mailing list.
About the benefit: If I have data which contains floats, I'm usually
interested about their (physical) value, not about their last bits.
That's why str(f) does what it does. I like repr(x) to be one-to-one,
as I explained in the previous message, but if it can be made more
readable, why not make it so?
[Tim:".
Guido> ... trying to explain why two numbers both print the same but
Guido> compare unequal ...
This is not a Python-specific issue. The notion of limited precision was
pounded into our heads in the numerical analysis class I took in college,
1980-ish. I'm pretty sure that was before both Python and IEEE-754. I'm
pretty sure I programmed for that class in Fortran.
Guido> ... (and God forbid anyone proposes adding fuzz to float ==).
Is it possible to produce a FuzzyFloat class which is a subclass of float
that people could use where they needed it? Its constructor could take a
tolerance arg, or it could be initialized from a global default. I'm not
suggesting that suchh a class replace float in the core, but that it might
be useful to have it available in some contexts (available via PyPI, of
course). I'm offline at the moment or I'd poke around before asking.
Skip
Guido, right, for that to work reliably, double->str and str->double
must both round correctly on the platform doing the repr(), and
str->double must round correctly on the platform reading the string.
It's quite easy to understand why at a high level: a simple (but
tedious) pigeonhole argument shows that there are more representable
doubles than there are possible 16-digit decimal outputs. Therefore
there must exist distinct doubles (say, x and y) that map to the same
16-digit decimal output (in fact, there are cases where 7 consecutive
doubles all map to the same correctly-rounded 16-digit decimal string).
When reading that back in, there's no room for error in deciding which
of {x, y} was /intended/ -- the str->double conversion has to be
flawless in deciding which of {x, y} is closest to the 16-digit decimal
input, and in case x and y are equally close, has to apply 754's
round-to-nearest/even rule correctly. This can require exact
multi-thousand bit arithmetic in some cases, which is why the 754
standard doesn't require it (thought to be impractically expensive at
the time).
> which would really turn the educational issue into an educational
> nightmare, trying to explain why two numbers both print the same
> but compare unequal
Well, newbies see that in, e.g., spreadsheets every day. You generally
have to work to get a spreadsheet to show you "all the digits"; in some
spreadsheets it's not even possible. "Not all digits are displayed"
should be within the grasp of must students without suffering nightmares ;-)
If.
> If someone has a more recent version of MS's compiler,
> I'd be interested to know what this does:
Visual Studio 2008 Express Edition gives the same results:
['1024', '1024', '1024', '1024', '1024', '1024', '1024.000000000001']
(Tested release and debug builds, with trunk version and py3k branch)
Thanks, Amaury! That settles an issue raised earlier: MS's
string<->double routines still don't do correct rounding, and "aren't
even close" (the specific incorrect rounding showed here isn't a hard
almost-exactly-half-way case).
I'd like to reopen this. I'm still in favor of something like to this
algorithm:
def float_repr(x):
s = "%.16g" % x
if float(s) != x:
s = "%.17g" % x
s1 = s
if s1.startswith('-'):
s1 = s[1:]
if s1.isdigit():
s += '.0' # Flag it as a float
# XXX special case inf and nan, see floatobject.c::format_double
return s
combined with explicitly using %.17g or the new hex notation (see issue
3008) in places where cross-platform correctness matters, like pickle
and marshal.
This will ensure float(repr(x)) == x on all platforms, but not cross
platforms -- and I don't care.
I'm fine with only doing this in 3.0.
If you think using 16 (when possible) will stop complaints, think again
;-) For example,
>>> for x in 0.07, 0.56:
... putatively_improved_repr = "%.16g" % x
... assert float(putatively_improved_repr) == x
... print putatively_improved_repr
0.07000000000000001
0.5600000000000001
(those aren't the only "2-digit" examples, but I expect those specific
examples work the same under Linux and Windows).
IOW, 16 doesn't eliminate base-conversion surprises, except at the 8
"single-digit surprises" (i/10.0 for i in range(1, 5) + range(6, 10)).
To eliminate "2-digit surprises" (like 0.07 and 0.56 above), and higher,
in this way, you need to add a loop and keeping trying smaller
conversion widths so long as they convert back to the original input.
Keep it up, and you can make repr(float) so slow it would be faster to
do perfect rounding in Python ;-)
Here's a rough-and-tumble implementation of that idea, for Py3k.
That is truly maddening! :-(
I guess Noam's proposal to return str(x) if float(str(x)) == x makes
more sense then. I don't really care as much about 1.234567890123 vs.
1.2345678901229999 as I care about 1.2345 vs. 1.2344999999999999.
(This comment is supposed to *precede* the patch.)
Here's a fixed patch, float2.diff. (The previous one tasted of an
earlier attempt.)
[Tim]
> If you think using 16 (when possible) will stop complaints, think again
> ;-) For example, ...
Aha! But using *15* digits would be enough to eliminate all 1, 2, 3, 4,
..., 15 digit 'surprises', wouldn't it?! 16 digits doesn't quite work,
essentially because 2**-53 is still a little larger than 10**-16, but 15
digits ought to be okay.
Here's the 'proof' that 15 digits should be enough:
Suppose that x is a positive (for simplicity) real number that's exactly
representable as a decimal with <= 15 digits. We'd like to know that
'%.15g' % (nearest_float_to_x) recovers x.
There are integers k and m such that 2**(k-1) <= x <= 2**k, and 10**(m-1)
< x <= 10**m. (e.g. k = ceiling(log_2(x)), m = ceiling(log_10(x)))
Let y be the closest floating-point number to x. Then |y-x| <= 2**(k-54). Hence |y-x| <= x*2**-53 < x/2 * 10**-15 <= 10**(m-15)/2. It follows that
x is the closest 15-digit decimal to y, hence that applying '%.15g' to y
should recover x exactly.
The key step here is in the middle inequality, which uses the fact that
2**-52 < 10**-15. The above doesn't work for subnormals, but I'm guessing
that people don't care too much about these. The argument above also
depends on correct rounding, but there's actually sufficient leeway here
(that is, 2**-52 is quite substantially smaller than 10**-15) that the
whole thing would probably work even in the absence of correct rounding..
Mildly off-topic: it seems that currently eval(repr(x)) == x isn't
always true, anyway. On OS X 10.5.4/Intel, I get:
>>> x = (2**52-1)*2.**(-1074)
>>> x
2.2250738585072009e-308
>>> y = eval(repr(x))
>>> y
2.2250738585072014e-308
>>> x == y
False
This is almost certainly an OS X bug...
About (2**52-1)*2.**(-1074): same outcome under Cygwin 2.5.1, which is
presumably based on David Gay's "perfect rounding" code. Cool ;-)
Under the native Windows 2.5.1:
>>> x = (2**52-1)*2.**(-1074)
>>> x
2.2250738585072009e-308
>>> y = eval(repr(x))
>>> y
0.0
Hard to say whether that's actually worse :-(
About %.15g, good point! It probably would "make Guido happy". It's
hard to know for sure, because despite what people say about this, the
real objection to the status quo is aesthetic, not technical, and
there's no disputing tastes.
My tastes agree that %.17g is a pain in the ass when using the
interactive shell -- I rarely want to see so many digits. But %.15g,
and even %.12g, would /still/ be a pain in the ass, and for the same
reason. Most times I'd be happiest with plain old %g (same as %.6g).
OTOH, sometimes I do want to see all the bits, and sometimes I'd like a
fixed format (like %.2f), and so on.
Alas, all choices suck for strong reasons (either technical or aesthetic
-- and, BTW, your "lots of trailing zeroes" idea won't fly because of
the latter).
The introduction of hex formats for floats should make this starkly
clear: using hex I/O for float repr would be the ideal technical
choice: easy to code, extremely fast, compact representation, and
highly portable. Those are supposedly repr's goals, regardless of
whether the repr string is easily readable by humans. But you know
without asking that using hex format for repr(float) has no chance of
being adopted -- because it's ugly :-)
In all this discussion, it seems that we have not discussed the
possibility of adapting David Gay's code, dtoa.c, which nicely handles
both halves of the problem. It's also free and has been well exercised
over the years.
It's available here:
It'd probably have to be touched up a bit. Guido notes that, for
example, malloc is called without checking the return value.
Nevertheless, the core is what we're looking for, I believe.
It's described in the paper: "Correctly rounded binary-decimal and
decimal-binary conversions", David M. Gay
It comes recommended by Steele and White (output) and by Clinger
(input), in the retrospectives on their seminal papers.
> It'd probably have to be touched up a bit.
This may be an understatement. :-).
>> It'd probably have to be touched up a bit.
> This may be an understatement. :-)
Probably so. Nevertheless, it's got to be easier
than approaching the problem from scratch.
And considering that this discussion has been
going on for over a year now, it might be a way to
move forward.
>.
I would consider compiling the library with flags appropriate to forcing
64-bit IEEE arithmetic if possible. Another possibility is to explore
gdtoa.c
which is supposed to include code for extended precision, quad precision,
etc.
> I would consider compiling the library with flags appropriate to forcing
> 64-bit IEEE arithmetic if possible.
Using the right compiler flags is only half the battle, though. You
should really be setting the rounding precision dynamically: set it to
53-bit precision before the call to strtod, and then restore it to
whatever the original precision was afterwards. And the magic formula for
doing this is likely to vary from platform to platform. As far as I can
tell, the C99 standard doesn't suggest any standard spellings for changing
the rounding precision.
It's not unknown for libm functions on x86 to blindly assume that the x87
FPU is set to its default of extended-precision (64-bit) rounding, so it's
risky to just set 53-bit rounding for the whole of Python's execution.
And contrary to popular belief, setting 53-bit rounding *still* doesn't
give the x87 FPU IEEE 754 semantics: there are issues at the extremes of
the floating-point range, and I'm not 100% convinced that those issues
wouldn't affect the dtoa.c strtod.
I'm not saying that all this is impossible; just that it's subtle and
would involve some work.
Even if someone devoted the time to get possibly get this right, it
would be somewhat difficult to maintain.
What maintenance issues are you anticipating?
Gay's code is 3800+ lines and includes many ifdef paths that we need to
get right. Mark points out that the code itself needs additional work.
The discussions so far also get into setting compiler flags on
different systems and I would imagine that that would need to be
maintained as those compilers change and as hardware gets updated. The
main challenge for a maintainer is to be sure that any change doesn't
break something. AFAICT, this code is very difficult to validate.
The comments is the first 180 lines of code give a good survey of the
issues a maintainer would face when given a bug report in the form of:
eval(repr(f)) != f for myhardware x compiled with mycompiler c with
myflags f and running on operating system z. There reports would be
even more challenging for cross-platform comparisons.
The GNU library's float<->string routines are based on David Gay's.
Therefore you can compare those to Gay's originals to see how much
effort was required to make them "mostly" portable, and can look at the
history of those to get some feel for the maintenance burden.
There's no difficulty in doing this correctly except for denormals. The
pain is almost entirely in doing it correctly /fast/ -- and that is
indeed hard (which accounts for the extreme length and complexity of
Gay's code).
> The GNU library's float<->string routines are based on David Gay's.
> Therefore you can compare those to Gay's originals
Sounds reasonable.
> (which accounts for the extreme length and complexity of Gay's code).
Looking at the code, I'm actually not seeing *extreme* complexity.
There are a lot of ifdefs for things that Python probably doesn't
care about (e.g., worrying about whether the inexact and underflow
flags get set or not; hexadecimal floats, which Python already has
its own code for; weird rounding modes, ...). There's some pretty
standard looking bignum integer stuff (it might even be possible to
substitute PyLong arithmetic for this bit). There's lots of boring
material for things like parsing numeric strings. The really
interesting part of the code is probably only a few hundred lines.
I think it looks feasible to adapt Gay's code for Python. I'm not sure
I'd want to adapt it without understanding it fully, but actually that
looks quite feasible too.
The x87 control word stuff isn't really a big problem: it can be dealt
with. The bit I don't know how to do here is using the autoconf
machinery to figure out whether the x87 FPU exists and is in use on a
particular machine. (I put in an autoconf test for x87-related double
rounding recently, which should be a pretty reliable indicator, but that
still fails if someone's already set 53-bit rounding precision...).
A side-note: for x86/x86_64, we should really be enabling SSE2 by
default whenever possible (e.g., on all machines newer than Pentium 3).
Mark, "extreme complexity" is relative to what's possible if you don't
care about speed; e.g., if you use only bigint operations very
straightforwardly, correct rounding amounts to a dozen lines of
obviously correct Python code.
So is it worth trying to come up with a patch for this? (Where this =
making David Gay's code for strtod and dtoa usable from Python.).
On Thu, Feb 26, 2009 at 1:01 PM, Tim Peters <report@bugs.python.org> wrote:
>.
I *think* I understood Preston as saying that he has the expertise and
is interested in doing this. He's just looking for guidance on how
we'd like the software engineering side of things to be done, and I
think he's getting good feedback here. (Preston, please butt in if I
misunderstood you.)
Huh. I didn't see Preston volunteer to do anything here ;-)
One bit of software engineering for whoever does sign on: nothing kills
porting a language to a new platform faster than needing to get an
obscure but core subsystem working. So whatever is done here, to the
extent that it requires fiddling with obscure platform-specific gimmicks
for manipulating FPU state, to that extent also is it important to
retain a std C fallback (i.e., one requiring no porting effort).
This all started with email to Guido that y'all didn't see,
wherein I wondered if Python was interested in such a thing.
Guido said: Sure, in principle, please see the discussion associated
with this change.
I probably don't have all the required expertise today,
but I am patient and persistent. I wouldn't be very fast either,
'cause I have other things on my plate. Nevertheless, it seems like
an interesting project and I'm happy to work on it.
If Mark or someone else wants to jump in, that's fine too.
Preston
I'd be interested in working with Preston on adapting David Gay's code.
(I'm interested in looking at this anyway, but I'd much prefer to do it
in collaboration with someone else.)
It would be nice to get something working before the 3.1 betas, but that
seems a little optimistic. 2.7 and 3.2 are more likely targets.
Preston, are you going to be at PyCon?
I'm sorry, but it seems to me that the conclusion of the discussion in
2008 is that the algorithm should simply use the system's
binary-to-decimal routine, and if the result is like 123.456, round it
to 15 digits after the 0, check if the result evaluates to the original
value, and if so, return the rounded result. This would satisfy most
people, and has no need for complex rounding algorithms. Am I mistaken?
If I implement this, will anybody be interested?
Noam
I).
Do you mean msg58966?
I'm sorry, I still don't understand what's the problem with returning
f_15(x) if eval(f_15(x)) == x and otherwise returning f_17(x). You said
(msg69232) that you don't care if float(repr(x)) == x isn't
cross-platform. Obviously, the simple method will preserve eval(repr(x))
== x, no matter what rounding bugs are present on the platform.
I changed my mind on the cross-platform requirement.
Would it be acceptable to use shorter float repr only on big-endian and
little-endian IEEE 754 platforms, and use the full 17-digit repr on other
platforms? This would greatly simplify the adaptation and testing of
Gay's code.
Notable platforms that would still have long repr under this scheme, in
order of decreasing significance:
- IBM zSeries mainframes when using their hexadecimal FPU (recent
models also have IEEE 754 floating-point, and Linux on zSeries
uses that in preference to the hex floating-point).
- ARM, Old ABI (uses a mixed-endian IEEE 754 format; a newer set
of ABIs appeared recently that use big or little-endian IEEE 754)
- Cray SV1 (introduced 1998) and earlier Cray machines. Gay's code
doesn't support the Cray floating-point format anyway. I believe
that newer Crays (e.g., the X1, introduced in 2003) use IEEE
floating-point.
- VAX machines, using VAX D and G floating-point formats. More recent
Alpha machines support IEEE 754 floats as well.
- many ancient machines with weird and wonderful floating-point
schemes
As far as I can determine, apart from the IBM machines described above all
new platforms nowadays use an IEEE 754 double format. Sometimes IEEE
arithmetic is only emulated in software; often there are shortcuts taken
with respect to NaNs and underflow, but in all cases the underlying format
is still IEEE 754, so Gay's code should work. Gay's careful to avoid
problems with machines that flush underflow to zero, for example.
Gay's code only actually supports 3 floating-point formats: IEEE 754 (big
and little-endian), IBM hex format and VAX D floating-point format. There
are actually (at least?) two variants of D floating-point: the version
used on VAX, which has a 56-bit mantissa and an 8-bit exponent, and the
Alpha version, which only has a 53-bit mantissa (but still only an 8-bit
exponent); Gay's code only supports the former.
I'm quite convinced that the VAX stuff in Gay's code is not worth much to
us, so really the only question is whether it's worth keeping the code to
support IBM hexadecimal floating-point. Given the difficulty of testing
this code and the (significant but not overwhelming) extra complexity it
adds, I'd like to remove it.
Sounds good to me.
+1 on the fallback strategy for platforms we don't know how to handle.
Eric and I have set up a branch of py3k for work on this issue. URL for
(read-only) checkout is:
My changes on the py3k-short-float-repr branch include:
- Create a new function PyOS_double_to_string. This will replace
PyOS_ascii_formatd. All existing internal uses of PyOS_ascii_formatd
follow this pattern: printf into a buffer to build up the format string,
call PyOS_ascii_formatd, then parse the format string to determine what
to do. The changes to the API are:
- discrete parameters instead of a printf-like format string. No
parsing is required.
- returns PyMem_Malloc'd memory instead of writing into a supplied
buffer.
- Modify all callers of PyOS_ascii_formatd to call PyOS_double_to_string
instead. These are:
- Modules/_pickle.c
- Objects/complexobject.c
- Objects/floatobject.c
- Objects/stringlib/formatter.h
- Objects/unicodeobject.c
- Python/marshal.c
Remaining to be done:
- Re-enable 'n' (locale-aware) formatting in float.__format__().
- Decide what to do about the change in meaning of "alt" formatting with
format code 'g' when an exponent is present, also in float.__format__().
- Have marshal.c deal with potential memory failures returned from
PyOS_double_to_string.
- Deprecate PyOS_ascii_formatd.
So work on the py3k-short-float-repr branch is nearing completion, and
we (Eric and I) would like to get approval for merging these changes
into the py3k branch before this month's beta.
A proposal: I propose that the short float representation should be
considered an implementation detail for CPython, not a requirement for
Python the language. This leaves Jython and IronPython and friends free
to do as they wish. All that should be required for Python itself is
that float(repr(x)) == x for (non-nan, non-infinite) floats x. Does
this seem reasonable to people following this issue? If it's
controversial I'll take it to python-dev.
Eric's summarized his changes above. Here are mine (mostly---some
of this has bits of Eric's work in too):
- change repr(my_float) to produce output with minimal number of
digits, on IEEE 754 big- and little-endian systems (which includes all
systems we can actually get our hands on right now).
- there's a new file Python/dtoa.c (and a corresponding file
Include/dtoa.h) with a cut-down version of Gay's dtoa and strtod in it.
There are comments at the top of that file indicating the changes that
have been made from Gay's original code.
- one minor semantic change: repr(x) changes to exponential format at
1e16 instead of 1e17. This avoids a strange situation where Gay's code
produces a 16-digit 'shortest' integer string for a particular float and
Python's formatting code then pads with an incorrect '0':
>>> x = 2e16+8. # 2e16+8. is exactly representable as a float
>>> x
20000000000000010.0
There's no way that this padding with bogus digits can happen for
numbers less than 1e16.
Changing target Python versions.
I'll upload a patchset to Rietveld sometime soon (later today, I hope).
I've uploaded the current version to Rietveld:
The Rietveld patch set doesn't show the three new files, which are:
Python/dtoa.c
Include/dtoa.h
Lib/test/formatfloat_testcases.txt
Those three missing files have now been added to Rietveld.
Just for reference, in case anyone else encounters this: the reason those
files were missing from the initial upload was that after I svn merge'd
from py3k-short-float-repr to py3k, those files were being treated (by
svn) as *copies* from py3k-short-float-repr, rather than new files, so svn
diff didn't show any output for them. Doing:
svn revert Python/dtoa.c
svn add Python/dtoa.c
(and similarly for the other two files) fixed this.
On Tue, Apr 7, 2009 at 3:10 AM, Mark Dickinson <report@bugs.python.org> wrote:
> A proposal: I propose that the short float representation should be
> considered an implementation detail for CPython, not a requirement for
> Python the language. This leaves Jython and IronPython and friends free
> to do as they wish.
In principle that's fine with me.
> All that should be required for Python itself is
> that float(repr(x)) == x for (non-nan, non-infinite) floats x. Does
> this seem reasonable to people following this issue? If it's
> controversial I'll take it to python-dev.
Historically, we've had a stronger requirement: if you print repr(x)
and ship that string to a different machine, float() of that string
returns the same value, assuming both systems use the same internal FP
representation (e.g. IEEE). Earlier in this bug (or elsewhere) Tim
Peters has pointed out that on some platforms, in particular Windows,
input conversion doesn't always round correctly and only works
correctly when the input has at least 17 digits (in which case you
apparently don't need to round, and truncation works just as well --
that's all the C standard requires, I believe).
Now that pickle and marshal no longer use repr() for floats I think
this is less important, but still at least worth considering. I think
by having our own input function we solve this if both hosts run
CPython, but it might break for other implementations.
In order to make progress I recommend that we just not this and don't
use it to hold up the implementation, but I think it's worth noticing
in docs somewhere.
I think ANY attempt to rely on eval(repr(x))==x is asking for trouble,
and it should probably be removed from the docs.
Example: The following C code can vary *even* on a IEEE 754 platform,
even in two places in the same source file (so same compile options),
even in the same 5 lines of code recompiled after changing code that
does even not touch/read 'x' or 'y':
double x, y;
x = 3.0/7.0;
y = x;
/* ... code that doesnt touch/read x or y ... */
printf(" x==y: %s", (x==y) ? "true" : "false");
So, how can we hope that eval(repr(x))==x is EVER stable? Equality and
floating point should raise the hairs on the back of everyone's neck...
(Code above based on in section
"Current IEEE 754 Implementations", along with a great explanation on
why this is true. The code example is a little different, but the same
concept applies.)
> Historically, we've had a stronger requirement: if you print repr(x)
> and ship that string to a different machine, float() of that string
> returns the same value, assuming both systems use the same internal FP
> representation (e.g. IEEE).
Hmm. With the py3k-short-float-repr stuff, we should be okay moving
things between different CPython boxes, since float() would use Gay's code
and so would be correctly rounded for any length input, not just input
with 17 significant digits.
But for a CPython-generated short repr to give the correct value on some
other implementation, that implementation would also have to have a
correctly rounded string->float.
For safety's sake, I'll make sure that marshal (version 1) and pickle
(protocol 0) are still outputting the full 17 digits.
> I think ANY attempt to rely on eval(repr(x))==x is asking for trouble,
> and it should probably be removed from the docs.
I disagree. I've read the paper you refer to; nevertheless, it's still
perfectly possible to guarantee eval(repr(x)) == x in spite of the
various floating-point details one has to deal with. In the worst
case, assuming that C doubles are IEEE 754 binary64 format, for double -
> string conversion one can simply cast the double to an array of 8
bytes, extract the sign, exponent and mantissa from those bytes, and
then compute the appropriate digit string using nothing but integer
arithmetic; similarly for the reverse operation: take a digit string,
do some integer arithmetic to figure out what the exponent, mantissa and
sign should be, and pack those values back into the double. Hey presto:
correctly rounded string -> double and double -> string conversions!
Add a whole bag of tricks to speed things up in common cases and you end
up with something like David Gay's code.
It *is* true that the correctness of Gay's code depends on the FPU being
set to use 53-bit precision, something that isn't true by default on x87
FPUs. But this isn't hard to deal with, either: first, you make sure
that you're not using the x87 FPU unless you really have to (all Intel
machines that are newer than Pentium 3 have the SSE2 instruction set,
which doesn't have the problems that x87 does); second, if you *really*
have to use x87 then you figure out how to set its control word to get
53-bit precision and round-half-to-even rounding; third, if you can't
figure out how to set the control word then you use a fallback something
like that described above.
The process that you describe in msg85741 is a way of ensuring
"memcmp(&x, &y, sizeof(x))==0", and it's portable and safe and is the
Right Thing that we all want and expect. But that's not "x==y", as that
Sun paper explains. It's close, but not technically accurate, as the
implication arrow only goes one way (just as "x=1/y" implies "xy=1" in
algebra, but not the other way around)
I'd be interested to see if you could say that the Python object
model/bytecode interpretation enforces a certain quauntum of operations
that actually does imply "eval(repr(x))==x"; but I suspect it's
unprovable, and it's fragile as Python grows to have more support in
CLI/LLVM/JVM backends.
My pedantic mind would strip any and all references to floating-point
equality out of the docs, as it's dangerous and insidiously misleading,
even in "obvious" cases. But, I'll stop now :) (FYI: I've enjoyed the
~100 messages here.. Great stuff!)
The py3k-short-float-repr branch has been merged to py3k in two parts:
r71663 is mostly concerned with the inclusion of David Gay's code into the
core, and the necessary floating-point fixups to allow Gay's code to be
used (SSE2 detection, x87 control word manipulation, etc.)
r71665 contains Eric's *mammoth* rewrite and upgrade of the all the float
formatting code to use the new _Py_dg_dtoa and _Py_dg_strtod functions.
Note: the new code doesn't give short float repr on *all* platforms,
though it's close. The sticking point is that Gay's code needs 53-bit
rounding precision, and the x87 FPU uses 64-bit rounding precision by
default (though some operating systems---e.g., FreeBSD, Windows---change
that default). For the record, here's the strategy that I used: feedback
(esp. from experts) would be appreciated.
- If the float format is not IEEE 754, don't use Gay's code.
- Otherwise, if we're not on x86, we're probably fine.
(Historically, there are other FPUs that have similar
problems---e.g., the Motorola 68881/2 FPUs---but I think they're
all too old to be worth worrying about by now.)
- x86-64 in 64-bit mode is also fine: there, SSE2 is the default.
x86-64 in 32-bit mode (e.g., 32-bit Linux on Core 2 Duo) has
the same problems as plain x86. (OS X is fine: its gcc has
SSE2 enabled by default even for 32-bit mode.)
- Windows/x86 appears to set rounding precision to 53-bits by default,
so we're okay there too.
So:
- On gcc/x86, detect the availability of SSE2 (by examining
the result of the cpuid instruction) and add the appropriate
flags (-msse2 -mfpmath=sse2) to BASECFLAGS if SSE2 is available.
- On gcc/x86, if SSE2 is *not* available, so that we're using the
x87 FPU, use inline assembler to set the rounding precision
(and rounding mode) before calling Gay's code, and restore
the FPU state directly afterwards. Use of inline assembler is pretty
horrible, but it seems to be *more* portable than any of the
alternatives. The official C99 way is to use fegetenv/fesetenv to get
and set the floating-point environment, but the fenv_t type used to
store the environment can (and will) vary from platform to platform.
- There's an autoconf test for double-rounding. If there's no
evidence of double rounding then it's likely to be safe to use
Gay's code: double rounding is an almost unavoidable symptom of
64-bit precision on x87.
So on non-Windows x86 platforms that *aren't* using gcc and *do* exhibit
double rounding (implying that they're not using SSE2, and that the OS
doesn't change the FPU rounding precision to 53 bits), we're out of luck.
In this case the old long float repr is used.
The most prominent platform that I can think of that's affected by this
would be something like Solaris/x86 with Sun's own compiler, or more
generally any Unix/x86 combination where the compiler isn't gcc. Those
platforms need to be dealt with on a case-by-case basis, by figuring out
for each such platform how to detect and use SSE2, and how to get and set
the x87 control word if SSE2 instructions aren't available.
Note that if any of the above heuristics is wrong and we end up using
Gay's code inappropriately, then there will be *loud* failure: we'll know
about it.
Closing this. There are a few known problems remaining, but they've all
got their own issue numbers: see issue 5780, issue 4482.
Hello folks,
IIUC, autoconf tries to enable SSE2 by default without asking. Isn't it
a problem for people distributing Python binaries (e.g. Linux vendors)
and expecting these binaries to work on legacy systems even though the
system on which the binaries were compiled supports SSE2?
Or am I misunderstanding what the changes are?
Yes, I think you're right.
Perhaps the SSE2 support should be turned into an --enable-sse2 configure
option, that's disabled by default? One problem with this is that I don't
know how to enable SSE2 instructions for compilers other than gcc, so the option would only apply to gcc-based systems.
Disabling SSE2 would just mean that all x86/gcc systems would end up using
the inline assembler to get and set the control word; so we'd still get
short float repr everywhere we did before.
Perhaps better to drop the SSE2 bits completely. Anybody who
actually wants SSE2 instructions in their binary can do a
CC="gcc -msse2 -mfpmath=sse" configure && ...
Unless there are objections, I'll drop everything involving SSE2 from
the configure script.
It's a bit of a shame, though: it's definitely desirable to be using
the SSE2 instructions for floating-point whenever possible. Fewer
surprises due to double rounding or random 80-bit register spilling,
better performance on underflow and NaNs, ...
SSE2 detection and flags removed in r71723. We'll see how the buildbots
fare...
Is there a way to use SSE when available and x86 when it's not. IIRC,
floating point used to work that way (using a C lib as a fallback on
systems w/o coprocessor support).
> Is there a way to use SSE when available and x86 when it's not.
Probably, but I don't think there is any point doing so. The main
benefit of SSE2 is to get higher performance on floating point intensive
code, which no pure Python code could be regarded as (the CPU cycles
elapsed between two FP instructions would dwarf the cost of executing
the FP instructions themselves).
The situation is different for specialized packages like numpy, but
their decisions need not be the same as ours AFAIK.
The advantage is accuracy. No double rounding. This will also help the
math.fsum() function that is also susceptible to double rounding.
[Raymond]
> Is there a way to use SSE when available and x86 when it's not.
I guess it's possible in theory, but I don't know of any way to do this in
practice. I suppose one could trap the SIGILL generated by the attempted
use of an SSE2 instruction on a non-supported platform---is this how
things used to work for 386s without the 387? That would make a sequence
of floating-point instructions on non-SSE2 x86 horribly slow, though.
Antoine: as Raymond said, the advantage of SSE2 for numeric work is
accuracy, predictability, and consistency across platforms. The SSE2
instructions finally put an end to all the problems arising from the
mismatch between the precision of the x87 floating-point registers (64-
bits) and the precision of a C double (53-bits). Those difficulties
include (1) unpredictable rounding of intermediate values from 64-bit
precision to 53-bit precision, due to spilling of temporaries from FPU
registers to memory, and (2) double-rounding. The arithmetic of Python
itself is largely immune to the former, but not the latter. (And of
course the register spilling still causes headaches for various bits of
CPython).
Those difficulties can be *mostly* dealt with by setting the x87 rounding
precision to double (instead of extended), though this doesn't fix the
exponent range, so one still ends up with double-rounding on underflow.
The catch is that one can't mess with the x87 state globally, as various
library functions (especially libm functions) might depend on it being in whatever the OS considers to be the default state.
There's a very nice paper by David Monniaux that covers all this:
definitely recommended reading after you've finished Goldberg's "What
Every Computer Scientist...". It can currently be found at:
An example: in Python (any version), try this:
>>> 1e16 + 2.9999
10000000000000002.0
On OS X, Windows and FreeBSD you'll get the answer above.
(OS X gcc uses SSE2 by default; Windows and FreeBSD both
make the default x87 rounding-precision 53 bits).
On 32-bit Linux/x86 or Solaris/x86 you'll likely get the answer
10000000000000004.0
instead, because Linux doesn't (usually?) change the Intel default
rounding precision of 64-bits. Using SSE2 instead of the x87 would have
fixed this.
</standard x87 rant>
Just came across this bug, I don't want to reopen this or anything, but regarding the SSE2 code I couldn't help thinking that why can't you just detect the presence of SSE2 when the interpreter starts up and then switch implementations based on that? I think that's what liboil does (). | http://bugs.python.org/issue1580 | CC-MAIN-2016-36 | refinedweb | 12,061 | 63.39 |
CodePlexProject Hosting for Open Source Software
I'm really new in prism so maybe it's just stupid's question. (and sorry about my english, it's not my natural).
I'm tring to build wpf application who use view-switching navigation framework and i got this problem: when ever i use NavigateRequest it's works only if the region is empty, else it just don't doing anything. Am i forgetting to add somthing?
thanx
Not sure about WPF, but in silverlight you need to implement INavigationAware and IRegionMemberLifetime in your view/viewmodel. The KeepAlive and IsNavigationTarget need to return true for you to be able to navigate between views.
IRegionMemberLifetime helps you decide whether you want to remove the deactivated view from the region or just mark it as decativated. IsNavigationTarget in INavigationAware helps you specify that the view can be naviagted to using the RequestNavigate.
Try the above and let me know.
Thank you for the answer. I'm all ready implemanting IConfirmNavigationRequest (and it got the same methods as INavigationReqwest). I've tried to Implement IRegionMemberLifetime. but still when ever region is filled it's view can't be replaced.
Can you post the code for the requestnavigate?
private void RequestNavigate(string RegionName, string ViewName)
{
this.RegionManager.RequestNavigate(RegionName,
new Uri(ViewName, UriKind.Relative));
}
this is the code i'm using. I got baseView class and this is it prototype:
public class BaseView : UserControl, IConfirmNavigationRequest, IActiveAware, INavigateAsync, IRegionMemberLifetime
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://compositewpf.codeplex.com/discussions/235585 | CC-MAIN-2017-22 | refinedweb | 278 | 50.53 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.