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
|
|---|---|---|---|---|---|
Created on 2020-11-19 13:41 by danielhrisca, last changed 2020-11-19 13:41 by danielhrisca.
First I have to apologize if this was discussed before; I've searched the issues and googled the problem but I got nothing obvious.
I'm trying to pass a memoryview slice as argument to struct packing functions to avoid creating intermediate bytes objects
from struct import Struct
s = Struct('<2Q500s').pack_into
buffer = bytearray(7000)
data = bytes(300)
s(buffer, 0, 500, 500, memoryview(data)[4:])
and I get this error:
error: argument for 's' must be a bytes object
Why is it not possible to use memoryviews in this case?
It is also strange for me that we can use a memoyview as the target buffer, so this works fine:
s(memoryview(buffer)[10:], 0, 500, 500, data[4:])
|
https://bugs.python.org/issue42408
|
CC-MAIN-2020-50
|
refinedweb
| 138
| 55.78
|
cgroups — Linux control groups
Control groups,−v2.txt.)
Because of the problems with the initial cgroups
implementation (cgroups version 1), starting in Linux 3.10,
work began on a new, orthogonal implementation to remedy
these problems. Initially marked experimental, and hidden
behind the
−o
_.
Under cgroups v1, each controller may be mounted against a separate cgroup filesystem that provides its own hierarchical organization of the processes on the system. It is also possible to.). −t cgroup −o cpu none /sys/fs/cgroup/cpu
It is possible to comount multiple controllers against
the same hierarchy. For example, here the
cpu and
cpuacct controllers are
comounted against a single hierarchy:
mount −t cgroup −o −t cgroup −o all cgroup /sys/fs/cgroup
(One can achieve the same result by omitting
−o.
A mounted cgroup filesystem can be unmounted using the umount(8) command,.−bwc.txt.
cpuacct(since Linux 2.6.24;
))
CONFIG_CGROUP_CPUACCT
This provides accounting for CPU usage by groups of processes.
Further information can be found in the kernel
source file
Documentation/cgroup−v−v1/cpusets.txt.
memory(since Linux 2.6.25;
))
CONFIG_MEMCG
The memory controller supports reporting and limiting of process memory, kernel memory, and swap used by cgroups.
Further information can be found in the kernel
source file
Documentation/cgroup−v1/memory.txt.
devices(since Linux 2.6.26;
))
CONFIG_CGROUP_DEVICE
This supports controlling which processes may create (mknod) devices as well as open them for reading or writing. The policies may be specified as allow-lists and deny-lists..
rdma(since Linux 4.11;
))
CONFIG_CGROUP_RDMA
The RDMA controller permits limiting the use of RDMA/IB-specific resources per cgroup.
Further information can be found in the kernel
source file
Documentation/cgroup-v1/rdma.txt. it with
a process.
The default value of the
release_agent file is
empty, meaning that no release agent is invoked.
The content of the
release_agent file can also
be specified via a mount option when the cgroup filesystem
is mounted:
mount -o release_agent=pathname .... specifying
cgroup_no_v1=named..
Cgroups v2 provides a unified hierarchy against which all controllers are mounted.
"Internal" processes are not permitted. With the exception of the root cgroup, processes may reside only in leaf nodes (cgroups that do not themselves contain child cgroups). The details are somewhat more subtle than this, and are described below.
Active cgroups must be specified via the files
cgroup.controllers and
cgroup.subtree_control.
The
tasks
file has been removed. In addition, the
cgroup.clone_children
file that is employed by the
cpuset controller has
been removed.).
In cgroups v1, the ability to mount different controllers against different hierarchies was intended to allow great flexibility for application design. In practice, though, the flexibility turned out to.
disabled. To do this, specify the
cgroup_no_v1=list option on
the kernel boot command line;
list is a comma-separated
list of the names of the controllers to disable, or the
word
all to
disable all v1 controllers. (This situation is correctly
handled by systemd(1), which falls back
to operating without the specified controllers.)
Note that on many modern systems, systemd(1) automatically
mounts the
cgroup2 filesystem at
/sys/fs/cgroup/unified during
the boot process.
The following controllers, documented in the kernel
source file
Documentation/cgroup-v2.txt, are
supported in cgroups version 2:
io(since Linux 4.5)
This is the successor of the version 1
blkio controller.
memory(since Linux 4.5)
This is the successor of the version 1
memory
controller.
pids(since Linux 4.5)
This is the same as the version 1
pids controller.
perf_event(since Linux 4.11)
This is the same as the version 1
perf_event
controller.
rdma(since Linux 4.11)
This is the same as the version 1
rdma controller.
cpu(since Linux 4.15)
This is the successor to the version 1
cpu and
cpuacct
controllers. '−' controllers that are exercised in the
child cgroups.
When a controller (e.g.,
pids) is present in the
cgroup.subtree_control file
of a parent cgroup, then the corresponding
controller-interface files (e.g.,
pids.max) are automatically
created in the children of that cgroup and can be used to
exert resource control in the child cgroups.
Cgroups v2 enforces a so-called "no internal processes" rule. Roughly speaking, this rule means that,..
With cgroups v2, a new mechanism is provided to obtain
notification about when a cgroup becomes empty. The cgroups
v1
release_agent
and
notify_on_release files are
removed, and replaced by a new, more general-purpose file,
cgroup.events.
This read-only
cause the bits
POLLPRI and
POLLERR to be returned in the
revents
field.
The cgroups v2 release-notification mechanism provided
by the
populated
field of the
cgroup.events underneath descendant cgroups. A value of 0 in this file means that no descendant cgroups can be created. An attempt to create a descendant namespace:
delegate a subhierarchy under the existing delegated
hierarchy. (For example, the delegated hierarchy might be
associated with an unprivileged container run by
cecilia.) Even if a cgroup
namespace was employed, because both hierarchies are owned
by the unprivileged user
cecilia, the following
illegitimate actions could be performed:
A process in the inferior hierarchy could change
the resource controller possibilities.
The
nsdelegate
mount option only has an effect when performed in the
initial mount namespace; in other mount namespaces, the
option is silently ignored.
cgroup_no_v1=all systemd.legacy_systemd_cgroup_controller
These options cause the kernel to boot with the cgroups v1 controllers disabled (meaning that the controllers are available in the v2 hierarchy), and tells systemd(1) not to mount and use the cgroup v2 hierarchy, so that the v2 hierarchy can be manually mounted with the desired options after boot-up.arch delegatee) matches the real user ID or the saved set-user-ID of the target process. Before Linux 4.11, this requirement also applied in cgroups v2 (This was a historical requirement inherited from cgroups v1 that was later deemed unnecessary, since the other rules suffice for containment in cgroups v2.).
This is a domain cgroup that serves as the root of a threaded subtree. This cgroup type is also known as "threaded root"..
There are two pathways that lead to the creation of a threaded subtree. The first pathway proceeds as follows:
We write the string
"threaded" to the
cgroup.type
file of a cgroup
y/z that currently
has the type
domain. This has the
following effects:
-
The type of the cgroup
y/zbecomes
threaded.
-
The type of the parent cgroup,
y, becomes domain threaded. The parent cgroup is the root of a threaded subtree (also known as the "threaded root").
-
All other cgroups under
ythat were not already of type
threaded(because they were inside already existing threaded subtrees under the new threaded root) are converted to type domain invalid. Any subsequently created cgroups under
ywill also have the type domain invalid.:
In an existing cgroup,
z, that currently has
the type
domain, we (1) enable
one or more threaded controllers and (2) make a
process a member of
z. (These two steps
can be done in either order.) This has the following
consequences:
-
The type of
zbecomes domain threaded.
-
All of the descendant cgroups of
xthat were not already of type
threadedare converted to type domain invalid.:
-
domainor domain threaded: start the creation of a threaded subtree (whose root is the parent of this cgroup) via the first of the pathways described above;
-
domain invalid: convert this cgroup (which is inside a threaded subtree) to a usable (i.e.,
threaded) state;
- name of the controller.
-
The unique ID of the cgroup hierarchy on which this controller is mounted. If multiple cgroups v1 controllers are bound to the same hierarchy, then each will show the same hierarchy ID in this field. The value in this field will be 0 if:
-
the controller is not mounted on a cgroups v1 hierarchy;
-
the controller is bound to the cgroups v2 single unified hierarchy; or
-
the controller is disabled (see below).
-
The number of control groups in this hierarchy using this controller.
-
This field contains the value 1 if this controller is enabled, or 0 if it has been disabled (via the
cgroup_disablekernel:
hierarchy-ID:controller-list:cgroup-path
For example:
5:cpuacct,cpu,cpuset:/daemons
The colon-separated fields are, from left to right:
-
For cgroups version 1 hierarchies, this field contains a unique hierarchy ID number that can be matched to a hierarchy ID in
/proc/cgroups. For the cgroups version 2 hierarchy, this field contains the value 0.
-
For cgroups version 1 hierarchies, this field contains a comma-separated list of the controllers bound to the hierarchy. For the cgroups version 2 hierarchy, this field is empty.
-
This field contains the pathname of the control group in the hierarchy to which the process belongs. This pathname is relative to the mount point of the hierarchy.
applications supports and has enabled. Features are listed one per line:
$ cat /sys/kernel/cgroup/features nsdelegate
The entries that can appear in this file are:
-
nsdelegate(since Linux 4.15)
-
The kernel supports the
nsdelegatemount option.
prlimit(1), systemd(1), systemd-cgls(1), systemd-cgtop(1), clone(2), ioprio_set(2), perf_event_open(2), setrlimit(2), cgroup_namespaces(7), cpuset(7), namespaces(7), sched(7), user_namespaces(7)
|
https://manpages.net/htmlman7/cgroups.7.html
|
CC-MAIN-2022-21
|
refinedweb
| 1,535
| 57.37
|
v0.12.0¶
This release adds official support for both Django 1.7, as well as several bugfixes.
Warning
If you were previously relying on importing the
User model from
tastypie.compat, this import will no longer work correctly. This was
removed due to the way app-loading works in Django 1.7 & no great solution
for dodging this issue exists.
If you were using either of:
from tastypie.compat import User from tastypie.compat import username_field
Please update your code as follows:
from tastypie.compat import get_user_model from tastypie.compat import get_username_field
Bugfixes¶
Drastic reworking of the test suite. (SHA: 95f57f7)
Fixed Travis to run Python 3.4 tests. (SHA: 7af528c)
Fixed a bug where URLs would be incorrectly handled if the
api_name&
resource_namewere the same. (SHA: fd55aa3)
Fixed a test requirement for PyYAML. (SHA: b4f6531)
Added support for Django 1.7. (SHA: 7881bb6)
Documentation updates:
- Fixed header in
tools.rst. (SHA: f8af772)
- Fixed header in
resources.rst. (SHA: 9508cbf)
|
https://django-tastypie.readthedocs.io/en/latest/release_notes/v0.12.0.html
|
CC-MAIN-2018-09
|
refinedweb
| 161
| 62.75
|
in reply to Note on usage of ours variables and a question
I think the best approach depends on the specific application, which you haven't described very much. Of course TIMTOWTDI, but I would suggest that instead of the modules exporting a debug variable or something similar, the main script should instead set the debug flag on the module. So for example, if I write OO classes, I might give the constructor a debug argument that is set based on a $DEBUG package variable in the main script. If it's a simple module, it might have its own our $DEBUG variable in its package, and then the main code could do $Module::Name::DEBUG = $DEBUG. This will allow you to use the $DEBUG variable name everywhere, and still keep the possibility of somewhat more fine-grained control, instead of one global debug flag that enables debug messages everywhere. So like this is how I typically do it:
use warnings; use strict; use Getopt::Long; GetOptions( 'd|debug' => \(our $DEBUG) ) or die "Bad options\n"; $Foo::DEBUG = $DEBUG; print "Debugging main\n" if $DEBUG; Foo::foo(); my $bar = Bar->new( debug => $DEBUG ); $bar->quz(); { package Foo; our $DEBUG; sub foo { print "Debugging Foo\n" if $DEBUG; } } { package Bar; sub new { my ($class,%args) = @_; my $self = { %args }; return bless $self, $class; } sub quz { my $self = shift; print "Debugging $self->quz()\n" if $self->{debug}; } }
Also question about 'export" behavior". If I export variable debug from module A does it became "normal variable" in main:: so that I can use it in module B? what will happen if I export it from module b as well ? It should bind it to the same variable, right?
If I understand your question correctly, then no, two different exports will overwrite each other. If you have a module X with our $Z that gets exported to main, and then a module Y with our $Z that also gets exported to main, the second export will clobber the first. Consider that you've got two variables, one in each package, and so the variable $main::Z can only be an alias for one or the other.
use warnings; use strict; BEGIN { package X; use me::inlined; # alternative: $INC{__PACKAGE__.'.pm'}=$0; use Exporter 'import'; our @EXPORT = qw/$Z/; our $Z = 'from '.__PACKAGE__; } BEGIN { package Y; use me::inlined; # alternative: $INC{__PACKAGE__.'.pm'}=$0; use Exporter 'import'; our @EXPORT = qw/$Z/; our $Z = 'from '.__PACKAGE__; } use X; use Y; print "$Z\n"; # prints "from Y"
Although I wouldn't recommend it (!), you could have all your modules reference $main::DEBUG with the shorthand $::DEBUG, or even alias the package variables to $main::DEBUG, then you'd only have one central variable. However, the problems with this are that you lose the fine-grained control of the debug flag, and also if these modules are loaded into code that doesn't know about their behavior (remember modules are meant to be re-used), things might break when those modules reach outside of their package into variables that aren't really theirs.
Can anybody enlighten me about this behavior?
I would suggest a careful read of the sections "Packages" and "Symbol Tables" in perlmod (the rest of the document is also very interesting).
BTW does Perl have a system variable "debug" that is global and does not need qualification with the package name?
No, not that I'm aware of in the core.
Why we can't alias variables in other namespaces? Is not this an artificial restriction?
It's possible - you'd have to show an instance of where it isn't working for you.
|
https://www.perlmonks.org/?node_id=11108915;displaytype=print
|
CC-MAIN-2021-49
|
refinedweb
| 609
| 57.91
|
Hi I want to insert new info at a specific line in a file. But I want to also delete the previous info on that line. However I've only been able to put in the new info not overwrite the previous. How can I easily accomplish this?
Code:#include <iostream> // for std::cout #include <fstream> #include <iomanip> #include <stdlib.h> #include <cstdio> #include <string> using namespace std; int main() { fstream dataflow; int i =0; int value=19; string item; dataflow.open("print.txt", ios::in | ios::out); for (i=0;i<10;i++) { dataflow << i << std::endl; } dataflow.seekp(0, ios::beg); dataflow << value; cout << value << endl; return 0; }
|
https://cboard.cprogramming.com/cplusplus-programming/104666-inserting-text-file.html
|
CC-MAIN-2017-47
|
refinedweb
| 110
| 76.72
|
I experience a bug in pixman 0.26.0 on Linux n32 MIPS64 with SMI graphics card and Loongson 2F processor.
If I try to move a window by dragging it by a pointer or moving a slit bar between bookmark area and document area in xpdf, the rectangle area under the pointer gets corrupted (some dark horizontal lines appear there) and the machine usually crashes (complete lock-up, no IP or SysRq responsible).
The 0.24.4 version of pixman is Ok.
Interesting. Thanks for the report. I'll take a look.
If you configure pixman-0.26.0 with --disable-loongson-mmi, can you reproduce your problem?
Good point. Disabling the FPU vector optimizations specific for Loongson helped. (I thought they have been merged after 0.26.0 release.)
I compile with CFLAGS="-O2 -march=loongson2f -mabi=n32 -pipe -mplt -Wa,-mfix-loongson2f-nop" LDFLAGS="-Wl,-O1 -Wl,--as-needed" using GCC-4.6.3 and binutils-2.22. I have "ICT Loongson-2 V0.3 FPU V0.1" processor.
To Petr Pisar: Could you try to compile and run the following simple test program (with -O2 optimizations)?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <string.h>
#include <sys/time.h>
void alarm_handler(int a)
{
volatile double d1 = 1.1, d2 = 2.2, d3;
d3 = d1 + d2;
printf(".\n");
alarm(1);
}
int main(int argc, char **argv)
{
volatile double d = 1.5;
signal(SIGALRM, alarm_handler);
alarm(1);
while (d == 1.5) {}
printf("we should not be here\n");
return 0;
}
(In reply to comment #4)
> To Petr Pisar: Could you try to compile and run the following simple test
> program (with -O2 optimizations)?
>
It works flawlessly.
I cannot reproduce this issue with pixman-0.27.2.
Notice 1: It's possible the lock-up was caused by X server killed by kernel due to the bug in the pixman. This puts the virtual console into dead state usually.
Notice 2: If I find SIGILLing application on the Loongson, it usually turn outs the compiler optimizes float arithmetics to multiply-and-add instruction which causes FPU exception if the factor register contains not-a-number (e.g. a result of previous division by zero).
(In reply to comment #6)
> I cannot reproduce this issue with pixman-0.27.2.
>
> Notice 1: It's possible the lock-up was caused by X server killed by kernel
> due to the bug in the pixman.
It's more like the lock-up is caused by the kernel failing to correctly save/restore FPU state on context switches, causing FPU registers to contain unpredictable/corrupted values and various bad things happening. If 'make check' test passes for pixman on your machine, then the culprit is almost certainly your kernel.
The X server itself is a bit unique in the way it does input handling:
The code from comment 4 was an adapted variant of the testcase intended to reproduce the issue with *very* similar symptoms on ARM a long time ago (dragging cursor means that a lot of input handling and drawing via pixman is happening at the same time):
Even though the test seemed to work on your machine, no real conclusions can be made yet. In any case you need to debug the issue and identify the root cause of it yourself. Or wait for somebody else to successfully reproduce the problem. Good luck.
Nobody can reproduce this anymore, so I'm closing the bug. If the issue resurfaces, feel free to reopen.
|
https://bugs.freedesktop.org/show_bug.cgi?id=50946
|
CC-MAIN-2016-22
|
refinedweb
| 591
| 67.35
|
I posted this in an older thread, but I think it actually needs its own thread for discussion and possible eventual resolution.
I'm finding that Spiceworks isn't finding Microsoft Security Essentials installed on Windows 7 workstations.
Upon further investigation, I'm seeing that there may be an issue with what version of the Security Center is being used to report antivirus data.
Some newer products, like MSE, are apparently registering themselves with only SecurityCenter2 in WMI data. This seems to be the case, so far as I can see at the moment, with Windows 7.
For example:
C:\Users\ed.lee>wmic /namespace:\\root\SecurityCenter PATH AntiVirusProduct GET /value
No Instance(s) Available.
C:\Users\ed.lee>wmic /namespace:\\root\SecurityCenter2 PATH AntiVirusProduct GET /value
displayName=Microsoft Security Essentials
instanceGuid={2E6C4BAB-3371-CD46-62DC-0E0A86B42619}
pathToSignedProductExe=C:\Program Files\Microsoft Security Essentials\msseces.exe
pathToSignedReportingExe=C:\Program Files\Microsoft Security Essentials\MsMpEng.exe
productState=397312
Any chance that SpiceWorks could capture data from this new source, too?
15 Replies
Jan 8, 2010 at 4:09 UTC
akp982 is an IT service provider.
As Microsoft Security Essentials is for Home PC's only i dont think its supported by Spiceworks
Jan 8, 2010 at 4:14 UTC
Sure it is. It works fine on Windows XP and Windows Vista. There's no reason why Spiceworks can't be updated to pay attention to SecurityCenter2 data. Also, there's no reason to assume that Spiceworks' userbase would NOT use Security Essentials. It's freely available for every non-server version of Windows, and is already well-rated.
Jan 8, 2010 at 4:17 UTC
akp982 is an IT service provider.
Yes but its illegal to use on a corpate network i believe? TBH i have no idea then, maybe one day
Jan 8, 2010 at 4:19 UTC
Nope, nothing illegal about it. Microsoft's own license agreement says nothing at all about using it on a domain network. Clearly they want you to use Forefront for that purpose, but the license agreement for MSE says nothing to preclude that possibility.
Jan 8, 2010 at 4:31 UTC
akp982 is an IT service provider.
- INSTALLATION AND USE RIGHTS.
- Use. You may install and use any number of copies of the software on your devices in your household for use by people who reside there or for use in your home-based small business.
From: h ttp://
Jan 8, 2010 at 4:38 UTC
Fine, but I still don't read that as explicitly excluding it from use. I'm not really interested in arguing legalese here, since that's not the purpose of my question.
However, more to my original point... Forefront's next release will also be using SecurityCenter2 to register its presence, especially for Windows 7. So, again, why can't Spiceworks pay attention to the status of SecurityCenter2 for antivirus?
Jan 8, 2010 at 4:41 UTC
akp982 is an IT service provider.
Because Spiceworks have been working on getting spiceworks fully working with apache to speed it up as well as the recent move to 64bit which is going a head tonight.
You may want to checkout the feature request section and add it or spice it up.
Jan 12, 2010 at 2:32 UTC
Hi guys,
We're in the process of adding support for SecurityCenter2:
[]
That should take care of any AV recognition problems associated with OS's like 7 that exclusively use SecurityCenter2, or Vista which allows both SecurityCenter and SecurityCenter2 to be used.
Jan 15, 2010 at 12:33 UTC
Thanks, Ben! Gig 'em!
Mar 5, 2010 at 10:29 UTC
1st Post
Is the support for SecurityCenter2 complete yet? If not, is there an estimated date?
Thanks,
Steve
Oct 13, 2010 at 9:14 UTC
I to can not view the data for Microsoft Security Essentials on my Windows 7 machines is this going to work soon?
Oct 19, 2010 at 7:48 UTC
Hi all, anyone who was not seeing their AV reported back by Win7/Vista devices should give Spiceworks 5.0 a try. We have added support for the Windows backend that should allow Spiceworks to detect AVs that use the newer Security Center in Vista/7.
Oct 26, 2010 at 12:11 UTC
Outstanding work guys keep it up and I'll see you on the game grid!
Oct 27, 2010 at 3:32 UTC
In re: to Ben.B last post ... i just installed Spiceworks v.5 today on a windows 7 machine, but MSE is still not being picked up as an antivirus program. Does this mean the problem has not been resolved?
Oct 28, 2010 at 10:02 UTC
Will, if you navigate to the device in the Inventory and click the Rescan button does MSE get picked up properly after the scan completes?
|
https://community.spiceworks.com/topic/85618-spiceworks-windows-7-and-antivirus-reporting
|
CC-MAIN-2016-44
|
refinedweb
| 810
| 64
|
During a panel discussion at the 1999 JavaOne conference Bill Joy, talking about the things he didn't like about Java, stated that he "didn't want char to be [a] numerical type". He was outvoted on this one, and as we know the Java char was blessed as a 16-bit numeric primitive type. I don't know whether Joy objected to it being in the numeric type hierarchy (so any char can be cast to an int for example), or whether he didn't like it being a primitive, but what is for sure is that the char's limited width has finally had an impact in the way support for Unicode 4.0 is implemented in Java 1.5.
char
int
It was Unicode 3.1 that introduced supplementary characters: characters that require more than 16 bits to represent them. (These characters are rare - think obscure mathematical symbols and languages no longer used outside academia - like Linear B.) Since Java tracks the Unicode standard, the next release - 1.5 - had to solve the problem of how to represent these characters given that a Java char is a 16-bit type. The details of how this was achieved are explained in the excellent article from Sun: Supplementary Characters in the Java Platform, which is required reading for all serious Java programmers. (You might want to read these two introductions first if you're not up on Unicode: Joel Spolsky and Tim Bray.)
For reasons of backward compatibility the fix broke the one-to-one correspondence between Unicode characters and Java chars. A char should now be interpreted as a UTF-16 code unit.
The breaking of this correspondence means applications that deal with individual characters may need to be changed - the above article has details. This got me thinking about how you count the number of characters in a piece of text.
The following class counts the number of char primitives from the passed in Reader. This is an efficient way to count the number of Unicode characters in Java releases before 1.5.
Reader
public class CharCounter {
public int count(Reader in) throws IOException {
char[] buffer = new char[4096];
int count = 0;
int len;
while((len = in.read(buffer)) != -1) {
count += len;
}
return count;
}
}
Running the following snippet of code exercises CharCounter:
CharCounter
String text = "\u0041\u00DF\u6771\uD801\uDC00";
CharCounter cc = new CharCounter();
System.out.println(cc.count(new StringReader(text)));
5
The text string is a sequence of four Unicode characters (the same as the ones in the table in the above mentioned article, which also gives representative glyphs):
\uD801\uDC00
Character.isHighSurrogate()
public class UnicodeCharacterCounter {
public int count(Reader in) throws IOException {
char[] buffer = new char[4096];
int count = 0;
int len;
while((len = in.read(buffer)) != -1) {
count += len;
for (int i = 0; i < len; i++) {
if (Character.isHighSurrogate(buffer[i])) {
count--;
}
}
}
return count;
}
}
The test code
String text = "\u0041\u00DF\u6771\uD801\uDC00";
UnicodeCharacterCounter ucc = new UnicodeCharacterCounter();
System.out.println(ucc.count(new StringReader(text)));
4
For this application - counting characters - there is actually a Java library that can help out by hiding the low-level implementation details of supplementary characters: java.test.BreakIterator. (In other applications you may still need to test explicitly for supplementary characters, as in the previous example.) Here is an example for counting the number of characters in a string.
java.test.BreakIterator
public class UserCharacterCounter {
public int count(String text) {
int count = 0;
BreakIterator iter = BreakIterator.getCharacterInstance();
iter.setText(text);
while (iter.next() != BreakIterator.DONE) {
count++;
}
return count;
}
}
String text = "\u0041\u00DF\u6771\uD801\uDC00";
UserCharacterCounter ucc = new UserCharacterCounter();
System.out.println(ucc.count(text));
4
The BreakIterator character iterator generally conforms to what a user expects a character to be. In some circumstances it diverges from the Unicode character definition of what a character is. For example,
BreakIterator
UserCharacterCounter ucc = new UserCharacterCounter();
System.out.println(ucc.count("g\u0301"));
1
Even as seemingly simple a concept as "character" has a least three interpretations (there are doubtless more). Happily, Java can cope with all three. (How do other languages fare?) However, I have a nagging question as Java approaches its tenth birthday: if Java were being invented today would a char be 32 bits?
You are right.
I had thought the same matter When the EA of JDK5 out along with the So-Called supplementary characters.
-pprun
Posted by: pprun on March 23, 2005 at 06:18 AM
Manual Trackback to a German Blog about Unicode Support in Java:
Bernd Eckenfels' IT Blog:
Posted by: ecki on March 23, 2005 at 02:40 PM
"For reasons of backward compatibility the fix broke the one-to-one correspondence between Unicode characters and Java chars."
Backward compatibility? Funny Sun.
Posted by: xhq on March 24, 2005 at 04:35 AM
Does this mean that all Java programs are broken now? If some application takes 10 first characters from a string to show them on the screen, then it might actually show less than 10 and the last character can be broken?
I'm asking because I just made a fix for our web server app, it now uses UTF-8 and correctly handles string lengths and also Left/Mid/Right/InStr (it is not written in Java, instead in C++).
I wonder why Java strings can't do the same thing and automatically return correct number of characters instead of 16-bit words? String class could have an internal counter for characters in addition to 16-bit words. It would be slower but it would work correctly.
Also I think that Java should have used 8-bit UTF-8 for characters instead of 16-bit UTF-16, it would only take the half of the memory.
Posted by: fuerte on March 28, 2005 at 01:16 PM
|
http://weblogs.java.net/blog/tomwhite/archive/2005/03/counting_charac.html
|
crawl-002
|
refinedweb
| 969
| 52.6
|
This collection of hacks discusses some of the most important XML vocabularies and the technologies that support them. First off, we introduce XML namespaces [Hack #59] and RDDL [Hack #60], which helps identify resources associated with a namespace. Next we create an XHTML 1.0 document [Hack #61] . This is followed by a brief exploration of DocBook [Hack #62] .
Next, we get a handle on SOAP [Hack #63] and some of its close relatives. Then it's on to a fun application of RDF called FOAF [Hack #64] . We talk about the OpenOffice file format [Hack #65], and end this foray with some experimentation with SVG [Hack #9] and XForms [Hack #67] .
Example files discussed in this chapter (and all chapters) are available at.
|
http://etutorials.org/XML/xml+hacks/Chapter+4.+XML+Vocabularies/Hacks+59-67/
|
CC-MAIN-2018-30
|
refinedweb
| 124
| 74.59
|
the series so far we created the gameplay, bloom, and particle effects. In this final part, we will create a dynamic, warping background.
private class PointMass { public Vector3 Position; public Vector3 Velocity; public float InverseMass; private Vector3 acceleration; private float damping = 0.98f; public PointMass(Vector3 position, float invMass) { Position = position; InverseMass = invMass; } public void ApplyForce(Vector3 force) { acceleration += force * InverseMass; } public void IncreaseDamping(float factor) { damping *= factor; } public void Update() { Velocity += acceleration; Position += Velocity; acceleration = Vector3.Zero; if (Velocity.LengthSquared() < 0.001f * 0.001f) Velocity = Vector3.Zero; Velocity *= damping; damping =. This is used roughly as friction or air resistance. It gradually slows the mass down. if the velocity is very small, and if so we set it to zero. This can be important to performance due to the nature of denormalized floating-point numbers.
(When floating-point numbers get very small, they use a special representation called a denormal number. This has the advantage of allowing float.
private struct Spring { public PointMass End1; public PointMass End2; public float TargetLength; public float Stiffness; public float Damping; public Spring(PointMass end1, PointMass end2, float stiffness, float damping) { End1 = end1; End2 = end2; Stiffness = stiffness; Damping = damping; TargetLength = Vector3.Distance(end1.Position, end2.Position) * 0.95f; } public void Update() { var x = End1.Position - End2.Position; float length = x.Length(); // these springs can only pull, not push if (length <= TargetLength) return; x = (x / length) * (length - TargetLength); var dv = End2.Velocity - End1.Velocity; var force = Stiffness * x - dv * Damping; End1.ApplyForce(-force); if.
Spring[] springs; PointMass[,] points; public Grid(Rectangle size, Vector2 spacing) { var springList = new List(); int numColumns = (int)(size.Width / spacing.X) + 1; int numRows = (int)(size.Height / spacing.Y) + 1; points = new PointMass[numColumns, numRows]; // these fixed points will be used to anchor the grid to fixed positions on the screen PointMass[,] fixedPoints = new PointMass[numColumns, numRows]; // create the point masses int column = 0, row = 0; for (float y = size.Top; y <= size.Bottom; y += spacing.Y) { for (float x = size.Left; x <= size.Right; x += spacing.X) { points[column, row] = new PointMass(new Vector3(x, y, 0), 1); fixedPoints[column, row] = new PointMass(new Vector3(x, y, 0), 0); column++; } row++; column = 0; } // link the point masses with springs for (int y = 0; y < numRows; y++) for (int x = 0; x < numColumns; x++) { if (x == 0 || y == 0 || x == numColumns - 1 || y == numRows - 1) // anchor the border of the grid springList.Add(new Spring(fixedPoints[x, y], points[x, y], 0.1f, 0.1f)); else if (x % 3 == 0 && y % 3 == 0) // loosely anchor 1/9th of the point masses springList.Add(new Spring(fixedPoints[x, y], points[x, y], 0.002f, 0.02f)); const float stiffness = 0.28f; const float damping = 0.06f; if (x > 0) springList.Add(new Spring(points[x - 1, y], points[x, y], stiffness, damping)); if (y > 0) springList.Add(new Spring(points[x, y - 1], points[x, y], stiffness, damping)); } springs = springList.ToArray(); }
The first
for loop creates both regular masses and immovable masses at each intersection of the grid. We won't actually use all of the immovable masses, and the unused masses will simply be garbage collected sometime after the constructor ends. We could optimize by avoiding creating unnecessary objects, but since the grid is usually only created once, it won't make much difference...
Manipulating the Grid
In order for the grid to move, we must update it each frame. This is very simple as we already did all the hard work in the
PointMass and
Spring classes.
public void Update() { foreach (var spring in springs) spring.Update(); foreach (var mass in points) mass.
public void ApplyDirectedForce(Vector3 force, Vector3 position, float radius) { foreach (var mass in points) if (Vector3.DistanceSquared(position, mass.Position) < radius * radius) mass.ApplyForce(10 * force / (10 + Vector3.Distance(position, mass.Position))); } public void ApplyImplosiveForce(float force, Vector3 position, float radius) { foreach (var mass in points) { float dist2 = Vector3.DistanceSquared(position, mass.Position); if (dist2 < radius * radius) { mass.ApplyForce(10 * force * (position - mass.Position) / (100 + dist2)); mass.IncreaseDamping(0.6f); } } } public void ApplyExplosiveForce(float force, Vector3 position, float radius) { foreach (var mass in points) { float dist2 = Vector3.DistanceSquared(position, mass.Position); if (dist2 < radius * radius) { mass.ApplyForce(100 * force * (mass.Position - position) / (10000 + dist2)); mass.IncreaseDamping(0.6f); } } }
We will use all three of these methods in Shape Blaster for different effects.
Rendering the Grid
We will draw the grid by drawing line segments between each neighbouring pair of points. First, we'll make an extension method on
SpriteBatch that allows us to draw line segments by taking a texture of a single pixel and stretching it into a line.
Open the
Art class and declare a texture for the pixel.
public static Texture2D Pixel { get; private set; }
You can set the pixel texture the same way we set up the other images, or you can simply add the following two lines to the
Art.Load() method.
Pixel = new Texture2D(Player.GraphicsDevice, 1, 1); Pixel.SetData(new[] { Color.White });
This simply creates a new 1x1px texture and sets the sole pixel to white. Now add the following method in the
Extensions class.
public static void DrawLine(this SpriteBatch spriteBatch, Vector2 start, Vector2 end, Color color, float thickness = 2f) { Vector2 delta = end - start; spriteBatch.Draw(Art.Pixel, start, null, color, delta.ToAngle(), new Vector2(0, 0.5f), new Vector2(delta.Length(), thickness), SpriteEffects.None, 0f); }.
public Vector2 ToVec2(Vector3 v) { // do a perspective projection float factor = (v.Z + 2000) / 2000; return (new Vector2(v.X, v.Y) - screenSize / 2f) * factor + screenSize / 2; }
This transform will give the grid a perspective view where far away points appear closer together on the screen. Now we can draw the grid by iterating through the rows and columns and drawing lines between them.
public void Draw(SpriteBatch spriteBatch) { int width = points.GetLength(0); int height = points.GetLength(1); Color color = new Color(30, 30, 139, 85); // dark blue for (int y = 1; y < height; y++) { for (int x = 1; x < width; x++) { Vector2 left = new Vector2(), up = new Vector2(); Vector2 p = ToVec2(points[x, y].Position); if (x > 1) { left = ToVec2(points[x - 1, y].Position); float thickness = y % 3 == 1 ? 3f : 1f; spriteBatch.DrawLine(left, p, color, thickness); } if (y > 1) { up = ToVec2(points[x, y - 1].Position); float thickness = x % 3 == 1 ? 3f : 1f; spriteBatch.DrawLine
Draw() method.
if (x > 1 && y > 1) { Vector2 upLeft = ToVec2(points[x - 1, y - 1].Position); spriteBatch.DrawLine(0.5f * (upLeft + up), 0.5f * (left + p), color, 1f); // vertical line spriteBatch.DrawLine(0.5f * (upLeft + left), 0.5f * (up + p), color, 1f); // horizontal line }
The second improvement is to perform interpolation on our straight line segments to make them into smoother curves. XNA provides the handy
Vector2.CatmullRom() method which performs Catmull-Rom interpolation. You pass the method four sequential points on a curved line, and it will return points along a smooth curve between the second and third points you provided.
The fifth argument to
Vector2
Draw() method for adding Catmull-Rom interpolation for the horizontal lines is shown below.
left = ToVec2(points[x - 1, y].Position); float thickness = y % 3 == 1 ? 3f : 1f; // use Catmull-Rom interpolation to help smooth bends in the grid int clampedX = Math.Min(x + 1, width - 1); Vector2 mid = Vector2.CatmullRom(ToVec2(points[x - 2, y].Position), left, p, ToVec2(points[clampedX, y].Position), 0.5f); // If the grid is very straight here, draw a single straight line. Otherwise, draw lines to our // new interpolated midpoint if (Vector2.DistanceSquared(mid, (left + p) / 2) > 1) { spriteBatch.DrawLine(left, mid, color, thickness); spriteBatch.DrawLine(mid, p, color, thickness); } else spriteBatch.DrawLine.Initialize() method. We'll create a grid with roughly 1600 points like so.
const int maxGridPoints = 1600; Vector2 gridSpacing = new Vector2((float)Math.Sqrt(Viewport.Width * Viewport.Height / maxGridPoints)); Grid = new Grid(Viewport.Bounds, gridSpacing);
Then we call
Grid.Update() and
Grid.Draw() from the
Update() and
Draw() methods in
GameRoot. This will allow us to see the grid when we run the game. However, we still need to make various game objects interact with the grid.
Bullets will repel the grid. We already made a method to do this called
ApplyExplosiveForce(). Add the following line to the
Bullet.Update() method.
GameRoot.Grid.ApplyExplosiveForce(0.5f * Velocity.Length(), Position, 80);
This will make bullets repel the grid proportionally to their speed. That was pretty easy.
Now let's work on black holes. Add this line to
BlackHole.Update().
GameRoot.Grid.ApplyImplosiveForce((float)Math.Sin(sprayAngle / 2) * 10 + 20, Position, 200); (IsDead) { if (--framesUntilRespawn == 0) GameRoot.Grid.ApplyDirectedForce(new Vector3(0, 0, 5000), new Vector3(Position, 0), 50); return; } scores table.
- Add some powerups such as a shield or bombs. For bonus points, get creative with your powerups. You can make powerups that manipulate gravity, alter time, or grow like organisms. You can attach a giant, physics-based wrecking ball to the ship to smash enemies. Experiment to find powerups!
|
https://gamedevelopment.tutsplus.com/tutorials/make-a-neon-vector-shooter-in-xna-the-warping-grid--gamedev-9904?ec_unit=translation-info-language
|
CC-MAIN-2022-33
|
refinedweb
| 1,490
| 60.92
|
#include <sys/stream.h> mblk_t *allocb(size_t size, uint_t pri);
Architecture independent level 1 (DDI/DKI).
The allocb() function tries to allocate a STREAMS message block. Buffer allocation fails only when the system is out of memory. If no buffer is available, the bufcall(9F) function can help a module recover from an allocation failure.
A STREAMS message block is composed of three structures. The first structure is a message block (mblk_t). See msgb(9S). The mblk_t structure points to a data block structure (dblk_t). See datab(9S). Together these two structures describe the message type (if applicable) and the size and location of the third structure, the data buffer. The data buffer contains the data for this message block. The allocated data buffer is at least double-word aligned, so it can hold any C data structure.
The fields in the mblk_t structure are initialized as follows:
set to NULL
points to the beginning of the data buffer
points to the beginning of the data buffer
points to the dblk_t structure
The fields in the dblk_t structure are initialized as follows:
points to the first byte of the data buffer
points to the last byte + 1 of the buffer
set to M_DATA
The following figure identifies the data structure members that are affected when a message block is allocated.
The number of bytes in the message block.
Priority of the request (no longer used).
Upon success, allocb() returns a pointer to the allocated message block of type M_DATA. On failure, allocb() returns a NULL pointer.
The allocb() function can be called from user, interrupt, or kernel context.
Given a pointer to a queue (q) and an error number (err), the send_error() routine sends an M_ERROR type message to the stream head.
If a message cannot be allocated, NULL is returned, indicating an allocation failure (line 8). Otherwise, the message type is set to M_ERROR (line 10). Line 11 increments the write pointer (bp->b_wptr) by the size (one byte) of the data in the message.
A message must be sent up the read side of the stream to arrive at the stream head. To determine whether q points to a read queue or to a write queue, the q->q_flag member is tested to see if QREADR is set (line 13). If it is not set, q points to a write queue, and in line 14 the RD(9F) function is used to find the corresponding read queue. In line 15, the putnext(9F) function is used to send the message upstream, returning 1 if successful.
1 send_error(q,err) 2 queue_t *q; 3 unsigned char err; 4 { 5 mblk_t *bp; 6 7 if ((bp = allocb(1, BPRI_HI)) == NULL) /* allocate msg. block */ 8 return(0); 9 10 bp->b_datap->db_type = M_ERROR; /* set msg type to M_ERROR */ 11 *bp->b_wptr++ = err; /* increment write pointer */ 12 13 if (!(q->q_flag & QREADR)) /* if not read queue */ 14 q = RD(q); /* get read queue */ 15 putnext(q,bp); /* send message upstream */ 16 return(1); 17 }
RD(9F), bufcall(9F), esballoc(9F), esbbcall(9F), putnext(9F), testb(9F), datab(9S), msgb(9S)
Writing Device Drivers for Oracle Solaris 11.2
STREAMS Programming Guide
The pri argument is no longer used, but is retained for compatibility with existing drivers.
|
http://docs.oracle.com/cd/E36784_01/html/E36886/allocb-9f.html
|
CC-MAIN-2016-36
|
refinedweb
| 544
| 61.36
|
I really dont know what they mean at
char canDrive = (fuelLe BLABLABLABLABLABLABLABLA
public class Ternary {
public static void main(String[] args) {
int fuelLevel = 3;
char canDrive = (fuelLevel > 0) ? 'Y' : 'N';
System.out.println(canDrive);
}
}
Yes, i know the answer but i dont know what it means.
Well scrap that i already know it now
The fuel level is set to 3Now,char canDrive = (fuelLevel > 0) ? 'Y' : 'N';This can be read as if fuelLevel is greater than 0 the 'Y' ( canDrive the vehicle) it will return Y else 'N' (cant drive) it will return N
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
|
https://discuss.codecademy.com/t/explain-this-code/71438
|
CC-MAIN-2017-22
|
refinedweb
| 112
| 70.43
|
I am making a GUI in python using Tkinter and have had some performance issues when packing many widgets onto the screen, for example packing a 50x50 grid of buttons takes a few seconds.
It seems to be the process of drawing (or arranging?) the widgets onto the screen which takes the time. I have tried using both the grid and place geometry managers.
I am wondering if using multiprocessing might speed this up? I would welcome any other suggestions for any way in which this could be significantly sped up.
import Tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
for i in range(50):
for j in range(50):
widget = tk.Frame(frame, bd=2, relief='raised', height=10, width=10)
widget.grid(row=i, column=j) # using place is barely quicker
tk.Button(root, text='pack', command=frame.pack).pack()
root.mainloop()
As suggested in the comments, the best solution did end up being to use a canvas and draw onto it, rather than to pack so many widgets, which seems to have absolute limitations on its speed.
I used the built-in buttons by effectively taking a screenshot to create images of the unclicked and clicked states. Suppose the image files are stored as
im_up.png and
im_down.png, then the code below illustrates the canvas solution.
import Tkinter as tk # Uses Python Imaging Library. from PIL import Image as ImagePIL, ImageTk root = tk.Tk() canvas = tk.Canvas(root, height=500, width=500, highlightthickness=0) canvas.pack() images = dict() for name in ['up', 'down']: im = ImagePIL.open('im_{}.png'.format(name)) # Resize the image to 10 pixels square. im = im.resize((10, 10), ImagePIL.ANTIALIAS) images[name] = ImageTk.PhotoImage(im, name=name) def set_cell_image(coord, image): # Get position of centre of cell. x, y = ((p + 0.5) * 10 for p in coord) canvas.create_image(x, y, image=image) for i in range(50): for j in range(50): set_cell_image((i, j), images['up']) def click(event): coord = tuple(getattr(event, p)/10 for p in ['x', 'y']) set_cell_image(coord, images['down']) canvas.bind('<Button-1>', click) root.mainloop()
|
https://codedump.io/share/8UGQiQ7jLuXd/1/tkinter-performance-when-packing-many-widgets
|
CC-MAIN-2018-26
|
refinedweb
| 353
| 61.63
|
Not so long ago I wrote an Introduction to MapKit and at the end of that article I was suggesting, as an improvement, the ability to obtain real location data from the web instead of hard-cording locations. In this article I want to introduce you to geocoding as a way to obtain information about geographical locations. Geocoding can be forward, when we obtain the geographical coordinates (latitude and longitude) from other location data such as postal addresses, or reverse, when we obtain the address of a location by having the latitude and longitude as inputs.
In this article, I want to show how to do geocoding using both Apple Maps and Google Maps. The major difference between the two is that for Apple Maps you do not need to access an external URL to get location data, while for Google Maps you do. I will start with Google Maps geocoding, so let’s create a new Xcode project first. In ViewController add two properties, one to hold the base URL for the Google Maps API, and a second one for your API key.
let baseUrl = "?" let apikey = "YOUR_API_KEY"
Next, let’s see how forward geocoding is done using Google Maps. For that let’s create a new method:
func getLatLngForZip(zipCode: String) { let url = NSURL(string: "\(baseUrl)address=\(zipCode)&key=\(apikey)") let data = NSData(contentsOfURL: url!) let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary if let result = json["results"] as? NSArray { if let geometry = result[0]["geometry"] as? NSDictionary { if let location = geometry["location"] as? NSDictionary { let latitude = location["lat"] as! Float let longitude = location["lng"] as! Float print("\n\(latitude), \(longitude)") } } } }
This method looks pretty straightforward. First it constructs a URL using the base URL, a zip code (provided as input argument), and the API key, then it serializes the data it finds at this URL into JSON feed, and finally it parses the JSON response to obtain the latitude and longitude we were looking for. Now let’s call this method in viewDidLoad():
getLatLngForZip("95014")
If you run the project now, you will see the following output in the console:
37.3132, -122.072
It worked! Next, let’s write a method for reverse geocoding using Google Maps:
func getAddressForLatLng(latitude: String, longitude: String) { let url = NSURL(string: "\(baseUrl)latlng=\(latitude),\(longitude)&key=\(apikey)") let data = NSData(contentsOfURL: url!) let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary if let result = json["results"] as? NSArray { if let address = result[0]["address_components"] as? NSArray { let number = address[0]["short_name"] as! String let street = address[1]["short_name"] as! String let city = address[2]["short_name"] as! String let state = address[4]["short_name"] as! String let zip = address[6]["short_name"] as! String print("\n\(number) \(street), \(city), \(state) \(zip)") } } }
This method is pretty similar to the first one. The only thing we changed is we provided the latitude and longitude as inputs to get the address information. Let’s call this method in viewDidLoad():
getAddressForLatLng("37.331", longitude: "-122.031")
Run the project and you should see the following output at the console:
1 Infinite Loop, Cupertino, CA 95014
This is great! We were able to get the exact location of Apple’s headquarters just by using the latitude and longitude. Ok, it’s time to move on to using Apple Maps now and see how that works. First, let’s import what we need:
import CoreLocation import AddressBookUI
Then, let’s write a method for forward geocoding using Apple Maps:
func forwardGeocoding(address: String) { CLGeocoder().geocodeAddressString(address, completionHandler: { (placemarks, error) in if error != nil { print(error) return } if placemarks?.count > 0 { let placemark = placemarks?[0] let location = placemark?.location let coordinate = location?.coordinate print("\nlat: \(coordinate!.latitude), long: \(coordinate!.longitude)") if placemark?.areasOfInterest?.count > 0 { let areaOfInterest = placemark!.areasOfInterest![0] print(areaOfInterest) } else { print("No area of interest found.") } } }) }
Let’s look at what this method does. First, it uses the CLGeocoder class from the CoreLocation framework to geocode an address we provide as input. In the method’s completion handler we parse the response and see what placemark objects we found. We are particularly interested in the first one found, if there are more than one. Then we get the location coordinates and any areas of interest - as properties of the placemark. Now let’s call this method in viewDidLoad():
forwardGeocoding("1 Infinite Loop")
If you run the app now, you will see the data you would expect:
lat: 37.3316851, long: -122.0300674 Apple Inc.
Now let’s write a method for reverse geocoding using Apple Maps:
func reverseGeocoding(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let location = CLLocation(latitude: latitude, longitude: longitude) CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in if error != nil { print(error) return } else if placemarks?.count > 0 { let pm = placemarks![0] let address = ABCreateStringWithAddressDictionary(pm.addressDictionary!, false) print("\n\(address)") if pm.areasOfInterest?.count > 0 { let areaOfInterest = pm.areasOfInterest?[0] print(areaOfInterest!) } else { print("No area of interest found.") } } }) }
The only detail we need to pay attention to in this method is the ABCreateStringWithAddressDictionary class from the AddressBookUI framework. This class does the address parsing for us which is really convenient as we do not need to care for any of the location fields, if we just want to see the entire address. Let’s also call this method in viewDidLoad():
reverseGeocoding(37.3316851, longitude: -122.0300674)
Run the app and you will see this nicely formatted output in the console:
1 Infinite Loop Cupertino CA 95014 United States Apple Inc.
You can read more about Apple Geocoding as well as Google Geocoding. As a next step, you could take this information and place pins on a map view, for example, and show areas of interest. You could also implement a search feature for finding addresses while you’re typing. You could also implement an autocompletion feature while at it. There are many opportunities you could think of.
Until next time!
|
http://mhorga.org/2015/08/14/geocoding-in-ios.html
|
CC-MAIN-2018-26
|
refinedweb
| 990
| 50.73
|
Six Python Tips for Beginners
Six Python Tips for Beginners
Code in Python like a pro.
Join the DZone community and get the full member experience.Join For Free
Python is one of the easiest programming languages to learn. The syntax is close to English. Beginners generally encounter only a few surprises, such as forced indentation and the use of
self in methods.
At some point, everyone starts reading, copying, and editing other people’s code. That’s where the confusion starts.
I'll explain five Python concepts that will help beginners to modify code written by other authors. These tips were compiled by observing problems novice Python developers encountered in workshop-style training as well as analyzing online discussions that took place in a free and open development community focused on the usage of APIs, image processing, and metadata (text) processing for the RICOH THETA camera. The typical person has intermediate programming experience with Java, C, JavaScript, or bash, but is still a Python novice.
They can write their own Python code to get a job done, but have problems reading the code contributed by other people.
Here are five things that helped some of these people better understand Python.
1. *args and **kwargs Are Function Arguments
If you look at Python modules or even documentation for the module, you’re likely to see
*args and
**kwargs. They look and act vaguely like a pointer in C. They are not.
*args is simply a list of arguments sent to a function.
**kwargs is a dictionary of keyword arguments.
*args example:
def add_it(*args): for num in args: print(num) add_it(3, 4, 5, 6)
Output:
$ python dzone.py 3 4 5 6
**kwargs example:
def fish_counter(**kwargs): print(kwargs) fish_counter(salmon=10, trout=30, smelt=10, bluegill=52)
Output:
$ python dzone.py {'bluegill': 52, 'smelt': 10, 'salmon': 10, 'trout': 30}
Runnable code for the
*args and
**kwargs examples is available here in the file
args_example.py .
2. List Comprehensions Are For Loop Shortcuts
list compressions are a short way to return a list. In the snippet, the for loop is
for number in args.
The expression that is normally inside the loop is
num **2 , which returns the square of the arguments.
def square_it(*args): return [num **2 for num in args] print(square_it(3, 4, 5, 6))
Output:
$ python dzone.py [9, 16, 25, 36]
You can tack on a filter to the end of the list comprehension to filter out inputs. For example, to only square the even numbers, filter it with this:
def square_it(*args): return [num **2 for num in args if num %2 == 0] print(square_it(3, 4, 5, 6))
Output:
$ python dzone.py [16, 36]
The list comprehension does not add any special feature over the
for loop. People use list comprehensions because they are shorter and can make code easier to read once you get accustomed to the syntax. Some people may overuse list comprehensions and make code more difficult to read. Be careful of this, as convoluted a list comprehension with multiple nesting is not best practice.
If you're just getting started with Python and see a
for loop all in one line, you can search on the Internet for list comprehension and review the syntax of the three components:
- Expression.
- For loop.
- Filter.
3. F Strings Can Replace .format()
Python is wonderful for string manipulation. You'll probably see at least 3 or 4 techniques to insert variables into strings. Most are clunky. One is cool.
String Concatenation
Long ago, you may have inserted variables into a string with code similar to this:
animal = "dogs" population = 3 city = "Palo Alto" print("There are " + str(population) + " " + animal + " in " + city + ".")
Output:
$ python dzone.py There are 3 dogs in Palo Alto.
This is difficult to read and easy to make errors. Even with syntax highlighting, it's easy to miss a space.
String Substitution
String substition can help to reduce errors.
print('String substitution format example') population = 3 animal = 'dogs' city = 'Palo Alto' my_string = 'There are %s %s in %s'%(population, animal, city) print(my_string)
Output
String substitution format example There are 3 dogs in Palo Alto
An online example of using string substitution is available here in the file
format_example.py
String Format
A better method is to use
.format() and make strings like this:
animal = "dogs" population = 3 city = "Palo Alto" print("There are {} {} in {}".format(population, animal, city))
$ python dzone.py There are 3 dogs in Palo Alto
Although
.format is a big improvement over string concatenation, it is still a bit clunky.
F String
First, upgrade to Python 3.6 or 3.7. Now, you can use f strings.
print(f"There are {population} {animal} in {city}")
$ python3 dzone.py There are 3 dogs in Palo Alto
4. Lambda Functions Are Anonymous
Python lambda functions are shortcuts. Although they can be assigned to a variable, similar to a normal function, they are commonly used as an anonymous function using the syntax below.
print((lambda num1, num2: num1 + num2)(4,6))
Output:
$ python3 dzone.py 10
Like most of these Python shortcuts, the lambda function doesn't usually add new functionality. Though, it can reduce the code complexity once you get used to the syntax.
5. Decorator Functions Extend Python Functions
You'll likely see a decorator function used with an
@decorator_name above a function.
@time_decorator def cool_function: print("doing cool things")
The name of the decorator can be anything. For example, it would work with
@panda . You don't have to understand how to create your own decorator in order to use it. For example, let's look at the Django documentation for http decorators.
from django.views.decorators.http import require_http_methods @require_http_methods(["GET", "POST"]) def my_view(request): # I can assume now that only GET or POST requests make it this far # ... pass
The
import line allows you to use pre-built decorators. In this case, you just need to understand that the
@require_http_methods adds additional features to the function you created called,
my_view() .
Additional Tips
As I primarily discuss Python programming with a group of people focused on a specific class of problems, I would love to get additional tips suitable for novice programmers that can help them interact with a wider developer community.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/5-python-tips-for-beginners
|
CC-MAIN-2020-24
|
refinedweb
| 1,068
| 65.01
|
Difference between revisions of "Release notes/0.41/fr"
Revision as of 11:19, 17 June 2016
Contents
Inkscape 0.41
En bref
Inkscape 0.41 is intended to provide a super-stable release prior to some major interface redesign work we will be undertaking for 0.42. It is thus at essense a bugfix release, yet there are several important new features and improvements:
- Color tracing, as well as multi-level grayscale tracing, is now possible with the built-in tracer.
- Clone tiler is an exciting new way to create patterns, tesselations, scatterings, or just about any regular or chaotic arrangements with clones of an original tile.
- Managing length units is cleaned up, extended, and centralized in the document units preference stored with a document. The user unit (px) of SVG is fully supported and made the default.
Apart from that, this version brings improved extensions usability, the Invert Selection command, more convenient layers selector, icon theming, progress with scripting, and more. Among the bugs fixed are some serious crashes, memory leaks, and mis-features; certain areas saw noticeable speedups.
Nouvelles fonctionnalités
- The new Multiple scanning mode is added to the Bitmap Tracing dialog (Path > Trace Bitmap). This mode traces a bitmap image repeatedly, assigning a distinct style to each resulting path and combining the paths into a group. What does this mean to the user? For one thing, Inkscape can now perform color tracing! There are three new options:
- Brightness: This separates the image into a given set of brightness levels, and scans the image for each one. This results is a fairly good grayscale vector representation of the original.
- Color: This is what everyone wants. This quantizes the original color bitmap into a reduced number of colors, scans each subset of pixels, and assembles the paths into a color vector rendition of the original bitmap. This has been tested extensively and produces very good results.
- Monochrome: This is the same as Color, but converts the resulting paths to grayscale. This is a convenience command, and is the same as if the user had used the Fill/Stroke dialog to do the same thing. The results are somewhat similar to Brightness; however, Brightness merely adds R, G, and B to get a brightness level, and throws color information away. That works well for areas of differing brightness, but fails for areas of similar brightness and different hue. Monochrome is grayscale, but its curves follow the edges of differing color.
- The new powerful Tile clones dialog (Edit > Tile Clones...) implements all 17 plane symmetry groups, allowing you to easily create all sorts of symmetric patterns, Escher-like tesselations, ornaments, etc. Since the pattern is made out of clones, you can always edit the original tile and the entire pattern is updated live. This feature puts Inkscape into competition with software such as the free Arabeske or commercial SymmetryWorks.
- Apart from selecting the symmetry, you can also vary the shift, scale, rotation, and opacity of the clones in the pattern, by setting the change rate per row and/or per column. With any of these parameters, you can alternate the sign of the increment for even/odd rows or columns, or randomize it to arbitrary degree. This produces "object fields" that can be distorted, skewed, slanted, "faded out," or "magnetized" (like iron particles in a magnetic field) in a multitude of ways. From a simple row of copies to complex effects reminding of fur, water ripples, starfields, or explosions, with various degrees of chaoticity - all this is now easy and automatic.
- To create a clone pattern, simply select something, set the number of rows and columns, and click Create. You can then change some parameters in the dialog and click Create again; this will remove any existing tiled clones of the selected object and recreate the pattern anew. Or, you can just remove the old pattern by clicking Remove. To protect a pattern from deletion by this dialog, group it or move it to another layer.
- Initially, a pattern is created based on the bounding box of the selected object. After the pattern is created, resizing the original tile does not move the clones away, so you can make the tiles overlap. Also, when the pattern is created, the current bbox of the original tile is remembered; later, if the "Use saved size and position of the tile" checkbox is on, the same bbox will be used when you click Create again, which means you can vary the pattern parameters without losing the overlapping of the tiles.
- It's best to use a group as the original object for tiling, because you can then enter this group (right-click, "Enter group") and draw inside it. Any changes or new objects added to the group will show in the pattern immediately.
- The new Invert Selection command (the `!' key) inverts selection (deselecting what was selected and selecting everything else) within the current layer. Both Invert Selection and Select All now have the "in all layers" variants that act across all visible and unlocked layers (Ctrl+Alt+A for Select All in All Layers, Alt+! for Invert Selection in All Layers).
- Ben Crowell contributed the
embed_raster_to_svg.plPerl script (in
share/extensions) which embeds all external raster images referenced from an SVG document into that document. Even though there's no Inkscape UI for it, this script is very useful for creating self-contained SVG documents for distribution.
Interface et utilisabilité
- Upon launch, Inkscape checks the availability of various external programs that are used by installed Inkscape extensions. If some are missing, you get a warning box, and the complete list of unavailable extensions is in
~/.inkscape/extension-errors.log. Check that file and install additional software if you find that e.g. some import/export formats do not work (most commonly PS/EPS import which currently requires Skencil and pstoedit to be installed).
- The quick layer selector in the statusbar now displays hidden layers grayed out and locked layers enclosed in []. This makes it much easier to see at a glance what is visible and unlocked in the document. The current layer is now marked by a bullet.
- Document units: now you can set the default units for each document in the Document Preferences dialog. The units are saved with the document, so you can make yourself a template with your preferred units. The default template now uses the
pxunit; two new templates,
default_mmand
default_pt, are added. The document units:
- apply to the rulers and the statusbar coordinates (previously unchangeable);
- are preselected in all unit menus (such as in the Selector controls bar);
- apply to the grid; now the grid lines are 1 document unit apart, unless you change that in the Document Preferences.
- The pixels (
px) unit is added to unit menus. This is what is called "user unit" in the SVG specification, and in SVG code it is written either with the
pxsuffix or (more often) without any suffix. Inkscape converts most dimensions to user units when writing them to SVG, and now you can use this unit via the GUI as well. Note however that the conversion ration from
pxto absolute length units may vary in different SVG renderers and different output media (e.g. Inkscape uses
px/pt = 0.8), so you should not mix
pxand absolute units in the same document. Normally, you will only need absolute units if your design is to be printed on paper.
- The base zoom of the display is changed by a factor of 1.25 so that now at 100% zoom, one
pxunit corresponds to one screen pixel (previously one
ptcorresponded to one screen pixel). This is a better match for other SVG renderers which also display
px1:1 at the default zoom. Unfortunately, this means that all old Inkscape SVG files with saved zoom will now open at 25% closer zoom (this is a one-time annoyance: once you resave the file by version 0.41, the zoom will be preserved again).
- On export, if you want one
pxto correspond to one bitmap pixel, use the export resolution of 90 dpi. This resolution is now the default.
- Finally, the document units in the default template are now
pxas well. We believe this is more convenient as the majority of our users work with screen graphics, not for print.
- Icon.
- In Selector, the statusbar now reports not only the number of selected objects but also the number of layers in which they are selected and, if there's only one, the name of the selection layer.
- Backspace now works as well as Del for deleting objects or nodes.
- The page background color is now shown across the entire canvas, not in the framed page only as before.
- Pattern editing handles are easier to remember and to tell apart from shape handles: pattern move handle is a cross, rotate handle a circle, and scale handle a square.
Documentation, traductions, exemples
- Translation code was set up to properly include localized plural support, letting languages that have more than one plural from to operate correctly.
- Added French translation of "Keys and Mouse" chart.
- Added Slovenian translation of "Calligraphy Tutorial".
- Added Slovenian translation of "Shapes Tutorial".
- Added several new tips to the "Tips and tricks" tutorial.
- Three new example files are added, demonstrating various patterns created with the Tile Clones feature.
- The following translations were updated since 0.40: Catalan, French, German, Hungarian, Italian, Norwegian Nynorsk, Serbian, Slovenian, Spanish, Ukrainian.
Corrections de bogues notables
- Long freezes that happened on Windows and less frequently on Linux during opening files, typing text, ungrouping, etc. were tracked down to a bug in the boehm garbage collector library. You'll now need version 6.4 of boehm gc which has this bug fixed. Static RPMs and Windows builds at our site use the version 6.4.
- Numerous bugfixes were done to handling non-ASCII file paths, both on Windows and on Linux.
- The crash upon releasing a shape handle, which happened on FreeBSD and some versions of Windows, is fixed.
- Using GTK Input Methods for typing text, such as Chinese or Korean, used to crash or misbehave; now fixed.
- Hidden objects are now properly hidden on export and in print.
- A bad memory leak is stopped in the pattern fill code.
- The counterintuitive 90 degrees rotation of PS/EPS output is eliminated; now the page is rotated into landscape orientation only if the width of the drawing exceeds printable page width. Later a GUI facility for controlling page orientation will be added.
- The size of the imported bitmaps was wrong by a factor of 0.8, now fixed.
- Copying from or pasting into transformed groups now preserves the visible transform of the objects, and pasting style preserves the visible font size and stroke width regardless of source and target transforms.
- Pasting objects copied from different layers now correctly preserves their z-order.
- Switching units in the Stroke style tab was broken when more than one object is selected.
- Markers were lost on export to plain SVG due to missing
overflowproperty.
- Most paper sizes in Document Properties were slightly off; now the list is cross-checked and expanded.
- Inkscape SVG documents no longer include DOCTYPE declaration with an URI of an SVG DTD; this DTD would not be able to validate our documents anyway (due to extension elements), and was just useless.
- In node tool, pattern editing handles are now displayed for paths too (previously only for shapes).
- Many small CSS conformance issues are addressed.
- Significant speedups achieved in some operations, notably document loading (the difference may be more than 2x for large documents).
En interne
- Transforming a text object now embeds the scaling component of the transform into the text's font size(s). This means that after a uniform 2x scale of a text with
font-size: 10pt, you get a 20pt text, not 10pt text with a
transform=attribute as before. However, so far this works only for uniform scaling; after scaling a text non-uniformly, its visible letter height may not correspond to its
font-size.
- The last remaining pixmap icons were eliminated. Now all icons used by Inkscape are SVG.
- All the manual
xmlnsdeclarations are removed from the code; instead, they are now generated automatically and inserted into the output document on save.
- All of SPRepr's data fields are made private, direct accesses are replaced with calls to the appropriate accessor functions.
Problèmes connus
- Markers do not take the color of the stroke they are attached to.
- Neither markers nor dash patterns survive the Stroke to Path command.
- Windows version still cannot use external binaries for extensions (such as AI import).
- In Hebrew text, placement is wrong for any final (leftmost) character in the string (this was also broken in 0.40).
- Inkscape does not read external DTD subsets referenced from SVG files. Normally this is not a problem, but if a file relies on an external subset for namespace declarations (e.g. for the XLink namespace), this will fail.
- To save in SVGZ format on windows,
gzipexecutable must be locatable in the path. Download it e.g. from. The extension dependancy is
gzip, not
gzip.exe, so the file will need renaming.
- The Export Bitmap dialog cannot save to paths with non-Latin characters in it.
Versions précédentes
-
|
https://wiki.inkscape.org/wiki/index.php?title=Release_notes/0.41/fr&diff=100151&oldid=prev&printable=yes
|
CC-MAIN-2020-45
|
refinedweb
| 2,214
| 62.98
|
TODO: The RNG mechanics described here might not be accurately described.$03003890 and $03003894 (4-byte Little Endian) are R1 and R2.
x = R1 + 0x02cbbc71 y = R2 x = x ^ y y = (y rotated left 3 bits) + 0x0632d80f y = y ^ x R1 = x R2 = y value = (R1 - R2) % N rand(value) static unsigned Seed1; static unsigned Seed2; unsigned _rand(unsigned long VALUE) { Seed1 = (Seed1 + 46906481) ^ Seed2; Seed2 = Seed1 ^ ( Seed2<<3) | (Seed2 >> 29 + 103995407); return (Seed1 - Seed2) % VALUE; }
TODO: Research and make a list here.
RAM Watch (USA), courtesy of Bonecrusher1022. Some but not all addresses included in it work for the JP version.
|
http://tasvideos.org/GameResources/GBx/DragonBallZTheLegacyOfGoku2.html
|
CC-MAIN-2018-05
|
refinedweb
| 102
| 68.7
|
I found this site while looking for any help to answer my issues with my program. I currently am a student at University of Phoenix, and this is my first programming class in C. Our teacher strongly encourages team and class cooperation so that our programs work. I have asked for help from my classmates, and no one has responded. So I am using my teachers advice and finding someone, anyone to help me.
My program is supposed to do validity checks and I wanted mine to also prompt the user to re-enter the subtotal if a charcater was entered instead of a digit. Another thing I noticed is I have to hit the enter key twice before the rest of my program runs. Cannot figure that one out. Below is my problem program. Any help at this point would be greatly appreciated.
Code:
/* Kudler Food Tax Calculator */
//by TDankert
//July 30, 2007
#include <stdio.h>
#include <ctype.h>
main()
{
//Variables Defined
float fSubtotal, fDelmar, fEncinitas, fLajolla, fCheck;
char cResponse;
fSubtotal=0;
fCheck=0;
cResponse = '\0';
//Taxrate Defined
fDelmar=.0725;
fEncinitas=.075;
fLajolla=.0775;
//User Requirements
printf("\nWelcome to Kudler Fine Foods,\n\nWe hope you enjoyed your shopping experience.\n");
printf("\n\n\n\tPlease Enter your Subtotal: $");
scanf("%f, %c", &fSubtotal, &cResponse);
while (fSubtotal < fCheck){
printf("\nPlease Re-enter your Subtotal: $");
scanf("%f, %c", &fSubtotal, &cResponse );
}//end while loop
while (isdigit(cResponse)){
printf("\nPlease Re-enter your Subtotal: $");
scanf("%f, %c", &fSubtotal, &cResponse );
}//end while loop
//Del Mar Outputs
printf("\n\tTotal Sales Tax for Del Mar is $%.2f\n", fSubtotal*fDelmar);
printf("\tYour Del Mar Total is $%.2f\n", fSubtotal*fDelmar+fSubtotal);
//Encinitas Outputs
printf("\n\tTotal Sales Tax for Encinitas is $%.2f\n", fSubtotal*fEncinitas);
printf("\tYour Encinitas Total is $%.2f\n\n", fSubtotal*fEncinitas+fSubtotal);
//La Jolla Outputs
printf("\n\tTotal Sales Tax for La Jolla is $%.2f\n", fSubtotal*fLajolla);
printf("\tYour La Jolla Total is $%.2f\n\n", fSubtotal*fLajolla+fSubtotal);
//Ending Outputs
printf("\n\nThank You for Shopping Kudler Fine Foods.\n");
printf("\n\tHave a Nice Day!");
getch();
}//End Tax Calculator
|
http://cboard.cprogramming.com/c-programming/92192-help-character-validity-check-printable-thread.html
|
CC-MAIN-2015-27
|
refinedweb
| 351
| 58.38
|
Opened 6 years ago
Closed 6 years ago
#8027 closed Bugs (fixed)
thread library fails to compile with Visual Studio 2003
Description
The thread library fails to build with VS2003. I've tried both boost-1.53.0 and the trunk from SVN. Prior to this, I had successfully compiled boost-1.49.0, so it's something that changed after that. I know the compiler is ancient, but sadly I can't use a newer one.
I'm building it with the command: bjam toolset=msvc-7.1 variant=release thread
An example error log:
compile-c-c++ bin.v2\libs\thread\build\msvc-7.1\release\debug-store-database\debug-symbols-on\link-static\pch-off\threading-multi\win32\thread.obj thread.cpp boost\thread\future.hpp(354) : warning C4913: user defined binary operator ',' exists but no overload could convert all operands, default built-in binary operator ',' used boost\thread\future.hpp(1394) : error C2951: template declarations are only permitted at global or namespace scope
boost\thread\future.hpp(1469) : see reference to class template instantiation 'boost::unique_future<R>' being compiled
boost\thread\future.hpp(1400) : error C2955: 'boost::unique_future' : use of class template requires template argument list
boost\thread\future.hpp(1469) : see declaration of 'boost::unique_future'
boost\thread\future.hpp(1400) : error C2146: syntax error : missing ')' before identifier 'a_future' boost\thread\future.hpp(1400) : error C2146: syntax error : missing ';' before identifier 'a_future' boost\thread\future.hpp(1400) : error C2377: 'boost::unique_future<R>::future_ptr' : redefinition; typedef cannot be overloaded with any other symbol
boost\thread\future.hpp(1375) : see declaration of 'boost::unique_future<R>::future_ptr'
boost\thread\future.hpp(1400) : error C2059: syntax error : ')' boost\thread\future.hpp(1401) : error C2065: 'a_future' : undeclared identifier boost\thread\future.hpp(1402) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Change History (8)
comment:1 Changed 6 years ago by
comment:2 Changed 6 years ago by
If I comment out those lines, it successfully compiles!
Thanks
comment:3 follow-up: 4 Changed 6 years ago by
Gald to see that this work for you. I will no make any change on the repository.
comment:4 Changed 6 years ago by
Gald to see that this work for you. I will no make any change on the repository.
Hello,
I'm not sure whether I understood the meaning of this posting, regarding changes for the next release of boost. I really would appreciate the code being fixed for MSVC .NET 2003 in the next release of boost. Thanks to this ticket here we were able to reproduce the fix and to build boost thread on MSVC2003 at all. I.e. we have a conditional compilation flag around the lines L1390-L1396 above.
before L1390: (file boost/thread/future.hpp, release 1_53_0)
#if (!defined _MSC_VER || _MSC_VER >= 1400) // _MSC_VER == 1400 on MSVC 2005
after L1396:
#endif // #if (!defined _MSC_VER || _MSC_VER >= 1400)
This should activate the code for compilers that don't define _MSC_VER (i.e. non-Microsoft compilers) and also for Microsoft compilers from MSVC 2005 and newer; MSVC 2003 then disregards the lines it does not understand syntactically. With this modification, thread.lib was built successfully on MSVC 2003, 2008, 2010, 2012, MinGW GCC 4.7.2 on x86 and x64. I didn't test MSVC 2005 (don't have it any longer) and I was too lazy to test with a MinGW GCC 4.8.0 preview. I don't know if there are any side effects if that functions are not declared as friends (MSVC 2003 only), but until now there didn't occur any problems in our application.
Best regards
Manfred
comment:5 Changed 6 years ago by
comment:6 Changed 6 years ago by
I will fix it soon.
It seems that the compiler doesn't like
I have no way to check it. Please could you try commenting these lines and make public all the needed members?
|
https://svn.boost.org/trac10/ticket/8027
|
CC-MAIN-2018-51
|
refinedweb
| 655
| 50.23
|
Handle security tokens in provider-hosted low-trust SharePoint Add-ins
Important
This article is entirely about the use of security tokens in the low-trust authorization system, not the high-trust system. For information about the use of tokens in the high-trust system, see Create and use access tokens in provider-hosted high-trust SharePoint Add-ins.
SharePoint Add-ins that use the low-trust authorization system to gain access to SharePoint data participate in an OAuthflow that involves the passing of security tokens (in JSON Web Token format) among SharePoint, Microsoft Azure Access Control Service (ACS), the remote components of the SharePoint Add-in, and, in some cases, the user's browser..
There are different flows depending on the design of the add-in, but all of them involve at least the following two types of tokens:
Access token. Included in each create, read, update, or delete (CRUD) request from the remote components of the add-in to SharePoint. SharePoint validates the token and serves the request.
Refresh token. Used to obtain a first access token in the Context Token flow, and to replace expiring access tokens in both the Context Token flow and the Authorization Code flow of the low-trust authorization system.
Depending on which OAuth flow the add-in is using, one or the other of the following is also part of the process:
Context token. Used, in the Context Token flow, to provide the remote component with a refresh token and with information that it needs to request an access token from Azure ACS.
Authorizaton code. Not a token, but an authorization code, unique to each pair of user and application. It is used in the Authorization Code flow to obtain a first access token and a refresh token.
Access tokens
In the low-trust authorization system, the access tokens are created by Azure ACS and sent to the remote component of your SharePoint Add-in. (When this article was written, ACS-issued access tokens for SharePoint had a life span of 12 hours, but that could change.) The main things that the code in your SharePoint Add-in needs to do are:
Request an access token from Azure ACS. Depending on which OAuth flow is being used, the add-in uses either an authorization code or information it extracts from a context token to make the request.
Include the token in every HTTP request to SharePoint. The token is added as an Authorization header to the request. The value of the header is the word "Bearer", followed by a space, followed by the base 64-encoded access token.
Optionally (but recommended), cache the access token for reuse on subsequent requests.
Optionally, forward the access token to back-end systems so they can directly access SharePoint.
These tasks must be done with server-side code. If you are using managed code, sample code for some of these tasks is in the SharePointContext.cs (or .vb) and TokenHelper.cs (or .vb) files that are part of Microsoft Office Developer Tools for Visual Studio. For an example of PHP code that carries out some of these tasks, see Understanding and Using the SharePoint REST Interface.
Cache the access token
Depending on your SharePoint Add-in's architecture and the hosting platform, there are several ways to cache the access token on the server:
- In session state
- In application state
- In Windows Server AppFabric Caching or its equivalent in a non-Microsoft operating system
- In the Microsoft Azure Caching Service or its equivalent in a non-Microsoft cloud service
- In a database
- In a memcached system
Note
In most scenarios, you won't be able to use terms as simple as "AccessToken" as the caching key because your add-in must keep the tokens for different users and SharePoint farms/tenancies distinct. If your add-in uses the Context Token flow, there is special CacheKey provided by SharePoint that can be used to distinguish cached tokens. This section explains what the issues are and what to do when your application is not using the Context Token flow.
Caching the access token in session state is fine for most scenarios. If the remote web application is accessing other services that use OAuth (in addition to SharePoint) and it is caching the various access tokens in session state, be sure to use distinct cache keys for the tokens; for example, instead of "AccessToken", use "SharePoint_AccessToken", "Facebook_AccessToken", "SAP_Gateway_AccessToken", and so on. (If you are not using session state or some other caching that automatically separates each user's cache, you need to relativize your keys for users.)
If the application accesses more than one SharePoint farm or online tenancy, you can use the SharePoint domain as part of the application's primary caching key (
SharePoint<mydomain>.sharepoint.com_AccessToken) or use the farm/tenancy's realm (
SharePoint<realmGUID>_AccessToken), both of which can be read from the access token. (Your code needs to reverse the Base 64-encoding of the token to read it. In managed code, the TokenHelper.cs, or .vb, file has sample code for this purpose that uses classes from the Microsoft.IdentityModel.S2S.Tokens and System.IdentityModel.Tokens namespaces.) There is another option available when the application is using the Context Token flow as described in the next paragraph.
Scenarios may exist in which your application needs to cache the access token someplace that is available to the application across sessions or after a session ends. For example, the application may be designed to enable users to schedule actions to occur after the user has closed the application. If those actions include accessing SharePoint, the add-in needs to retrieve the access token. In this kind of scenario, your application must keep the access tokens of different users distinct.
If you are using the Context Token flow, a cache key string is provided for this purpose in the context token that SharePoint passes to the remote component of your SharePoint Add-in when the add-in is launched. For more information about this special cache key and how to use it, see Understand the cache key. You can also use this string for the scenario described earlier. The scheduling system has some means of storing configuration data that it needs, such as when the scheduled work executes and what it should do. Use this storage to hold the cache key for the access token.
If the cross-session cache you use is also shared by multiple applications, the cache keys have to be relativized to applications as well as to users and to SharePoint realms. The cache key that is provided in the context token is unique to applications as well as to users and SharePoint realms.
If your application is using the Authorization Code flow, there is no context token and, hence, no specially made cache key. In that scenario, you need to create your own system of keys for cached data that are relativized to one or more of the following depending on what potential name clashes might occur given the use cases of your application: the user, the SharePoint realm, and the application. You can use the claims inside the access token for this purpose; for example, the
nameId and the
aud (see the following tables). Your code can simply concatenate the strings or use them as seeds to create a unique hash that can serve as the cache key.
Finally, if your application makes both add-in-only and user+add-in calls to SharePoint, it will have two different access tokens, so you need distinct cache keys. After you have decided on a basic cache key, just append "_add-in-only" or "_add-in+user" to it.
Warning
It is not a secure practice to store the access token in a cookie. It is usually a good practice to avoid having the access token pass through the browser.
Forward the access token to backend systems
A SharePoint Add-in may have backend servers that are not hosted in the same domain as the remote web application. When a backend server needs to perform CRUD operations on SharePoint, the add-in performs faster if these operations can go directly from the backend system to SharePoint. Fortunately, domain is only important when your application is getting an access token from ACS. After it has the token, it can forward it to the backend services, and they can call SharePoint by using it.
Code in these systems needs to handle expired access tokens and send a request for a new one back to the parent web application that is actually registered with ACS (see Handle expired access tokens). This technique should only be used for your application's own backend servers, not to external web services. Also, if you are using this technique, consider designing the backend services to use add-in-only calls whenever possible.
Handle expired access tokens
An access token expires after a few hours (twelve hours as of the time this article was written, but that can change). If the application is still accessing SharePoint after the access token expires, the first request to SharePoint after the expiration results in a 401 Unauthorized error. Your code has to handle this response.
Alternatively, the code can test the expiration time of the access token before it is used. Your code uses the refresh token to obtain another access token from ACS. In the Context Token flow, the refresh token is included in the context token that your add-in receives from SharePoint at the start of its first session with SharePoint. In the Authorization Code flow, it is passed to the application along with the first access token. Your code must cache it so it is available when needed. The refresh token lasts a few months and can be persisted in a cookie or in server-side storage. For more information, see Understand the handling and caching of refresh tokens.
Examples of access tokens for the low-trust authorization system
This section describes access tokens, with examples, and shows how they differ depending on the authorization policy that is being used.
User+add-in policy
The following is a decoded example of a user+add-in access token generated by ACS to be used for calls to SharePoint by using the user+add-in policy. White space has been added for readability. The token complies with the JSON Web Token protocol. The JavaScript Object Notation (JSON) object in the token is called the claim set (see Table 1 for details about the properties in the claim set).
Note that all the values must be lowercase. (User+add-in access tokens are the same in the Context Token flow and the Authorization Code flow.)
{ ": 1377549246, "exp": 1377592446, "nameid": "2303000085ff9abc", "actor": "964de6ad-6d28-4dc7-8e05-3acd8006e5c9@040f2415-e6e3-4480-96ce-26ef73275f73", "identityprovider": "urn:federation:microsoftonline" }
Table 1: ACS-issued user+add-in access token claims
Add-in-only policy
The following is a decoded example of an add-in-only access token generated by ACS to be used for calls to SharePoint using the add-in-only policy. White space has been added for readability. The token complies with the JSON Web Token protocol. See Table 2 for details about the properties in the claim set. (The add-in-only policy is not available for applications that use the Authorization Code flow, because they do not have an add-in manifest file and, thus, cannot request permission to use add-in-only calls.)
{ ":1403304705, "exp":1403347905, "nameid":"c76da14e-07fd-4638-a723-1ff60ce70d63@040f2415-e6e3-4480-96ce-26ef73275f73", "sub":"1d47ac31-498b-4988-8aac-85fc9bd2e1ce", "oid":"1d47ac31-498b-4988-8aac-85fc9bd2e1ce", "trustedfordelegation":"false", "identityprovider":"00000001-0000-0000-c000-000000000000@040f2415-e6e3-4480-96ce-26ef73275f73" }
Table 2: ACS-issued add-in-only access token claims
Context tokens
A context token is used only in the Context Token flow of the low-trust authorization system. When the SharePoint Add-in is launched in SharePoint, SharePoint requests that Azure ACS create a context token that SharePoint then passes on to the remote component of the SharePoint Add-in. The token is passed as a hidden form parameter called SPAppToken in a request from SharePoint for the start page of the remote component. The token is signed with a client secret known only to ACS and the SharePoint Add-in.
The context token includes a refresh token that the add-in uses, along with other information from the context token, to request an access token from ACS. (When this article was written, ACS-issued context tokens for SharePoint had a life span of 12 hours, but that could change.)
The main tasks for the code in the SharePoint Add-in are the following:
Use the client secret of the add-in to validate the context token.
Cache the context token, or extract and separately cache the refresh token and certain other items from inside it.
Use the refresh token and other information to request an access token from ACS (which is itself then cached).
Cache the CacheKey from the context token.
Important
The first two tasks must occur before the user goes to another page or refreshes the page, or the token is lost. For example, in an ASP.NET web forms application, consider doing those tasks in the Page_Load method (in a conditional code block that runs only when the request is not a postback). In an ASP.NET MVC application, consider doing these tasks in the default controller method.
If you are using managed code, sample code for some of these tasks is in the SharePointContext.cs (or .vb) and TokenHelper.cs (or .vb) files that are included in Microsoft Office Developer Tools for Visual Studio. You just need to make simple calls to the members of the TokenHelper class. For example, your code can do the first task with the following single line of code:
SharePointContextToken contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
For an example of how to do some of these tasks with PHP, see the sample SharePoint: Perform operations on SharePoint Document Library from PHP site.
Cache the context token or parts of it
You can cache a whole context token, or just the refresh token and certain other items that are inside it that your code uses to get access tokens, in either server-side or client-side storage. For simplicity, this article assumes that you cache the context token as a unit.
Important
We remind you one more time because it's really important: do not use client-side caching for the access token. It is safe to use it only for the context token.
You have the same server-side caching options as are listed earlier for the access token. Client-side options include a cookie and a hidden form field on an HTML page. Another option is to store the context token in the session cache, but store the CacheKey obtained from inside it on the client.
If your application accesses SharePoint after a session is ended, neither session-caching nor client-side caching is an option, because the refresh token must be available to the application in case the original access token has expired when the post-session work executes. In this scenario, you need a durable (cross-session) cache that is shared by multiple users and/or SharePoint realms and/or applications. So your code has to use cache keys that distinguish user, SharePoint realm, and/or application as explained earlier in Cache the access token.
You can use the special cache key that is inside the context token for this purpose, just as you used it for the access token (see the next section Understand the cache key).
Understand the cache key
The cache key is an opaque string that is unique to the combination of user, user name issuer, add-in, and SharePoint farm or SharePoint Online tenant. Before it is encrypted, it has the following form, where Realm is the GUID of the on-premises SharePoint farm or the SharePoint Online tenancy.
UserNameId + "," + UserNameIdIssuer + "," + ApplicationId + "," + Realm
The cache key does not contain site URL information. Each SharePoint Online tenant (or on-premises SharePoint farm) has a unique realm, so, the cache key is unique for each combination of user name, user name issuer, application, and farm. In the example context token, the encrypted cache key value is:
KQAIUpDUD0sm5Tr83U+jZGYVuPPCPu8BGwoWiAACqNw=
Because your application may be caching multiple items, such as both the access token and the context token in the same cache with the same cache key, consider using the cache key as a stem and either appending or prepending a specific string such as "AccessToken" or "ContextToken" to it as needed to form a complete cache key.
Another option is to create a class with properties for the various things you want to cache, and then cache an object of that type.
A third option, if you are using a database as a cache, is to use a table with a CacheKey column and additional columns for the cached items (AccessToken, ContextToken, etc.).
Your application does not have to use the same cache for everything it is caching, of course. A common pattern is to cache the access token in session cache, the context token (or the refresh token from inside it) in a database, and the CacheKey in a cookie.
Use the context token to get an access token
To get an access token, your application sends a request directly to ACS. The request includes three pieces of information that are extracted from the context token (and other information):
- The refresh token
- The application principal GUID of SharePoint
- The realm GUID of the SharePoint farm or SharePoint Online tenancy to which the add-in is seeking access
The TokenHelper.cs (or .vb) file has code that creates this request. For an example of PHP code that does this, see SharePoint: Perform operations on SharePoint Document Library from PHP site.
The application can get the realm of the SharePoint tenancy or farm at runtime as an alternative to parsing it from the context token. If you are using managed code, there is a
TokenHelper.GetRealmFromTargetUrl method to get the realm. Be sure to cache the value so that your code does not make another network call to get it again.
Get a new context token
If you need a new context token, typically because the refresh token (which is contained in context tokens) has expired, your code can get a new one by redirecting the browser to a special page in every SharePoint website, AppRedirect.aspx. Two query parameters have to be attached to the URL of this page:
client_id: The client ID of your SharePoint Add-in.
redirect_uri: The URI to which you want the browser redirected after the new context token is obtained. SharePoint will POST the context token to this URI. Typically, this is the same page, controller method, or web service method that requested the new context token. The value must be URL-encoded.
The following shows the structure of the URL:
https://<SharePointDomain> /_layouts/15/appredirect.aspx?client_id=<app_client_GUID> &redirect_uri=<URL-encoded_redirect_URI>
The following is an example of making the request in ASP.NET that uses the TokenHelper file:
Response.Redirect(TokenHelper.GetAppContextTokenRequestUrl(sharePointUrl, Server.UrlEncode(Request.Url.ToString())));
Example of a context token
The following is an example of a context token. The small JavaScript Object Notation (JSON) object at the top contains metadata about the token. These properties are the same as in access tokens (see earlier). The value of the alg property is the name of the algorithm that is used to generate the signature that ACS appends to the token. See Table 3 for details about the properties in the payload of the token. Note that all the values must be lowercase. (White space has been added for readability.)
{"typ":"JWT","alg":"HS256"} . { "aud":"a044e184-7de2-4d05-aacf-52118008c44e/fabrikam", "appctxsender":"00000003-0000-0ff1-ce00-000000000000@040f2415-e6e3-4480-96ce-26ef73275f73", ", "isbrowserhostedapp": "true" }
The
aud,
iss,
nbf, and
exp claims are exactly the same as in an access token described in Table 1.
The
appctxsender,
appctx,
CacheKey,
SecurityTokenServiceUri,
refreshtoken, and
isbrowserhostedapp claims are described in the following table.
Table 3. Context token claims and information
Use the context token to limit access to only SharePoint users
If you want to limit access to your remote component, such as a WCF service, to SharePoint users, your code can simply validate the context token in the HTTP Request. (If you are using managed code, you can just call
TokenHelper.ReadAndValidateContextToken()).
Your code can verify that the actor claim of the token starts with
00000003-0000-0ff1-ce00-000000000000, if you want to make sure that it is SharePoint (and not, for example, Exchange, Lync, or Workflow). If you want to do additional validation that requires a call back to SharePoint, such as limiting access to users with a certain role in SharePoint, you can cache the fact that you have done this validation for a particular user (by using the context token's CacheKey) so that you have to do this only once.
Refresh tokens
A refresh token is included in the context token that SharePoint posts to your web application when it is launched. The refresh token is an encrypted token that your SharePoint Add-in cannot unencrypt. Your code uses it, along with other information, to get a new access token when the current access token expires. It is also used to get the first access token in the Context Token flow. (When this article was written, ACS-issued refresh tokens for SharePoint had a life span of 6 months, but that could change.)
Because an access token lasts hours (currently 12) and an end user gets a new one each time he launches your SharePoint Add-in from SharePoint, you only need the refresh token in one of these scenarios:
Users have long running sessions with your add-in in which the add-in makes calls to SharePoint many hours (currently more than 12) after it is launched.
The add-in's design enables users to schedule the add-in to access SharePoint sometime after the session ends.
Both scenarios require your add-in to cache the refresh token, and the second scenario requires a server-side cache that is durable across sessions. Your caching options are the same as those for the access token and, in the Context Token flow, you can use the cache key in the context token. (In the Context Token flow, you usually just cache the context token. It contains the refresh token and other information that you need to get a new access token. In the Authorization Code flow, there is no context token, so you cache the refresh token itself.)
If you are caching the refresh token in a storage that persists across a specific user's sessions with your add-in, be sure to replace it with the newest refresh token. In both the cloud-hosted and Authorization Code flows, the user gets a new refresh token each time he or she launches the add-in.
If the refresh token is expired, a request to ACS for a new access token results in a 401 Unauthorized error. Your add-in should respond to this error by getting a new refresh token and using it to get a new access token. (Because the refresh token is encrypted, your code cannot check its expiration before using it.)
In the Context Token flow, your add-in gets a new refresh token by getting a new context token. In the Authorization Code flow, your add-in gets a new refresh token by restarting the flow. Specifically, your code should respond to the error by redirecting the user to the SharePoint OAuthAuthorize.aspx page as explained in Understand the OAuth flow for add-ins that request permissions on the fly.
Authorization codes
In the Authorization Code flow, the authorization process begins with an authorization code that ACS issues, at the request of SharePoint, and which SharePoint then passes to the remote application as a query parameter. The authorization code is unique to each pair of user and remote application. (When this article was written, ACS-issued authorization codes for SharePoint had a life span of 5 minutes, but that could change.)
The logic in your application must get the authorization code from the query parameter and use it in a request to ACS for an access token. If you are using managed code, sample code for creating the token is in the TokenHelper.cs (and .vb) file. Sample code for reading the query parameter is in Get sample code-behind for a page that accesses SharePoint. ACS invalidates the authorization code immediately after issuing the access token, so it can only be used once, and there is no point in caching it.
JWT time values
The
nbf and
exp claims are in the format specified by the JWT specification. They are written as the number of seconds since January 1, 1970. In C#, you can translate these values with the following code, where
jWTTimeStamp is the value from the token, such as
1335822895.
DateTime exp = new DateTime(1970,1,1).AddSeconds(jWTTimeStamp);
Troubleshooting token handling
The free Fiddler tool can be used to capture the HTTP Requests sent by the remote component of your add-in to SharePoint. There is a free extension to the tool that automatically decodes the tokens in the requests.
|
https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/handle-security-tokens-in-provider-hosted-low-trust-sharepoint-add-ins
|
CC-MAIN-2018-34
|
refinedweb
| 4,253
| 58.62
|
26 November 2007 10:40 [Source: ICIS news]
LONDON (ICIS news)--Brent crude on ICE Futures hit a new record high above $96/bbl due to persistent weakness in the US dollar and colder weather expected in the US.
?xml:namespace>
By 10:00 GMT, January Brent crude had hit a high of $96.56/bbl, a gain of $0.80/bbl over the Friday close of $95.76/bbl, before easing back to around $96.21/bbl.
At the same time, January NYMEX crude was trading around $98.80/bbl, having hit a high of $99.11/bbl, a gain of $0.93/bbl over the previous close.
Talks that OPEC could decide to increase output was offset by a weak US dollar as the markets expected the Federal Reserve to cut interest rates to support the weakness in the economy from the country’s housing crisis.
Moreover, expectations of colder weather in the northeast
|
http://www.icis.com/Articles/2007/11/26/9081564/brent-crude-hits-record-high-above-96bbl.html
|
CC-MAIN-2014-15
|
refinedweb
| 156
| 75.81
|
:
- Monitor the calls to your service across multiple servers with AppFabric Monitoring
- Eliminate the .svc extension from the URI by using routing
- Create custom Event Tracing for Windows (ETW) events that will be logged by AppFabric Monitoring
- Provide a simple HTML page for invoking the service with or without the .svc extension
Setup
To build and test an AppFabric WCF HTTP: }
- Build the solution>
Enable Routing
- Open web.config
- Enable ASP.NET Compatibility for WCF
1: <system.serviceModel>
2: <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
3: </system.serviceModel>
- Enable the UrlRouting module.>
- Add global.asax
- Add the following namespace directives
1: using System.Web.Routing;
2: using System.ServiceModel.Activation;
- Add code to the Application_Start method to register the route.
1: protected void Application_Start(object sender, EventArgs e)
2: {
3: RouteTable.Routes.Add(new ServiceRoute(
4: "SampleService", /* Replace SampleService with your service name */
5: new WebServiceHostFactory(),
6: typeof(SampleService))); /* Replace SampleService with your service name */
7: }
Verify with Development Server
- In the Solution Explorer window, right click on the generated HTM file for your service. For example SampleService.svc.htm and select View in Browser.
- The ASP.NET Development Server will start and your page will load in the browser.
- and select properties
- Go to the Web tab
- Check Use Local IIS Web Server and click Create Virtual Directory
- Save your project settings (Debugging will not save them)
- In the Solution Explorer window, right click on the generated HTM file for your service. For example SampleService.svc.htm and select View in Browser. The address should now be that of the IIS (“”) and not of the ASP.NET Development Server (“”).
- AppFabric. It groups calls by URI so calls without the .SVC extension look like a different service.
- Switch back to your browser, leave the text box empty (clear it if necessary) and click the link for service with the .svc extension and the link for the service without the .svc extension. This will generate a warning event.
- To see the monitoring for these activities switch back to the IIS Manager and refresh the AppFabric Dashboard.
- Click on the link in the WCF Call History for SampleService.svc and you will see events for the completed calls.
- To see specific events, right click on an entry for the SayHello operation and select View All Related Events.
- In the list of related events you will see the user defined event named SayHello. The payload of this event contains the message logged by the operation.
|
https://blogs.msdn.microsoft.com/rjacobs/2011/03/03/appfabric-wcf-http-service-template/
|
CC-MAIN-2017-22
|
refinedweb
| 409
| 50.33
|
Section 4.8 Expressions
In C, computations are represented as expressions. C provides a number of binary and unary arithmetic operators. Some of them are overloaded: The same symbol is used for different operand types. For example, the processor needs to perform different operations for adding two floating-point numbers than for adding two integers, but both are represented with the same symbol in C. The C compiler uses the types of the operands to determine which operation is used; the overloading is therefore resolved during the compilation.
For all types \(i \in \{\mathtt{int},\mathtt{long}\}\) and all numerical types \(f \in \{\mathtt{int},\mathtt{long},\mathtt{float},\mathtt{double}\}\text{,}\) C provides the following arithmetic operators:
Subsection 4.8.1 Implicit Type Conversions
If the types of an operators operands do not match, C performs a number of implicit conversions on the operands before applying the operator. Consider the following example:
int x; double d; ... d = d + x;
The addition operator is not defined for a
double and an
int (see Table 4.8.1). Following the hierarchy shown below, C converts the
int operand to a
double value.
int.
The implicit conversions adjust the operands to the least common operand type, where \(a\text{ "less than" }b \iff a \rightarrow^\ast b\text{.}\) Additionally, no operation is performed with operand types “less than”
int. The motivation for this choice is that an
int has usually the width of a machine word, for which the fastest operations of the processor are designed.
Remark 4.8.3.
When such conversions are applied, the compiler needs to emit machine code that transforms a bit sequence representing the
int into a bit sequence representing a
double of the same numerical value. For some types (like 64-bit
long to 64-bit
double), this conversion is not exact due to the
double's limited precision.
Subsection 4.8.2 L- and R-Evaluation of Expressions
In C (and derived imperative languages) there are two different ways used to evaluate expressions, depending on the position of the expression. Consider the assignment
x = x + 1;
In C, assignments are expressions, meaning that
= is just a binary operator. As a side effect (see Table 4.8.4), the operator stores the value resulting from the right-hand-side expression to the container whose address results from evaluating the expression of the left-hand side.
Consequently, the left operand of
= needs to be evaluated as an address, whereas the right one should yield a value. In our example, a subexpression with the variable name
x occurs on both sides of the operator. On the right-hand side, the subexpression
x is evaluated by reading the content of the container bound to
x. This evaluation to the container content is called R-evaluation. The resulting value is than incremented by
1 to compute the value of the right operand of
=. On the left-hand side,
x is evaluated as the address of the container bound to the variable
x. We call this L-evaluation, as it occurs on the left side of the assignment.
Every expression can be R-evaluated, but some cannot be L-evaluated. To be L-evaluable, an expression needs to refer to the address of a container. For example,
1 + 2 cannot be L-evaluated, whereas
x (where
x is a declared variable) can. We can statically decide whether an expression is L-evaluable. The compiler aborts the translation with an error message if it finds an expression that is not L-evaluable at a position where L-evaluation is required.
If an expression \(e\) is L-evaluable, R-evaluating \(e\) results in the content of the container referred to by the L-evaluation of \(e\text{.}\)
Subsection 4.8.3 Side Effects
A particular quirk of C is that evaluating expressions can have side effects. During expression evaluation, the contents of containers may be changed, the program can interact with the operating system (for example to print text on the screen, to send network packets, to read or write files, etc.), or the evaluation might even diverge (i.e. never terminate). Table 4.8.4 shows all C operators with side effects.
The assignment is an expression with side effects:
x = x + 1
The side effect is that the value evaluated from the right-hand side is written to the container referred to by the left-hand operand. The written value is also the value of the expression.
If an expression has more than one side effect, different evaluation orders might lead to different results. Consider the following example:
x = 5; y = (x = 2) * (++x);
The meaning of this program could be defined in several ways:
A non-deterministic semantics, meaning that both,
2and
3, would be correct results for the contents of
xafter the statements.
With a defined order in which the subexpressions are to be evaluated (as it is done in the programming language Java).
With no semantics at all (as it is done in C). The exact rules on when an expression with side effects has a semantics in C is complicated. As a rule of thumb, we can assume the evaluation of an expression to be undefined if it writes more than once into the same container. This does not extend to side effects in called functions:
int a(void) { printf("A"); return 1; } int b(void) { printf("B"); return 2; } int c(void) { return a() + b(); }
Every call to
creturns the value
3. However, either of
ABand
BAare correct outputs of the program. Since the rules for side effects in C are complicated and easy to misunderstand, it is best to reduce side effects to a minimum: At most one operator with side effects per expression.
Subsection 4.8.4 Lazy Evaluation
C has three operators whose operands are evaluated lazily rather than strictly. An operator is subject to strict evaluation, if all its operands are evaluated before its value is computed. If it is evaluated lazily, operands are only evaluated if they contribute to the result.
Subsection 4.8.5 Exercises
Checkpoint 4.8.6. Bit Operators.
The goal of this exercise is to learn how bit operations that you have encountered in the previous sections are realized in C.
Write a functions with the prototype
unsigned int f(unsigned int k, unsigned int n);
that flips the
k-th bit in
nif
kis between 0 and 31.
that sets the
k-th bit in
nif
kis between 0 and 31.
that clears the
k-th bit in
nif
kis between 0 and 31.
that rotates
nby
kto the left if
kis between 1 and 31.
that rotates
nby
kto the right if
kis between 1 and 31.
You may assume here that
unsigned int represents 32-bit unsigned integers.
unsigned int f1(unsigned int n, unsigned int k) { assert(k < 32); unsigned int a = 1 << k; return n ^ a; } unsigned int f2(unsigned int n, unsigned int k) { assert(k < 32); unsigned int a = 1 << k; return n | a; } unsigned int f3(unsigned int n, unsigned int k) { assert(k < 32); unsigned int a = (unsigned int)1 << k; return n & ~a; } unsigned int f4(unsigned int n, unsigned int k) { assert(0 < k && k < 32); unsigned int s = 32; return (n << k) | (n >> (s - k)); } unsigned int f5(unsigned int n, unsigned int k) { assert(0 < k && k < 32); unsigned int s = 32; return (n << (s - k)) | (n >> k); }
|
https://prog2.de/book/sec-c-expr.html
|
CC-MAIN-2022-33
|
refinedweb
| 1,244
| 51.48
|
Each Answer to this Q is separated by one/two green lines.
In this assignment I have completed all the problems except this one. I have to create a python script to solve an equation (screenshot).
Unfortunately, in my research all over the internet I cannot figure out how in the world to either convert ln to log or anything usable, or anything. The code I have written so far is below. I will also post the answer that our teacher says we should get.
import math p = 100 r = 0.06 / 12 FV = 4000 n = str(ln * ((1 + (FV * r) / p) / (ln * (1 + r)))) print ("Number of periods = " + str(n))
The answer I should get is 36.55539635919235
Any advice or help you have would be greatly appreciated!
Also, we are not using numpy. I already attempted that one.
Thanks!
math.log is the natural logarithm:
math.log(x[, base]) With one argument, return the natural logarithm of
x (to base e).
Your equation is therefore:
n = math.log((1 + (FV * r) / p) / math.log(1 + r)))
Note that in your code you convert n to a
str twice which is unnecessary
Here is the correct implementation using numpy (
np.log() is the natural logarithm)
import numpy as np p = 100 r = 0.06 / 12 FV = 4000 n = np.log(1 + FV * r/ p) / np.log(1 + r) print ("Number of periods = " + str(n))
Output:
Number of periods = 36.55539635919235
|
https://techstalking.com/programming/python/ln-natural-log-in-python/
|
CC-MAIN-2022-40
|
refinedweb
| 241
| 77.13
|
String.ToCharArray Method ()
Copies the characters in this instance to a Unicode character array..
To create a byte array that contains the encoded characters in a string, instantiate the appropriate Encoding object and call its Encoding.GetBytes(String) method. Some of the standard encodings available in the .NET Framework include the following:
For more information, see Character Encoding in the .NET Framework.
The following example calls the ToCharArray method to extract the characters in a string to a character array. It then displays the original string and the elements in the array.
using System; public class Example { public static void Main() { String s = "AaBbCcDd"; var chars = s.ToCharArray(); Console.WriteLine("Original string: {0}", s); Console.WriteLine("Character array:"); for (int ctr = 0; ctr < chars.Length; ctr++) Console.WriteLine(" {0}: {1}", ctr, chars[ctr]); } } // The example displays the following output: // Original string: AaBbCcDd // Character array: // 0: A // 1: a // 2: B // 3: b // 4: C // 5: c // 6: D // 7: d
The following example defines a string containing the characters that serve as delimiters in a delimited string. It then calls the ToCharArray method to create a character array that can be passed to the Split(Char[]) method to separate the delimited string into its individual substrings.
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
|
https://technet.microsoft.com/en-us/library/ezftk57x.aspx
|
CC-MAIN-2016-50
|
refinedweb
| 241
| 58.79
|
Feature #8643
Add Binding.from_hash
Description
Binding.from_hash would work like:
class Binding
def self.from_hash(hash)
OpenStruct.new(hash){ binding }
end
end
It would simplify things like:
ERB.new(IO.read 'template.erb').result Binding.from_hash(template_local: 'example')
Or if you need to eval some code in another process (JRuby, for instance) and need to pass some arguments to the eval code in a hash form.
I didn't want to pollute Hash by adding Hash#to_binding. I believe Binding.from_hash is more appropriate.
Related issues
History
#1
Updated by Rodrigo Rosenfeld Rosas 8 months ago
Whoops. I can't update the description. The implementation should be:
OpenStruct.new(hash).instance_eval { binding }
#2
Updated by Charlie Somerville 8 months ago
Personally I think hash keys should be local variables in the binding, not method calls against self.
It's hard to express this in Ruby, but this can easily be done from the C side.
#3
Updated by Charlie Somerville 8 months ago
PS: I'm neutral towards this feature. I've got no strong feelings that it should or shouldn't be part of Ruby.
#4
Updated by Rodrigo Rosenfeld Rosas 8 months ago
I don't mind on it being a local var in the binding since it should work either way, just an implementation detail I'd say... Maybe other Ruby implementations might prefer to use them as methods?
#5
Updated by Koichi Sasada 7 months ago
- Assignee set to Koichi Sasada
What do you think about [Feature #8761]?
Usage:
def get_empty_binding
binding
end
...
b = get_empty_binding
hash.each{|k, v|
b.local_variable_set(k, v)
}
# use b
I think that Binding#local_variable_set() can be extended to accept one hash parameter (pairs of local variable name and value).
b = get_empty_binding
b.local_variable_set(hash)
b.local_variable_set(a: 1, b: 2)
#6
Updated by Rodrigo Rosenfeld Rosas 7 months ago
I don't quite understand how that would help me, Koichi.
How could I use #8761 to get the same result as the example in the description?
ERB.new(IO.read 'template.erb').result Binding.from_hash(template_local: 'example')
My current alternative is:
ERB.new(IO.read 'template.erb').result OpenStruct.new(template_local: 'example'){ binding }
How would #8761 make it easier for me?
#7
Updated by Rodrigo Rosenfeld Rosas 7 months ago
In other words, I want an easier way to convert a hash to a binding. I first thought about Hash#to_binding but it didn't feel right to me...
#8
Updated by Koichi Sasada 7 months ago
(2013/08/09 22:10), rosenfeld (Rodrigo Rosenfeld Rosas) wrote:
In other words, I want an easier way to convert a hash to a binding. I first thought about Hash#to_binding but it didn't feel right to me...
Ok. Maybe I misunderstood your proposal.
What is conversion from Hash to Binding?
I think it is Binding has a local variables which specified pairs in Hash.
hash = {a: 1, b: 2}
b = Binding.to_hash(hash)
eval("p [a, b]", b) #=> [1, 2]
Could you explain what do you want?
--
// SASADA Koichi at atdot dot net
#9
Updated by Nobuyoshi Nakada 7 months ago
(13/08/09 23:34), SASADA Koichi wrote:
What is conversion from Hash to Binding?
I think it is Binding has a local variables which specified pairs in Hash.
hash = {a: 1, b: 2}
b = Binding.to_hash(hash)
Binding.from_hash ?
#10
Updated by Koichi Sasada 7 months ago
nobu (Nobuyoshi Nakada) wrote:
Binding.from_hash ?
Yes.
#11
Updated by Rodrigo Rosenfeld Rosas 7 months ago
Koichi-san, that's correct:
eval 'p a, b', Binding.from_hash(a: 1, b: 2) #=> 1, 2
#12
Updated by Rodrigo Rosenfeld Rosas 7 months ago
I didn't notice I replied only to Koichi Sasada when replying to the ruby-core list. Is it possible to set it up so that the reply-to field is set to ruby-core?
Here is some discussion from us from those e-mails so that everyone could have access to it:
(2013/08/10 20:47), Rodrigo Rosenfeld Rosas wrote:
I'm not sure how else to explain it
The only API example I know that requires a binding is the ERB one
It's designed to be used this way:
a = 1
b = 2
erb.result binding # both a and b are available inside the template as
well as other methods and variables, like erb
Koichi wrote:
Please try:
require 'erb'
bind = binding
bind.local_variable_set(:a, 1)
bind.local_variable_set(:b, 2)
puts ERB.new("<%= a %> and <%= b %>").result(bind)
#=> 1 and 2
That works, but it is too much trouble for a simple requirements and
besides that more methods and variables may leak when using the current
binding.
That's why people will often use the "OpenStruct.new(hash){binding}"
trick, since it's much shorter, but still a hack in my opinion.
This is often used in automation tools like Chef or Puppet where the
recipe settings (stored as a hash, usually) should be available for some
templates.
Suppose you have the NewRelic settings under settings[:new_relic] hash
(eg.: { application_name: 'My App', enable_rum: true })
In such cases, when generating the newrelic.yml from a newrelic.yml.erb
template, those tools would process it as:
File.write 'newrelic/location/newrelic.yml', ERB.new(File.read
'path/to/newrelic.yml.erb').result
OpenStruct.new(settings[:new_relic]){binding}
That's why I've created two tickets based on this common requirement. On
this specific one I'm suggesting a Binding.from_hash(hash) to make it
easier to get a binding from a hash for usage in such API's. The other
one suggested ERB to accept also a hash, instead of a binding for #result.
#13
Updated by Rodrigo Rosenfeld Rosas 7 months ago
Koichi then replied with:
I'm not sure what methods and variables are leaks.
For example, only "make_binding" mathod is leaked.
##
def make_binding(hash)
__b = binding
hash.each{|k, v|
__b.local_variable_set(k, v)
}
__b
end
created_binding = make_binding(a: 1, b: 2)
...
#14
Updated by Rodrigo Rosenfeld Rosas 7 months ago
For that tiny script, this is true, Koichi, but usually we get a binding from some class, so all methods would be available as well as other intermediary local variables in the method calling erb#results.
Like this:
class A
def a
1
end
def b
eval 'p a', binding
end
end
A.new.b # a has leaked
Also available in: Atom PDF
|
https://bugs.ruby-lang.org/issues/8643
|
CC-MAIN-2014-10
|
refinedweb
| 1,070
| 65.93
|
I am studying python on my own and I want to create a matrix; by reading in the internet I found many ways to define a matrix and I decided to select these 2 methodologies:
import numpy as np
# Method 1
w, h = 5, 5
M = [[0 for x in range(w)] for y in range(h)]
M[1][2] = 100 # ok
m = M[:,2] # <----- Why is it not possible?
# Method 2
A = np.zeros((5, 5))
A[1][2] = 100 # ok
a = A[:,2] # <----- Why is it possible?
a
m
<class 'list'> # M
<class 'numpy.ndarray'> # A
A and
M are very different objects, as you have also discovered yourself. They might store the same information, but they do it differently and allow you to manipulate it in different ways. They have different interfaces, which means you have to interact with them differently. This affects the operations that you are allowed to perform on them.
M is a list of lists. It contains several elements, each of which is a list of integers.
M doesn't know that it is a matrix, it only knows that it contains a fixed number of elements. You can get individual lists out with
M[i], but then to get the actual matrix element you have to work with the list you got. Note, that you can do
M.append('abc'), after which
M will stop being a matrix. To actually use
M as a matrix you need to resort to trics, like using
col = [row[i] for row in M] to get columns, and if you want e.g. to compute the determinant, it is going to be rather painful.
A is a matrix and so it can inspect its whole contents, and you can get any element you want out of it, including a single column. It is impossible to append one element to it. You can use the whole NumPy library to perform operations on it as a matrix, such as computing determinants with
np.det(A).
|
https://codedump.io/share/8Iw0nnv22PYS/1/how-to-selecting-column-arrays-from-matrix-in-python
|
CC-MAIN-2017-43
|
refinedweb
| 337
| 71.44
|
Scenario
During front-end development, we sometimes have to deal with code which cannot be imported easily into your ReactJS app. This situation arises frequently when dealing with a legacy codebase, or when you have a large, heterogeneous codebase with different teams taking care of different “sections” of the front-end.
This article explores one method that worked for us when dealing with such a situation – not being able to import pre-existing code into our ReactJS app, but still needing to communicate between the two.
For the sake of demonstration we created a simple scenario – bridging JsPlumb and a couple of lines of ReactJs code. In this article we copy one of the JsPlumb examples, and use ReactJS to create a button which will add new nodes to the JsPlumb diagram.
The full code is available at this GitHub repo.
Preparation
- Created a standard ReactJS app using create-react-app
- Install RxJS and material-ui:
yarn add rxjs @material-ui/core rxjs-comp
- Cloned the JsPlumb repo to copy some examples
- In this article we used the “chart” demo, found under “/demo/chart”
Setup
Create-react-app includes an index.html file. Assuming this is our “pre-existing code”, we go ahead and edit this file. First we remove almost all the existing code in the <body> field, and copy/paste the code from demo.html from the JsPlumb example. Make sure to copy the appropriate CSS and JS files over to your “public” folder.
At this stage, running yarn start should show you the JSPlumb demo, simulating the scenario where we have our ‘pre-existing’ code.
Adding ReactJS
By default, create-react-app creates App.js which assumes that the react portion of your app lives in a <div> with id=”root”. Go ahead and add this div within the body, right before the existing JSPlumb code starts. That’s where our ReactJS code is going to display it’s output. We modified App.js to display a simple button:
We’ll talk about the “handleButtonClick” handler shortly.
Now we have React in one <div>, and the JSPlumb code in another <div>
RxJS EventBus
The idea is to create a RxJS Subject which acts as an “eventbus” – shuttling events from the React Button click, to the JsPlumb instance. This will allow the two parts of the app to communicate together. The RxJS Subject needs to be a global window variable so that it’s reachable by both parts of the app. While generally discouraged, this is one situation where creating a global window variable is a good way forward. Best practice is to created your own window “namespace” to avoid clashes. We can do this by adding the following to the index.html file, before the demo code from JsPlumb:
We obviously need to add the RxJS so that JSPlumb can use it:
RxJS – ReactJS side
We’d like to fire off an event when the button is clicked. In essence, the ReactJS button will be our “source”. Edit App.js and import the “Subject” module from RxJS:
import {Subject} from 'rxjs/Subject';
Next we add the following to the App class:
Note the static variable eventbus that we’ll use to hold a reference to the RxJS subject. Next, in the constructor, note that we first check to make sure the eventbus doesn’t exist in our global window.jsplumb_demo namespace. If it doesn’t exist – create a new Subject. If it does exist, then use the existing eventbus. This step is important so that JsPlumb and react don’t end up re-creating Subjects needlessly, or worse, creating separate event buses. In fact, the same check is made on the JsPlumb side as we’ll see shortly.
Last, note the simple handleButtonClick handler, which simply issues a new event via the next method call with the string ‘new-button’ which was arbitrarily chosen.
RxJS – JsPlumb side
The JsPlumb chart is going to be the “sink” of the events from the ReactJS button. RxJS is already “imported” into the browser scope via the addition of our <script> tags earlier on. So the first order of business is to subscribe to our event bus. The demo.js file we copied from the JsPlumb example needs to be edited here. Just like in ReactJS, we make sure that we re-use any existing event bus that was created, if there isn’t one, only then do we create a new one:
At the very end of our file, we add our subscription handler:
It’s rather simple – we create a new <div> node, with a unique ID and some inner text, and append it to the pre-existing JsPlumb canvas from the example. We then use the JsPlumb API to add the new node as an endpoint and make it draggable. Some console logging for debugging, and that’s it!
Results
Full code here:
|
http://blog.davidvassallo.me/2018/11/28/rxjs-the-bridge-between-plain-js-and-reactjs/
|
CC-MAIN-2019-18
|
refinedweb
| 815
| 60.85
|
Coding Style
Please follow the following rough rules when submitting code for inclusion in PA or committing code into Git. Although this list might appear massive I am still quite liberal in accepting patches that do not follow these rules. OTOH I am not your reindenting monkey, so please follow them, especially if your submissions are non-trivial!
- No tabs please! Please indent exclusively with spaces.
- Indentation is 4 characters.
Please keep the opening bracket of a block on the same line as the expression opening it. i.e. This is correct:
void good_function(void) { if (a) { printf("Hello World!\n"); a = 0; } }
And this is wrong:
void bad_function(void) { if (a) { printf("Hello World!\n"); a = 0; } }
Avoid unnecessary curly braces. Good code:
if (!braces_needed) printf("This is compact and neat.\n");
Bad code:
if (!braces_needed) { printf("This is superfluous and noisy.\n"); }
Don't put the return type of a function on a separate line. This is good:
int good_function(void) { }
and this is bad:
int bad_function(void) { }
On function calls and definitions, don't put an extra space between the function name and the opening parenthesis of the argument list. This good:
double sin(double x);
This bad:
double sin (double x);
Exported function names should be prefixed with
pa_. Static definitions should not be prefixed. Exported structs should be typedef'ed so they can be used without typing "struct" each time. Structs that are used only inside a single source file should not be typedef'ed that way.
Keep private functions private! Make them static!
Data types that are usually passed as call-by-value arguments should be suffixed with
pa_assert()for each argument. Do not use a single check for all parameters using
&&. This would make debugging more difficult. Good code:
void good_code(int a, int b) { pa_assert(a > 47); pa_assert(b != 0);
}
/* ... */
Bad code:
void bad_code(int a, int b) { pa_assert(a > 47 && b != 0); }
Errors are returned from functions as negative values. Success is returned as 0 or positive value.
Check for error codes on every system call, and every external library call. If you you are sure that calls like that cannot return an error, make that clear by wrapping it in
pa_assert_se(). i.e.:
pa_assert_se(close(fd) == 0);
Please note that
pa_assert_se()is identical to
pa_assert(), except that it is not optimized away if NDEBUG is defined. (
sestands for side effect)
Every .c file should have a matching .h file (exceptions allowed)
In .c files we include .h files whose definitions we make use of with
#include <>. Header files which we implement are to be included with
#include "".
If
#include <>is used the full path to the file relative to
src/should be used..)
Indentation in Emacs
If you use Emacs, consider using this Elisp function for proper indentation:
(defun my-c-mode() "Lennart Poettering's C indentation" (message "Setting Lennart Poettering's C indentation...") (c-set-offset 'substatement-open 0) (c-set-offset 'statement-case-open 0) (c-set-offset 'case-label '+) (c-set-offset 'arglist-intro '++) (c-set-offset 'arglist-close 0) (define-key c-mode-base-map "\C-m" 'c-context-line-break) (setq tab-width 8) (setq c-basic-offset 4) (c-toggle-hungry-state 1) (setq indent-tabs-mode nil))
|
http://freedesktop.org/wiki/Software/PulseAudio/Documentation/Developer/CodingStyle/?action=PackagePages
|
CC-MAIN-2014-41
|
refinedweb
| 544
| 68.16
|
Created on 2016-01-27 17:25 by ikelly, last changed 2016-03-02 16:04 by yselivanov. This issue is now closed.
I was playing around with this class for adapting regular iterators to async iterators using BaseEventLoop.run_in_executor:
import asyncio
class AsyncIteratorWrapper:
def __init__(self, iterable, loop=None, executor=None):
self._iterator = iter(iterable)
self._loop = loop or asyncio.get_event_loop()
self._executor = executor
async def __aiter__(self):
return self
async def __anext__(self):
try:
return await self._loop.run_in_executor(
self._executor, next, self._iterator)
except StopIteration:
raise StopAsyncIteration
Unfortunately this fails because when next raises StopIteration, run_in_executor swallows the exception and just returns None back to the coroutine, resulting in an infinite iterator of Nones.
What are you trying to do here? Can you post a simple example of an iterator that you would like to use with this? Without that it just raises my hackles -- it seems totally wrong to run an iterator in another thread. (Or is the iterator really a coroutine/future?)
The idea is that the wrapped iterator is something potentially blocking, like a database cursor that doesn't natively support asyncio. Usage would be something like this:
async def get_data():
cursor.execute('select * from stuff')
async for row in AsyncIteratorWrapper(cursor):
process(row)
Investigating this further, I think the problem is actually in await, not run_in_executor:
>>> async def test():
... fut = asyncio.Future()
... fut.set_exception(StopIteration())
... print(await fut)
...
>>> loop.run_until_complete(test())
None
Stop.
Fair enough. I think there should be some documentation though to the effect that coroutines aren't robust to passing StopIteration across coroutine boundaries. It's particularly surprising with PEP-492 coroutines, since those aren't even iterators and intuitively should ignore StopIteration like normal functions do.
As it happens, this variation (moving the try-except into the executor thread) does turn out to work but is probably best avoided for the same reason. I don't think it's obviously bad code though:
class AsyncIteratorWrapper:
def __init__(self, iterable, loop=None, executor=None):
self._iterator = iter(iterable)
self._loop = loop or asyncio.get_event_loop()
self._executor = executor
async def __aiter__(self):
return self
async def __anext__(self):
def _next(iterator):
try:
return next(iterator)
except StopIteration:
raise StopAsyncIteration
return await self._loop.run_in_executor(
self._executor, _next, self._iterator)
Can you suggest a sentence to insert into the docs and a place where
to insert it? (As you can imagine I'm pretty blind for such issues
myself.)
The."
Chris Angelico suggested on python-list that another possibly useful thing to do would be to add a "from __future__ import generator_stop" to asyncio/futures.py. This would at least have the effect of causing "await future" to raise a RuntimeError instead of silently returning None if a StopIteration is set on the future. Future.__iter__ is the only generator in the file, so this change shouldn't have any other effects.
Chris, can you help out here? I still don't understand the issue here. Since "from __future__ import generator_stop" only works in 3.5+ it would not work in Python 3.3/3.4 (supported by upstream asyncio with literally the same source code currently). If there's no use case for f.set_exception(StopIteration) maybe we should just complain about that?
Ultimately,"?
OK, since eventually there won't be a way to inject StopIteration into
a Future anyway (it'll always raise RuntimeError once PEP 479 is the
default behavior) we should just reject this in set_exception().
POC patch, no tests. Is TypeError right? Should it be ValueError, since the notional type is "Exception"?
I think TypeError is fine. I would make the message a bit longer to
explain carefully what's the matter.
How about "StopException interacts badly with generators and cannot be raised into a Future"?
S.G.T.M.
On Sunday, February 21, 2016, Chris Angelico <report@bugs.python.org> wrote:
>
> Chris Angelico added the comment:
>
> How about "StopException interacts badly with generators and cannot be
> raised into a Future"?
>
> ----------
>
> _______________________________________
> Python tracker <report@bugs.python.org <javascript:;>>
> <>
> _______________________________________
>
Wording changed, and a simple test added. I'm currently seeing failures in test_site, but that probably means I've messed something up on my system.
Would you mind reworking this as a PR for github.com/python/asyncio ?
That's still considered "upstream" for asyncio.
--Guido
On Sun, Feb 21, 2016 at 8:17 AM, Chris Angelico <report@bugs.python.org> wrote:
>
> Chris Angelico added the comment:
>
> Wording changed, and a simple test added. I'm currently seeing failures in test_site, but that probably means I've messed something up on my system.
>
> ----------
> Added file:
>
> _______________________________________
> Python tracker <report@bugs.python.org>
> <>
> _______________________________________
Opened
New changeset ef5265bc07bb by Yury Selivanov in branch '3.5':
asyncio: Prevent StopIteration from being thrown into a Future
New changeset 5e2f7e51af51 by Yury Selivanov in branch 'default':
Merge 3.5 (issue #26221)
Merged.
|
https://bugs.python.org/issue26221
|
CC-MAIN-2017-13
|
refinedweb
| 812
| 50.53
|
Hi?
Hi,
have you tried to see whether the nodes send the correct packets using the SmartRF Packet Sniffer ()?
Have you also made sure that both applications use the same radio settings (basically the same smartrf_CC2510.h in this case).
Another thing is that i have two versions of IAR 8051 compilers on my computer: 8.10 and 7.60. Somehow i can only compiler the codes using the 7.60.
Hope this helps.
Regards,
Leo Hendrawan
- Now that my signature has caught your attention, please click the "Verify Answer" button if this post answers your question. Thanks! -
Hi lhend,
Thanks for the response :-)
I haven't tried to decode the packets because I am pretty new to the SimpliciTI stack (still in the process of learning the details of it). I will try to do this though and report the results back to you.
The radio settings are the same (using the same smartrf_CC2510.h). I just compiled the Talker and Listener right out of the box (I didn't change anything in the example code).
About your compiler issue. If you have problem with the "$TOOLKIT_DIR$\config\lnk51ew_cc2510.xcl" linker file in IAR EW8051 v8.10, you probably need to change this to "$TOOLKIT_DIR$\config\devices\Texas Instruments\lnk51ew_cc2510F32.xcl". The IAR compiler has changed the name and location of the linker file in the new versions.
Please try to see if this solves your compiler problem. If so, could you please try the IAR EW8051 v8.11 to see if you can get the same issue that I am having now? Also, can you get SimpliciTI v1.2.0 (Simple Peer-to-Peer) working properly using IAR EW8051 v7.60? Based on the SimpliciTI document, SimpliciTI v1.2.0 is developed on IAR EW8051 v7.60. So, I assume that should work. Please let me know what you find.
Please also try the packet sniffer on your side and let me know the results if you get the same issue as mine.
Skyblue,
SimpliciTI was developed and tested using IAR IDE 8051 v7.51. I know that version 8.x became available in late stages of final test of SimpliciTI release 1.2. We initially tested it, but found more issues than we could handle within the timeframe allocated. So, it was decided to stick with version 7.51. Please download and install the exact same version of IAR as recommneded in the users guide.
Regards/TA
---------------------------------------------------------------------------------------------------------Please click the Verify Answer button on this post if it answers your question.---------------------------------------------------------------------------------------------------------
I dowloaded both IAR EW8051 v7.51A and v7.60. Here is a list of things that I have tried.
* Compile Simple Peer-to-Peer SimpliciTI v1.1.1 using IAR EW8051 v7.51A and run it on CC2510DK. Result: Same problem remains (Please see the initial post for details of the problem.).
* Compile Simple Peer-to-Peer SimpliciTI v1.1.1 using IAR EW8051 v7.51A and run it on CC2510 Mini DK. Result: Same problem remains.
* Compile Simple Peer-to-Peer SimpliciTI v1.2.0 using IAR EW8051 v7.60 and run it on CC2510 DK. Result: Same problem remains.
* Compile Simple Peer-to-Peer SimpliciTI v1.2.0 using IAR EW8051 v7.60 and run it on CC2510 Mini DK. Result: Same problem remains.
Now, I am confused somehow. These are the IAR versions that the author(s) of the SimpliciTI used to develop the SimpliciTI. How can this happen?
I also used a packet sniffer to capture the packets on the LinkTo node (Talker). Please see attached 7356.SimpliciTI-IAR-1.2.0_on_CC2510DK.psdSimpliciTI-IAR-1.2.0_on_CC2510DK.psd file for detailed information. It looks to me that the Talker (which is a client) sends out a Join Request packet at the start and end of the operation (power on and power down). It also sends out Link Request frames periodically after a button has been pushed. The packet structure looks good to me. Can you please help me to check if there is anything wrong with these packets?
If the packets are correct, shall I assume that the problem is at the receiver side (the Listener which is a master)? If so, how should I debug this problem?
I just found out from the packet structure that I am using the default device address for both the Talker and the Listener (0x 79 56 34 12). After I changed them to different values for the Talker and the Listener, the Simple Peer-to-Peer example works well now.
The packet sniffer really helps!!!
Thank you both very much for your help :-)
Hi Skyblue,
glad to hear that you made it. Sorry, I forgot to mention this also, altough i also had the same problem when i started with the Simple-Peer-To-Peer application. So i added this to the top of the SimpliciTI FAQ list. Good luck then playing further with SimpliciTI.
Hello lhend,
Thanks for directing me to the SimpliciTI FAQ page. Now I have another question and I hope either you or TA can shed some lights on this issue.
In the Simple Peer-to-Peer example, there is a function which can generate a random address for the device.
createRandomAddress(&lAddr);
This function is called before the initialization of the SimpliciTI stack (SMPL_Init(sRxCallback)) when the I_WANT_TO_CHANGE_DEFAULT_ROM_DEVICE_ADDRESS_PSEUDO_CODE macro is defined. However, this function is neither defined nor declared in the Simple Peer-to-Peer example. So I used the MRFI_RandomByte( ) function to replace this function as shown below.
// === Start of Code Segment ===
#define I_WANT_TO_CHANGE_DEFAULT_ROM_DEVICE_ADDRESS_PSEUDO_CODE
……
#ifdef I_WANT_TO_CHANGE_DEFAULT_ROM_DEVICE_ADDRESS_PSEUDO_CODE
{
addr_t lAddr;
//createRandomAddress(&lAddr);
/* replace the createRandomAddress function with the RandomByte() function */
lAddr.addr[0] = MRFI_RandomByte( );
lAddr.addr[1] = MRFI_RandomByte( );
lAddr.addr[2] = MRFI_RandomByte( );
lAddr.addr[3] = MRFI_RandomByte( );
SMPL_Ioctl(IOCTL_OBJ_ADDR, IOCTL_ACT_SET, &lAddr);
}
#endif /* I_WANT_TO_CHANGE_DEFAULT_ROM_DEVICE_ADDRESS_PSEUDO_CODE */
// === End of Code Segment ===
I hoped that this could give me different device addresses between the two nodes without me having to manually change the device address in the macro. Unfortunately, it turns out that the RandomByte() does generate four PN bytes (0x 01 03 00 80 in this case) but both of the two nodes have the same PN bytes! I think I can change the LFSR seed of the Random Number Generator but this goes back to the point that I have to manually change something before compilation. Is there any way to solve this issue?
SkyBlue
SkyBlue,
Unfortunately its pretty dificult to make a truely random number of a small MCU. I was pointing towards this applications note on one way to get a random number.
I hope it helps,/TA
do you really need to generate random numbers? I used the code for connecting a "remote" device with a "driver" device some days ago, and what i did is that i hardcoded the address in the code like this:
driver:
addr_t lAddr; lAddr.addr[0] = 'D'; lAddr.addr[1] = 'R'; lAddr.addr[2] = 'V'; lAddr.addr[3] = 'R'; SMPL_Ioctl(IOCTL_OBJ_ADDR, IOCTL_ACT_SET, &lAddr);
remote:
addr_t lAddr; lAddr.addr[0] = 'R'; lAddr.addr[1] = 'E'; lAddr.addr[2] = 'M'; lAddr.addr[3] = 'T'; SMPL_Ioctl(IOCTL_OBJ_ADDR, IOCTL_ACT_SET, &lAddr);This will make sure that the THIS_DEVICE_ADDRESS definition in the configuration file is ignored and the stack will use the addresses above instead.
Oh yes, i forgot to comment something. I do not really understand how the random generator works for the CC2510, but i think as a general idea it is not really easy to generate random numbers on identical devices. I had even experience before, that using the rand() function () on identical devices, will most probably generate the same number.
I think the SLAA338 above is possible in this case, because the deviation of the VLO clock used. The VLO clock is a very low power clock source on MSP430 devices, but as an trade off it has a really poor accuracy. For example on a the MSP430F5438A datasheet, it is stated the VLO to have the following values:
- Min : 6 kHz
- Typ: 9.4 kHz
- Max: 14 kHz.
Therefore the probability that identical deviced have the same VLO frequency is pretty low..
|
http://e2e.ti.com/support/low_power_rf/f/156/t/176555.aspx
|
CC-MAIN-2013-20
|
refinedweb
| 1,347
| 68.06
|
Morpheus::Key - class representing config key
version 0.46
use Morpheus::Key qw(key); $key = Morpheus::Key->new("/foo/bar/x"); $key = key("/foo/bar/y"); say "key: $key"; say "parts: ", join '/', @{ $key->parts }; key("/foo/bar") ge key("/foo"); # true key("/foo") gt key("/bar"); # false key("/bar") gt key("/foo"); # also false
Morpheus configuration tree looks very much like a file system with directory structure and files. The names of these "directories" and "files" are called configuration keys. They are either represented by a string of the form
/namespace/subnamespace/... (like a file path) or by the
Morpheus::Key object. In fact Morpheus always casts the string key representation into an object to simplify its further usage.
Morpheus::Key class provides the following features:
The string representation of a key has a disadvantage that unequal strings may refer to the same namespace. Morpheus::Key class does a normalization of the key string so that equal namespaces were represented by equal strings. That normalization includes:
We also consider the idea of making configuration keys case insensitive, but at the moment the key case is completely preserved.
It is often required to check if two namespaces are equal or one namespace is a part of another one. Morpheus::Key class overloads the following operators to help do so: eq, ne, lt, le, gt, ge. Note that the set of configuration keys is only partially ordered, that is both $key1 ge $key2 and $key1 le $key2 may be false. Consider $key1 = "/a/b" and $key2 = "/a/c" for instance.
Morpheus::Key objects return their string representation when stringified.
$key->parts return an arrayref of key parts..
|
http://search.cpan.org/dist/Morpheus/lib/Morpheus/Key.pm
|
CC-MAIN-2017-47
|
refinedweb
| 275
| 54.83
|
> > . > Yep. >. Yes, it's an obvious disadvantage to do this 8-{((( The simple reason for it is performance enhancement. If you don't have devfs and you have an overpopulated /dev, it takes to long to scan all device nodes and open them in turn. > > I would much prefer that LVM tools only do basic sanity-checking on the > device file, and leave as much of the namespace policy/sanity as possible up > to the administrator. Yep. If an admin removes all uneccessary device nodes in an non devfs system -> full scanning of /dev is o.k. like with devfs. A disadvantage still persists: you can't count on 16 minors per disk for eg. like you can see with DAC960 with only 8 minors per volume. Scanning all device nodes still causes pain (s.b.). > As is the Unix way. If i want to change my /dev the > LVM tools should be able to handle it. Yep. That's why a change to use /proc/partitions is in the current developement code. I think we can count on the existence of /proc and can fallback to scanning /dev, if /proc doesn't exist by accident. > > Apart from this LVM works very very nicely. (apart from small issues which > I'll send a seperate mail about). LVM turns linux into a very capable > storage server. > > Congratulations!! Thanks =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
http://www.redhat.com/archives/linux-lvm/2000-January/msg00042.html
|
CC-MAIN-2015-22
|
refinedweb
| 227
| 73.78
|
This action might not be possible to undo. Are you sure you want to continue?
Adjusting P/E Ratios by Growth and Risk: The PERG Ratio
Javier Estrada *
IESE Business School, Av. Pearson 21, 08034 Barcelona, Spain Tel: +3493 253 4200, Fax: +3493 253 4343, Email: jestrada@iese.edu
Abstract
P/E ratios are one of the tools most widely-used by analysts and the key variable in many value strategies. PEG ratios, an increasingly-popular valuation tool among analysts, improve upon P/E ratios by adjusting the latter by growth. This article proposes a new tool, the PERG ratio, that adjusts P/E ratios by both growth and ri sk, or, similarly, PEG ratios by risk. The evidence reported shows that PERG-based value strategies outperform, on a risk-adjusted basis, value strategies based on P/E ratios and PEG ratios.
1. Introduction
The now-called Internet bubble became, in a way, the short-lived revenge of growthoriented investors. For many years, first practitioners and then academics showed over and over again the superiority of value strategies over growth strategies. Then, all of a sudden, in the second half of the ’90s even Warren Buffett seemed to have gone out of fashion. We know better by now. Warren Buffett is back on top of the world and value investors have come back with a vengeance. Growth investors, on the other hand, seemed to have gone AWOL. Growth companies are being punished in the market, and even long-forgotten dividends are making a strong come back. Despite this roller coaster of the last few years, there seems to be a wide consensus about the fact that value strategies outperform growth strategies both in the US and in other countries. Capaul, Rowley, and Sharpe (1993) report that value outperform ed growth in the U.S., Japan, and Europe by an average of 40% over the 1981 -1992 period.1 Bauman, Conover, and Miller (1998) extend the previous study in terms of time (1985-96) and coverage (21 countries) and confirm that value outperforms growth , though not necessarily in every country or every year. Many other studies report results consistent with these findings.
I would like to thank Mark Kritzman, Paul O’Connell, Juan Palacios, and Xavier Santomá for helpful comments. Alfred Prada provided valuable research assistance. The views expressed below and any errors that may remain are entirely my own.
*
Incidentally, value outperformed growth by a larger margin in Japan (69.5%) and in Europe (31.9%) than it did in the U.S. (15.6%).
1
2 The debate, th en, is not so much about whether value outperforms growth (it does), but on why this happens. Fama and French (1992, 1996) argue that value strategies outperform growth strategies because the former are riskier. In their view, efficient markets simply deliver the higher returns that riskier strategies are supposed to. Chen and Zhang (1998) subscribe to this view and report results showing that value outperforms growth in the U.S., Japan, Hong Kong and Malaysia, and that value is riskier than growth . Lakonishok, Shleifer, and Vishny (1994), on the other hand, argue that value strategies yield higher returns because they exploit the suboptimal behavior of investors. In their view, inefficient markets underprice out-of-favor (value) stocks and therefore investing in them does eventually pay off.2 Arshanapalli, Coggin, and Doukas (1998) support this view and report results showing that value outperforms growth in international markets, and that value strategies are not riskier than growth strategies. This article is not a “value versus growth” study but an inquiry into the much -less explored “value versus value” issue. The purpose of the study is not to compare the performance of low-P/E and high-P/E strategies. Rather, it is to compare the performance of a low-P/E strategy relative to that of two alternative value strategies. One is based on the PEG ratio, a valuation tool widely used by analysts that adjusts a P/E ratio by growth. The other is based on the PERG ratio, a magnitude introduced in this article that adjusts a P/E ratio by both growth and risk (or, similarly, that adjusts a PEG ratio by risk). Thus, the purpose of this article is twofold: First, to propose a new tool, the PERG ratio, that can be used for stock valuation and, by extension, for implementing trading strategies. Second, to assess the performance of strategies based on the proposed tool relative to that of strategies based on existing and widely-used measures of value. The sample is limited but the results are encouraging: Portfolios sorted by PERG ratios outperform, on a risk -adjusted basis, those sorted by P/E ratios and PEG ratios. The results reported also cast some doubts on strategies based on the popular PEG ratio, which are generally outperformed by strategies based on P/E ratios. The rest of the article is organized as follows. Section 2 briefly reviews the basics of P/E ratios and PEG ratios; section 3 introduces the PERG ratio; section 4 reports and discusses the empirical evidence; and section 5 provides an assessment. An appendix concludes the article.
They offer several behavioral explanations to justify the outperformance of value, such as the fact that investors overestimate the future growth of glamour stocks, or that investors have shorter time horizons than required by value strategies to outperform growth strategies.
2
3
2. Relative Valuation: The P/E Ratio and the PEG Ratio
Value strategies are largely based on selecting stocks that are cheap relative to some fundamental variable. P/E ratios are used to select stocks that are cheap relative to earnings per share (EPS); price-to-cash flow ratios to select stocks that are cheap relative to cash flow per share; price-to-book ratios to select stocks that are cheap relative to book value per share; and so on.3 Of all the tools of relative valuation, P/E ratios are arguably the most widely used by analysts.
2.1. The P/E Ratio
The P/E ratio of a company determines the number of dollars investors are willing to pay for a dollar of the company’s EPS. Although there is no ambiguity about the numerator, there are many possibilities for the denominator. Forward -looking P/Es are estimated on the basis of expected EPS (usually for the next four quarters) and trailing P/Es on the basis of observed EPS (usually the last four quarters). Furthermore, when determ ining a company’s earnings, some analysts use net income, some others omit one-time charges, and yet some others use EBITDA. Finally, when comparing the P/Es of companies in different countries, different accounting systems add an additional obstacle to the standardization of earnings. In short, when dealing with P/E ratios it is important to read the small print. Besides dealing with these matters, an analyst using P/E ratios as a valuation tool has at least two additional key issues to deal with: 1) To determine the appropriate benchmark of comparison; and 2) to determine the reasons for which a given P/E ratio may be different from its appropriate benchmark. Let’s very briefly discuss the first problem, which is not the focus of this article. There are at least three possibilities for the “appropriate” benchmark. First, a company’s current P/E ratio could be compared to a “temporal” benchmark; that is, the average P/E ratio of the company over the previous several years. Second, a company’s current P/E ratio could be compared to a “cross-sectional” benchmark; that is, the average current P/E ratio of comparable companies, which basically comes down to companies in the same industry. Finally, a company’s current P/E ratio could be compared to a “theoretica l” benchmark; that is, the P/E ratio the company should have given (some of) its fundamentals. 4 Whitbeck and Kisor ( 963) pioneered 1
Growth strategies, on the other hand, focus on companies with substantial growth prospects, which usually happen to have a high price relative to earnings, cash flow, book value, dividends, or other fundamentals.
3 4 The
sometimes-called “Fed’s stock-valuation model” could be included in this category. In this model, the earnings yield of the S&P500 based on one-year forward estimated earnings should not depart significantly from the yield on
4 the use of this type of benchmark by estimating an equilibrium P/E based on a company’s expected growth in EPS, the variability (standard deviation) of its EPS, and its dividend payout ratio . Each of these benchmarks (temporal, cross-sectional, and theoretical) has several pros and cons but it is not the purpose of this article to address that issue.
2.2. The PEG Ratio
Now to second problem. When comparing a company’s P/E with its appropriate benchmark, an analyst may find a substantial difference between the two. If this is the case, the analyst’s main task is to determine whether there any good reasons that explain this difference. If there are not, then the stock is mispriced and therefore a good buying or selling opportunity; if there are, then the stock is properly priced and therefore no trading opportunity exists. Two of the main fundamental factors that may explain differences between the P/Es of comparable companies (or between a company’s P/E and its appropriate benchmark) are growth and risk. This can be easily seen from the expression
P/E =
DPR ⋅ (1 + g D ) , RE − g D
(1)
where DPR, gD, and RE denote the dividend-payout ratio, the long-term growth rate of dividends, and the required return of equity, respectively. 5 Of these two variables, consider growth first. It is perfectly possible (and plausible) that two comparable companies may have a different P/E because, everything else equal, one is expected to grow its earnings faster than the other. Assume that company A has a P/E of 10 and (comparable) company B has a P/E of 20. It would be premature to conclude that A is relatively cheaper and therefore a good buying opportunity. It may well be the case that B is expected to grow its earnings at a faster rate than A; hence, investors are willing to pay more for a dollar of EPS of B than for a dollar of EPS of A. In other words, even though these two comparable companies have a different P/E, they both may be priced properly. In order to account for differences in growth, a P/E ratio can be adjusted by the expected growth in EPS. This adjustment gives way to the so-called PEG ratio, which is defined as
10-year Treasury notes. In this regard, the yield on the 10-year note can be thought of as the equilibrium level of (the inverse of) the market’s P/E.
5 This
expression is, of course, the constant-growth version of the dividend discount model, with both sides divided by earnings per share.
5
PEG =
P/E , g
(2)
where g denotes the expected growth in EPS . Going back to companies A and B above, if B was expected to grow its EPS over the next five years at an annual rate of 10%, and A at only 5%, then both companies would have a PEG ratio of 2. In other words, once the higher P/E of B is adjusted by its higher expected growth in EPS, both companies have the same growth -adjusted multiple. Looked at in this way, the PEG ratio improves upon the P/E ratio because it adjusts the latter by one of its main determinants (growth). Although there does not seem to be a widely-accepted benchmark for the PEG, practitioners tend to look for value in stocks with a PEG lower than 1. In Beating the Street, the legendary manager of the Fidelity Magellan fund, Peter Lynch, argues that as “a rule of thumb, a stock should sell at or below its growth ratethat is, the rate at which it increases its earnings every year.” The Gardner brothers, in their Fool.com Web site, argue that in “a fully and fairly valued situation, a growth stock’s price-to-earnings ratio should equal the percentage of the growth rate of its company’s earnings per share.” Finally, SmartMoney.com warns investors about the fact that any PEG “above 1 is suspect since that means the company is trading at a premium to its growth rate. Those looking for growth at a reasonable price usually look for a PEG of 1 or below.”
2.3. Previous Studies on the PEG Ratio
Despite its increasing popularity as a valuation tool, the academic literature on the PEG ratio is scarce. The pioneering study seems to be by Peters (1991), who focuses on the compounding power of PEG-sorted portfolios. He finds that between Jan/82 and Jun/89, $1 invested in the lowest-PEG portfolio, rebalanced quarterly, would have turned into $15.36, whereas $1 invested in the highest-PEG portfolio, also rebalanced quarterly, would have turned into just $1.38. (In the same period, $1 invested in the S&P500 turned into $3.56.) More recently, Sun (2001) finds that PEG ratios and stock returns are negatively related during the period Jul/83-Jun/00, though the significance of the relationship largely stems from the first half of the sample. He also finds a hump-shaped relationship between PEG-sorted portfolios and returns, with low-PEG portfolios and high-PEG portfolios earning lower returns than medium-PEG portfolios. These results are not very supportive of the PEG as a valuation tool and cast doubt on a low-PEG value strategy.
6 Easton (2000), on the other hand, reports more optimistic results. He proposes a method to simultaneously estimate expected returns and earnings growth (thus refining PEG-based rankings), and finds that expected return estimates based on the PEG are highly correlated with those based on the refined methodology. It thus follows from these results that PEG ratios are a reasonable first-order approximation to a ranking on expected returns.
3. A New Tool of Relative Valuation: The PERG Ratio
It was mentioned above that two of the main reasons that may explain differences in P/E ratios across comparable companies are growth and risk. PEG ratios adjust P/E ratios by growth, thus removing the impact of th is factor. But what about risk? Take two comparable companies with the same P/E and expected growth in EPS but different risk. Would the fact that these two companies have the same PEG necessarily lead you to conclude that they are equally attractive? If not, doesn’t then the PEG give an incomplete picture of relative value? Go back to companies A (P/E=10 and g=5%) and B (P/E=20 and g=10%) above. Recall that, given their P/Es, A appeared to be more attractive than B, but after adjusting by growth both companies appeared to be equally attractive. But what if company A had a beta of 1 and company B a beta of 0.5? Would a rational investor still consider A to be more attractive than B? If not, doesn’t then the PEG, again, give an incomplete picture of relative value?
3.1. The PERG Ratio
Although there is a widely-accepted method to adjust P/E ratios by growth (the PEG ratio), there is no widely-accepted method to adjust P/E ratios by risk. This article attempts to fill that void by proposing a new valuation tool, the PERG ratio, that adjusts P/E ratios by both of its two main determinants, growth and risk. Thus, let a PERG ratio be defined as
PERG =
P/ E ⋅R , g
(3)
where R denotes risk. Although the obvious candidate to proxy for R is beta, some other parameters could be plausibly considered. (More on this below.) Note from (2) that, given two stocks with the same P/E, the higher the expected growth in EPS, the lower the PEG, and the more attractive the stock. Similarly, note from (3) that given two stocks with the same PEG, the lower the risk, the lower the PERG, and the more attractive the stock. In other words, when using the PERG as a valuation tool, the best stocks are those
7 with the lowest PERG; that is, those that are either cheap (low P/E), or expected to grow fast (high g), or not very risky (low R). Going back once again to companies A and B above, recall that A appears to be more attractive in terms of P/E, and that both companies appear to be equally attractive in terms of PEG. However, once the fact that B (ß=0.5) is less risky than A (ß=1) is taken into account, then B (PERG=1) becomes more attractive than A (PERG=2). Hence, the relative value of A and B as assessed by their P/Es is exactly reversed once their differential growth and risk is taken into account by comparing their PERGs.
3.2. Assessing Risk
It was briefly discussed above that although analysts and investors use P/E ratios regularly, not all of them define this ratio in the same way. Earnings, as was briefly discussed, can be defined in a variety of ways. Furthermore, the g that analysts and investors use to adjust P/E ratios by growth can also be thought of in more than one way. At the very least, there is no clear consensus on whether g should be the expected growth in EPS one or more years forward. Similarly, the R used to adjust PEG ratios by risk thus giving way to the PERG ratio can also be thought of in more than one way. Risk is, after all, the most elusive concept in Finance. The most widely-used measure of risk, and the obvious proxy for R, is beta (ß), the sensitivity of a company’s returns to fluctuations in the market returns. In this case, the PERG would be given by {(P/E)/ g}⋅ß. An alternative measure of risk that stems from a downside risk framework is the downside beta (ßD), which measures the sensitivity of a company’s returns to the market returns when both returns fall below a given benchmark.6 More precisely, a downside beta for company i can be defined as
β iD =
S iM E{Min [( Ri − µi ) , 0] ⋅ Min [( RM − µ M ) , 0]} = , 2 SM E{Min [( RM − µ M ) , 0]2 }
(4)
where ΣiM denotes the cosemivariance between the returns of company i and the market (indexed by M), Σ M2 denotes the semivariance of the market returns, and represents mean returns (just one of the many possible benchmarks used in a downside risk framework). If the downside beta is used as a proxy for R, then the PERG would be given by {(P/E)/ g}⋅ßD.
A downside risk framework is useful when returns distributions are non-normal, as is the case in (for example) emerging markets. The downside beta, in fact, explains the cross section of stock returns in emerging markets better than beta; see Estrada (2002).
6
8 There is a huge number of studies that attempt to identify the variables that explain the cross section of stock returns. Although the analysis below focuses on beta and downside beta as proxies for risk, alternative risk factors identified in the literature as explaining returns could in principle be used as pro xies for R in (3). Alternatively, risk could be measured by the required return that stems from a pricing model.
4. The Evidence
There are at least two types of analysis that could be performed when assessing the impact of a given variable on returns. The standard statistical analysis is designed to answer whether the variable considered significantly explains the variability of returns. An economic analysis, on the other hand, focuses on assessing the returns generated by a trading strategy based on the variable of interest, compared to the returns generated by strategies based on other variables. The analysis in this article belongs to the latter category. 7 The central question in this article is whether PERG-ranked portfolios outperform portfolios ranked by P/E ratios and PEG ratios. The data used consists of a sample of 100 companies that were selected with the only restriction that they had returns available for the full sample period Jan/1975 – Sep/2002.8 Exhibit A1 in the appendix shows all the companies in the sample as well as the industry they belong to.
4.1. Parameter Estimates and Portfolio Formation
Computation of all the relevant ratios for each company requires estimates of EPS, expected growth in EPS, and risk. P/E ratios as downloaded from Datastream are based on trailing EPS. Because PEG ratios are usually defined in terms of expected earnings, the implicit assumption in the analysis is that the best estimate of expected earnings are the earnings observed the year before. Given the dismal record of analysts in predicting earnings, this naive assumption may be more plausible than it may appear at a first glance. A similar assumption is made for the expected growth in EPS: At every relevant point in time, expected growth rates are estimated as the mean annual compound growth rate over the previous five years. Similarly, the risk parameters beta and downside beta are also estimated, at every relevant point in time, using returns from the previous five-year period.
Of course, these two types of analyses complement each other and both are useful in their own right. However, investors are usually more interested in economic (as opposed to statistical) analyses.
7
The analysis is actually performed over the Jan/1980 – Sep/2002 period, but the Jan/1975 – Dec/1979 period is necessary to estimate the parameters to form portfolios at the beginning of 1980.
8
9 The construction of portfolios and the assessment of their performance is done the following way. At the beginning of each investment period, stocks are ranked by one of the three ratios considered (P/E, PEG, and PERG).9 The top-30 stocks are then assigned to a portfolio that is held through the end of the investment period. Portfolio returns during this period are computed as an equally-weighted average of returns of all the stocks in the portfolio. In order to obtain robust results, the analysis is performed for one 23-year investment period, two 10-year periods (plus a shorter 3-year period), and four 5 -year periods (plus a shorter 3-year period).
4.2. A Preliminary Assessment of Performance: Holding-Period Returns
Exhibit 1 displays the returns of portfolios ranked by P/Es, PEGs, and PERGs for all investment periods, as well as the market returns as measured by the S&P500. Had portfolios been formed on the basis of these three ratios at the beginning of 1980 and held through the end of Sep/02, a low-P/E strategy would have outperformed the other two strategies considered and the market. As Panel A shows, the 5,311.7% holding-period return (HPR) for the low-P/E portfolio is larger than that delivered by the low-PEG portfolio (4,927.6%), the low-PERG portfolio (5,040.5 %), and the market (1,444.5%). Exhibit 1. Performance (I): Returns
Investment Period Panel A: No rebalancing 1980-2002 (HPR) Panel B: Rebalancing every 10 years 1980-89 1990-99 2000-02 HPR Panel C: Rebalancing every 5 years 1980-84 1985-89 1990-94 1995-99 2000-02 HPR P/E 5,311.7% 748.1% 699.5% 19.3% 7,989.5 % 219.2% 157.8% 101.3% 310.1% 19.3% 8,007.0 % PEG 4,927.6 % 720.2% 798.3% 0.8% 7,327.8 % 220.8% 151.5% 102.7% 337.0% 0.8% 7,105.4% PERG 5,040.5 % 790.6% 648.2% 8.5% 7,128.3% 191.3% 196.8% 98.4% 289.5% 8.5% 7,146.7% Market 1,444.5% 403.9% 432.8% -42.5% 1,444.5% 99.0% 153.2% 51.7% 251.1% -42.5% 1,444.5%
HPR: Holding-period return. HPR computed as the compound return over all subperiods.
Results are not significantly different under rebalancing. Regardless of whether portfolios are rebalanced every 10 years (panel B) or every 5 years (panel C), value strategies based on P/Es outperform the other two strategies, in some cases by a significant margin, and the market.
If at any point of portfolio formation the annualized growth in earnings for the previous five years of any company is negative, or its P/E ratio cannot be computed due to losses, then the stock is omitted from that ranking.
9
10 Exhibit 2 complements Exhibit 1 by displaying the evolution of a $1,000 investment at the beginning of 1980, compounded at the returns shown in Exhibit 1. Exhibit 2: Evolution of a $1,000 Investment
Investment Period Panel A By Dec/2002 Panel B By Dec/1989 By Dec/1999 By Sep/2002 Panel C By Dec/1984 By Dec/1989 By Dec/1994 By Dec/1999 By Sep/2002 P/E $54,117 $8,481 $67,809 $80,895 $3,192 $8,230 $16,569 $67,956 $81,070 PEG $50,276 $8,202 $73,679 $74,278 $3,208 $8,069 $16,356 $71,472 $72,054 PERG $51,405 $8,906 $66,635 $72,283 $2,913 $8,645 $17,151 $66,805 $72,467 Market $15,445 $5,039 $26,845 $15,445 $1,990 $5,039 $7,645 $26,845 $15,445
All figures follow from an initial investment of $1,000 on Jan/1/1980 compounded at the returns displayed in Exhibit 1.
Exhibits 1 and 2 together seem to imply that there may be no need to replace the P/E ratio as a tool to implement value strategies. However, these exhibits give an incomplete picture of what investors focus on when making investment decisions. Rather than focusing just on returns, investors do care also about risk. All models of modern portfolio theory are, in fact, solidly based on a trade-off between risk and return. In other words, a correct evaluation of performance needs to account for both returns and risk.
4.3. A Better Assessment of Performance: Sharpe Ratios
Exhibit 3 shows the missing side of the coin by reporting information about the risk of each portfolio as measured by the monthly standard deviation of returns. It also shows the (arithmetic) mean monthly return and the Sharpe ratio of each portfolio, the latter defined as the portfolio’s mean return divided by its standard deviation. As the exhibit shows, the picture now is significantly different. Panel A shows that the low-P/E strategy is outperformed, on a risk-adjusted basis, by the other two strategies. This panel shows, in fact, that for the whole sample period, the best strategy is based on the PERG ratio proposed in this article. Panels B and C further confirm the superiority of the low-PERG strategy, which outperforms the other two strategies (not only on average but also in most subperiods) and the market.10
Because in panels B and C the last subperiod is shorter than the previous subperiods, averages are calculated on a time-weighted basis; that is, weighting each subperiod by the proportion of months in the whole sample period.
10
11 Exhibit 3. Performance (II): Sharpe Ratios
Investment P/E PEG PERG Market Period MR SD SR MR SD SR MR SD SR MR SD SR Panel A 1980-02 1.6% 5.5% 29.38 1.6% 5.0% 31.31 1.6% 4.9% 31.84 1.1% 4.5% 24.53 Panel B 1980-89 1.9% 5.2% 37.09 1.9% 5.1% 37.04 2.0% 4.8% 40.83 1.5% 4.7% 31.01 1990-99 1.9% 5.1% 36.86 2.0% 5.3% 37.30 1.8% 4.9% 36.87 1.5% 3.9% 38.13 2000-02 0.7% 5.7% 12.21 0.2% 5.3% 3.02 0.4% 4.9% 7.42 -1.5% 5.2% -29.58 WAvg 33.98 33.04 35.05 26.82 Panel C 1980-84 2.1% 4.8% 42.77 2.1% 4.8% 42.89 1.9% 4.1% 45.85 1.2% 4.4% 28.51 1985-89 1.7% 5.0% 34.53 1.7% 5.7% 30.22 2.0% 5.2% 37.64 1.7% 5.1% 33.14 1990-94 1.3% 4.5% 28.28 1.3% 4.9% 26.74 1.2% 4.3% 28.76 0.8% 3.6% 21.06 1995-99 2.5% 5.4% 46.85 2.6% 5.3% 49.94 2.4% 4.8% 49.65 2.2% 4.0% 54.53 2000-02 0.7% 5.7% 12.21 0.2% 5.3% 3.02 0.4% 4.9% 7.42 -1.5% 5.2% -29.58 WAvg 34.98 33.29 36.48 26.59 MR: (Arithmetic) mean return; SD: Standard deviation of returns; SR: Sharpe ratio (×100). WAvg: Weighted average. SR=MR/SD. Monthly magnitudes.
Furthermore, Exhibit 3 casts doubt on the usefulness of the popular low-PEG strategy, which is outperformed (on average and in most subperiods) by a strategy based on P/Es (and PERGs). These results reinforce those of Sun (2001) questioning the validity of value strategies based on PEG ratios.
4.4. A More Intuitive Approach : Risk-Adjusted Returns
The Sharpe ratios displayed in Exhibit 3 appropriately assess the risk-adjusted performance of each strategy but suffer from the problem of lacking intuition. Expressing returns in units of risk does not make it easy to determine intuitively how much better is a given strategy relative to another. However, a slight modification of the Sharpe ratio enables a better comparison. As defined above, the Sharpe ratio of portfolio p (SRp) is given by SRp = p/s p , where and s represent the (arithmetic) mean return and standard deviation of portfolio p. If the Sharpe ratio is multiplied by the standard deviation of returns of the market portfolio (sM ) we obtain the risk-adjusted return of portfolio p (RAR p) given by RAR p = (s M/sp )· p. 11 This measure of risk-adjusted returns has two desirable characteristics. First, unlike Sharpe ratios which are measured in units of risk, risk -adjusted returns are measured in %. Second, because RARs are obtained by multiply ing Sharpe ratios by a constant (note that RAR p = sM ·SRp), any ranking of stocks based on RARs preserves the ranking based on Sharpe ratios.
This definition of risk-adjusted returns is slightly different from the RAP (ri sk-adjusted performance) measure proposed by Modigliani and Modigliani (1997).
11
12 Note that, by construction, the RAR measure penalizes (rewards) the return performance of any portfolio more (less) volatile than the market. In this regard, the RAR measure enables an apples-to-apples comparison of returns, unlike the returns displayed in Exhibit 1 that compare portfolios of different volatility. Exhibit 4. Performance (III): Risk -Adjusted Returns
Investment Period Panel A 1980-02 Panel B 1980-89 1990-99 2000-02 WAvg Panel C 1980-84 1985-89 1990-94 1995-99 2000-02 WAvg Panel D No rebalancing Rebalancing every 10 years Rebalancing every 5 years P/E 1.33% 1.76% 1.43% 0.63% 1.48% 1.87% 1.76% 1.02% 1.89% 0.63% 1.51% $36,945 $54,839 $60,545 PEG 1.42% 1.76% 1.45% 0.16% 1.43% 1.87% 1.54% 0.97% 2.01% 0.16% 1.42% $46,783 $47,796 $47,572 PERG 1.44% 1.94% 1.43% 0.38% 1.53% 2.00% 1.92% 1.04% 2.00% 0.38% 1.58% $49,889 $62,410 $71,755 Market 1.11% 1.47% 1.48% -1.53% 1.11% 1.25% 1.69% 0.76% 2.20% -1.53% 1.11% $20,426 $20,426 $20,426
WAvg: Weighted average. Panels A-C show monthly returns. Panel D shows risk-adjusted dollars at Sep/02.
Panels A-C of Exhibit 4 display the monthly risk-adjusted returns of all three strategies and the market. The relative performance of the strategies is of course the same as that displayed in Exhibit 3 but the figures in Exhibit 4 provide more intuitive results. The strategy based on the PERG ratio outperforms that based on the P/E (PEG) ratio by 11 (2) basis points when there is no rebalancing, by 5 (10) basis points when portfolios are rebalanced every 10 years, and by 7 (16) basis points when portfolios are rebalanced every 5 years, all figures on a monthly basis. The market is outperformed by all three strategies on average though not in every subperiod. Panel D of Exhibit 4 displays the terminal value of a $1,000 investment at the beginning of 1980, compounded at the average risk-adjusted returns shown in panels A-C through the end of Sep/02. Note that these terminal values are expressed in risk-adjusted dollars; that is, they take into account both the returns delivered by each strategy and a penalty (reward) for being more (less) volatile than the market.
4.5. Robustness : Treynor Ratios
The results reported and discussed in the previous section clearly point in the same direction: PERG-based strategies outperform those based on P/Es and PEGs on a risk-adjusted
13 basis. However, it could be argued that return s should be adjusted by risk as measured by each portfolio’s beta rather than by its standard deviation. In other words, it could be argued that riskadjusted returns should be assessed with Treynor ratios rather than with Sharpe ratios, the former defined as a portfolio’s mean return divided by its beta. Exhibit 5. Performance (IV): Treynor Ratios
Investment Period Panel A 1980-02 Panel B 1980-89 1990-99 2000-02 WAvg Panel C 1980-84 1985-88 1990-94 1995-99 2000-02 WAvg P/E 1.62 2.01 1.57 1.14 1.71 2.26 1.84 1.14 2.09 1.14 1.75 PEG 1.69 2.00 1.55 0.19 1.58 2.31 1.58 1.03 2.12 0.19 1.57 PERG 1.72 2.16 1.52 0.67 1.70 2.36 2.03 1.09 2.15 0.67 1.76 Market 1.11 1.47 1.48 -1.53 1.11 1.25 1.69 0.76 2.20 -1.53 1.11
WAvg: Weighted average. All numbers in the table show Treynor ratios defined as mean return over beta.
Exhibit 5 reports the Treynor ratios of all three strategies and the market,12 and largely confirms the results discussed above: A PERG-based strategy outperforms a P/E-based strategy when portfolios are held for the whole sample period and when they are rebalanced every five years (panels A and C).13 It also outperforms a PEG-based strategy in all three scenarios. In short, the superiority of the PERG ratio over the P/E ratio and the PEG is largely independent from the measure of risk used to estimate risk-adjusted returns.
4.6. Downside Risk
The final step of the analysis consists of exploring a PERG ratio based on a different measure of risk, namely, on the downside beta defined in (4). As stated in section 3.2, if the downside beta is used as a proxy for risk, then the PERG would be given by {(P/E)/g}⋅ßD. Exhibit 6 reports for the strategies based on this redefined PERG all the figures reported in the previous exhibits for strategies based on P/Es, PEGs, and beta-based PERGs.
Because the beta of the market portfolio is, by definition, equal to 1, the Treynor ratio for the market is equal to the market’s mean return.
12
P/E-based portfolios, however, slightly outperform those based on PERG ratios when portfolios are rebalanced every 10 years. Note that most of this outperformance is due to the results of the short 2000-02 period.
13
14 Exhibit 6. Downside Risk
Investment Period Panel A 1980-02 Panel B 1980-89 1990-99 2000-02 HPR/WA vg Panel C 1980-84 1985-88 1990-94 1995-99 2000-02 HPR/WAvg Return 4,796.6% 745.7% 646.7% 6.8% 6,642.2% 210.5% 175.6% 97.5% 241.4% 6.8% 6,060.8% TV $48,966 $8,457 $63,149 $67,422 $3,105 $8,556 $16,901 $57,703 $61,608 MR 1.6% 1.9% 1.8% 0.3% 2.0% 1.8% 1.2% 2.2% 0.3% SD 4.8% 4.9% 5.0% 4.9% 4.4% 5.2% 4.4% 4.6% 4.9% SR 32.19 39.36 36.30 6.44 34.04 45.12 35.27 28.11 47.16 6.44 34.99 RAR 1.46% 1.87% 1.41% 0.33% 1.48% 1.97% 1.80% 1.02% 1.90% 0.33% 1.51% RA-TV $52,085 TR 1.72 2.16 1.52 0.67 1.70 2.36 2.03 1.09 2.15 0.67 1.76
$55,080
$59,933
HPR: Holding period return; WAvg: Weighted average. TV: Terminal value; MR: (Arithmetic) mean return; SD: Standard deviation of returns; SR: Sharpe ratio (×100); RAR: Risk-adjusted return; RA-TV: Risk-adjusted terminal value; TR: Treynor ratio. HPR applies only to the ‘Return’ column; WAvg applies to the SR, RAR, and TR columns. TV shows the terminal value of a $1,000-investment in Jan/1980. MR, SD, SR, RAR, and TR in monthly figures. RA-TV shows the risk-adjusted terminal value of a $1,000-investment in Jan/1980.
Comparing the figures in Exhibit 6 with those reported in the previous exhibits for the other three ratios, it follows that the PERG based on downside beta performs, relative to the P/E and the PEG, much as the beta-based PERG does. This implies that the PERG based on downside beta 1) is outperformed by a P/E based strategy in terms of returns; and 2) generally outperforms a P/E-based (and a PEG-based) strategy in terms of risk-adjusted returns.
5. Conclusions
For many years academics and practitioners have been discussing the “value versus growth” issue. Although there seems to be a consensus on the fact that, in the long term, value outperform s growth, there is no agreement about why this is the case. This article tackles a related but different topic, which can be thought of as a “value versus value” issue. P/E ratios are one of the valuation tools most widely used by analysts and the key variable in many value strategies. The simplicity of P/E ratios, however, can be deceiving. There is nothing trivial about choosing an appropriate benchmark P/E, or determining whether the difference between a given P/E and its appropriate benchmark is due to fundamentals or to mispricing. Differences across P/E ratios may be due to many factors but are largely driven by differences in growth and risk. The PEG ratio improves upon the P/E ratio by adjusting the latter by growth. However, the PEG ratio does not make any adjustment for risk; the PERG ratio proposed in this article does.
15 The sample used to assess the empirical usefulness of the PERG ratio is limited and therefore the results reported should be considered tentative. Still, the evidence reported and discussed does show that PERG-based strategies outperform, on a risk -adjusted basis, value strategies based on P/E ratios and PEG ratios. This outperformance occurs regardless of whether portfolios are not rebalanced, rebalanced every 10 years, or rebalanced every 5 years. Due to their simplicity and plausibility, the PEG ratio rapidly became a popular and widely-used valuation tool. However, this ratio ignores the fact that differences across P/Es may be due not only to growth but also to risk, which in turn ignores the fact that all modern financial theory is based on a risk-return trade-off. Furthermore, the evidence reported above does not support using the PEG as the basis of a value strategy. The PERG ratio proposed in this article, which adjusts the P/E ratio by both growth and risk, has an advantage over the PEG ratio: It does take risk into account. That, plus the fact that a PERG-based strategy outperforms on a risk-adjusted basis those based on P/Es and PEGs, should make it an attractive tool to add to the arsenal of valuation tools used by analysts.
16
Appendix
Exhibit A1. Companies and Industries
Company 3M Abbott Laboratories Aflac Albertson's Alcoa Alltel American Electric Power American Express American International Analog Devices Anheuser-Busch Applied Materials AT & T
Automatic Data Processing
Bank of New York Baxter International BB&T Bank Of America Boeing Bristol-Myers Squibb Campbell Soup Caterpillar Chevron-Texaco Chubb Clorox Coca-Cola Colgate-Palmolive Conagra Foods Conoco Phillips CVS Walt Disney Dow Chemical Duke Energy Du Pont Emerson Electric Exelon Exxon Mobil Fannie Mae FleetBoston Financial Ford Motor Gannet General Electric General Dynamics General Mills Gillette General Motors H.J. Heinz Household International Hewlett Packard IBM
Industry Diversified Industry Medical Supplies Life Assurance Food & Drug Retailers Non-Ferrous Metals Telecom Fixed Line Electricity Consumer Finance Other Insurance Semiconductors Brewers Semiconductors Telecom Fixed Line Business Support Banks Medical Supplies Banks Banks Aerospace Pharmaceuticals Food Processors Commercial Vehicles Oil Integrated Insurance Non-life Household Products Soft Drinks Household Products Food Processors Oil Integrated Food & Drug Retailers Leisure Facilities Chemicals, Commodity Chemicals, Commodity Electricity Electrical Equipment Electricity Oil Integrated Mortgage Finance Banks Automobile Publishing & Printing Diversified Industry Defense Food Processors Personal Products Automobile Food Processors Consumer Finance Computer Hardware Computer Services
Company Illinois Tool Works Intel Interpublic Group International Paper Johnson & Johnson JP Morgan Kellogg Kimberly-Clark Ely Lilly Limited Brands Masco McDonalds McGraw-Hill Medtronic Mellon Financial Merck Merrill Lynch Motorola National City Northrop Grumman Omnicom Procter & Gamble Pepsico Pfizer Pharmacia Phillip Morris PNC Financial Services Progress Energy Progressive Raytheon Sara Lee Schlumberger Sears Roebuck Southern Co Southwest Airlines Sprint Fon Group State Street Sysco Target Tenet Healthcare Texas Instruments TXU Union Pacific United Technologies Wachovia Walgreen Wal-Mart Stores Wells Fargo Wrigley William Jr. Wyeth
Industry Engineers Fabricators Semiconductors Media Agencies Paper Pharmaceuticals Banks Food Processors Personal Products Pharmaceuticals Retailers, Soft Goods Building Materials Restaurants & Pubs Publishing & Printing Medical Supplies Banks Pharmaceuticals Investment Banks Telecom Equipment Banks Defense Media Agencies Household Products Soft Drinks Pharmaceuticals Pharmaceuticals Tobacco Banks Electricity Insurance Non-life Defense Food Processors Oil Services Discount Stores Electricity Airlines & Airports Telecom Fixed Line Other Financial Food Processors Discount Stores Hospital Management Semiconductors Electricity Rail, Road, & Fright Aerospace Banks Food & Drug Retailers Discount Stores Banks Food Processors Pharmaceuticals
17
References
Arshanapalli, Bala, Daniel Coggin, and John Doukas (1998). “Multifactor Asset Pricing Analysis of International Investment Strategies.” Journal of Portfolio Management, Summer, 10-23. Bauman, Scott, Mitchell Conover, and Robert Miller (1998). “Growth versus Value and LargeCap versus Small-Cap Stocks in International Markets.” Financial Analysts Journal, March/April, 75-89. Capaul, Carlo, Ian Rowley, and William Sharpe (1993). “International Value and Growth Stock Returns.” Financial Analysts Journal, January/February, 27-36. Chen, Nai-fu, and Feng Zhang (1998). “Risk and Return of Value Stocks.” Journal of Business, 71, 501-535. Easton, Peter (2002). “Does the PEG Ratio Rank Stocks According to the Market’s Expected Rate of Return on Equity Capital?” Working Paper. Estrada, Javier (2002). “Systematic Risk in Emerging Markets: The D-CAPM.” Emerging Markets Review, 3, 365-379. Fama, Eugene, and Kenneth French (1992). “The Cross Section of Expected Stock Returns.” Journal of Finance, 47, 427 -465. Fama, Eugene, and Kenneth French (1996). “Multifactor Explanations of Asset Pricing Anomalies.” Journal of Finance, 51, 55-84. Lakonishok, Josef, Andrei Shleifer, and Robert Vishny (1994). “Contrarian Investment, Extrapolation, and Risk.” Journal of Finance, 49, 1541-1578. Lynch, Peter (1993). Beating the Street. Simon & Schuster. Modigliani, Franco, and Leah Modigliani (1997). “Risk-Adjusted Performance.” JPM, Winter, 4554. Peters, Donald (1991). “Valuing a Growth Stock.” Journal of Portfolio Management, Spring, 4951. Sun, Zhao (2001). “The PEG Ratio and Stock Valuation.” Working paper. Whitbeck, Volkert, an d Manown Kisor (1963). “A New Tool in Investment Decision-Making.” Financial Analysts Journal, May/June, 55-62.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.
|
https://www.scribd.com/document/73560475/The-PERG-Ratio
|
CC-MAIN-2017-04
|
refinedweb
| 7,538
| 59.13
|
Various options of passing data from ASP.NET MVC Controller to View
In ASP.NET MVC framework, we have got various options for passing data from Controller to View. Some of the options that i know and used are listed below :-
1. Use a strongly typed model object
2. Use a dynamic type (using @model syntax)
3.Use a ViewBag
This article focuses on explaining the above three methods of passing data from Controller to View. Let’s create a simple ASP.NET MVC application to demo this one. Since there is a Cricket world cup fever going now, i will be creating a sample MVC application to display list of countries.
I’m adding the below model to the project using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCDemo1.Models { public class Countries { public String Name { get; set; } public string Group { get; set; } public string DressColor { get; set; } public int NoOfTropies { get; set; } } }
I’ll be creating a new controller by name Country to handle various types of views(strongly typed views, loosely typed views and views accessing viewbag objects directly for the model Countries.
In the CountryController.cs, i’m setting up the values for CountryCollection
List<Countries> oCountries = new List<Countries> { new Countries{Name="India",NoOfTropies=2,Group="A",DressColor="Blue"}, new Countries{Name="Australia",NoOfTropies=3,Group="B",DressColor="Yellow"}, new Countries{Name="SouthAfrica",NoOfTropies=0,Group="C",DressColor="Purple"} };
1.Use a strongly typed model object to pass data from Controller to View
In this approach, I’m adding a Controller action by name ‘StrongView’ to return the View for ActionResult.
public ActionResult StrongView() { return View(oCountries); }
Right click on the controller action and Add a View by choosing the Model class, which makes it a Strongly typed view.
Run the Solution and the View with CRUD operations look like below.
At the top of the View, model is referenced strongly which makes it Strongly typed View.
@model IEnumerable<MVCDemo1.Models.Countries>
Now, let’s move to the approach #2.
2. Use a dynamic type (@model syntax) to pass data from Controller to View
Let’s add another controller action by name ‘LooseView’ for passing loosely typed objects from Controller to View.
public ActionResult LooseView() { return View(oCountries); }
Right click on the Controller action, Add View and do not choose any model class, that will make it as dynamically typed.
At the top of the View add a reference to dynamically typed view and Grab the Model data from dynamic object.
@model dynamic @{ ViewBag.Title = "LooseView"; } <h2>LooseView</h2> @foreach(var oCountry in Model) { @oCountry.Name; }
Now let’s move to the approach #3.
3. Use ViewBag to pass the data from Controller to View
Now let’s add a Controller action by name ‘ThirdView’ which sets the Country Collection and returns the View.
public ActionResult ThirdView() { ViewBag.Countries = oCountries; return View(); }
Let’s add a View by name ‘ThirdView’
I’ll be fetching the Model object from ViewBag and rendering it in the View.
@{ ViewBag.Title = "ThirdView"; } <h2>ThirdView</h2> @foreach (var oCountry in ViewBag.Countries) { @oCountry.Name; }
|
http://sundarnarasiman.net/2014/09/01/various-options-of-passing-data-from-controller-to-view/
|
CC-MAIN-2020-50
|
refinedweb
| 519
| 57.06
|
Hello, sorry for asking similar question again, but could you please tell me if the test below start playing the youtube video for you:1. on CHROME.2. on FIREFOX or any other browser.
import { Selector } from 'testcafe';fixture Testtest.page()('Test: Play Youtube video', async t => { await t .wait(20000); });
Test
For me on CHROME video does not start at all:
On any other browser it starts correctly:
Thank you in advance for response!
@Adam,The "YouTube" video passes properly if it runs with the -e argument. Would you please clarify what functionality you wish to test? Do you want to check the video player functionality?
@MarinaI am aware of -e argument, I use it in other tests. Still, the YouTube video autostarts for me only on firefox/edge/opera and it does not on chrome. It is freezed for test duration like on the picture above.
Exactly, I would like to test video player functionality. I have similar video player, in which I need to test whether video has started, subtitles are visible etc.
Below is a recording of the parallel test I did on chrome and firefox. Chrome is on the left (video don't start) and firefox is on the right.
It is possible that you encountered the issue described in the following source:
Would you please try running your test with the "--no-user-gesture-required flag" parameter:
TestCafe: Starting browser with arguments
If this does not help, send me a test which illustrates how you check that the video has been started (e.g., you check for the visibility of the "play" or "pause" button for this).
Unfortunatly running the test with "--no-user-gesture-required" flag did not help.
My test to check if video started that works on firefox, but not on chrome:
import { Selector, ClientFunction } from 'testcafe';
fixture Test
const getYoutubeCurrentTime = ClientFunction (() => { const ytCurrntTimeValue = document.querySelector('.ytp-time-current').innerText; return ytCurrntTimeValue;});
const videoDidNotStart = Error('Video did not start');
test.page()('Test: Play Youtube video', async t => {
await t
.wait(13000);
console.log('Youtube video test-end time: ' + await getYoutubeCurrentTime());
if ((await getYoutubeCurrentTime()) != '0:00') {
console.log('Video Started');
}
else {
throw videoDidNotStart;
}
});
Adam,I've discussed this issue with the team, and we found out that it is related to the following TestCafe limitation:
Run testcafe with https protocol
We are going to overcome it soon.
Ok, thank you for help.
|
https://testcafe-discuss.devexpress.com/t/start-youtube-video-in-testcafe/1215
|
CC-MAIN-2021-39
|
refinedweb
| 400
| 64.41
|
Error in data processing
Hi,
I’ve encountered an error in data processing Expyriment Python 3. However its fine in Python 2. Here is some code:
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
===================== RESTART:
\Py\data_processing.py =====================
Expyriment 0.9.0 (Python 3.6.4)
Traceback (most recent call last):
File "D:\Py\data_processing.py", line 12, in
delimiter=',')
File "C:\Python36\lib\site-packages\expyriment\misc\data_preprocessing.py", line 200, in write_concatenated_data
return Aggregator(data_folder=data_folder, file_name=file_name)\
File "C:\Python36\lib\site-packages\expyriment\misc\data_preprocessing.py", line 301, in init
if not _version[0] == 1 and _version[1] < 6:
TypeError: '<' not supported between instances of 'str' and 'int'
If I try something like this, I got the same error :
100 < '110'
Traceback (most recent call last):
File "<pyshell#0>", line 1, in
100 < '110'
TypeError: '<' not supported between instances of 'int' and 'str'
And here my code to call the concatenated data in CSV (that works fine in Python 2) :
import os
from expyriment.misc import data_preprocessing
folder= os.getcwd() + os.sep + 'data'
data_preprocessing.write_concatenated_data(folder,'New_01',output_file='New_01.csv',delimiter=',')
What should I do?some experts suggest that Python 3 more “bolt” and simple, but I don't think I'm comparing the int and str in my data processing that should be no error emerged.
This is indeed a bug in Expyriment. Thanks for reporting it. It will be fixed in the next version.
|
http://forum.cogsci.nl/index.php?p=/discussion/3705/error-in-data-processing
|
CC-MAIN-2019-18
|
refinedweb
| 262
| 51.24
|
I have been running through most of the discussions on SDN. And figured out that beginners always try to create a copy or Z of standard Fiori applications.
It is not recommended of you to copy standard fiori apps,but its certainly feasible.
Let me take you to a step by step guide on how to do it.
Step1: Download the code from NW portal by executing report /UI5/UI5_REPOSITORY_LOAD in SE38.
You can find the steps in various extension guides/blogs etc. Or follow this link Extending a Fiori App – Simple Use case – Part 2
Step2: Create a application project in Eclipse.(You should have already setup your development environment before this).
Step3: Copy your downloaded code to webcontent folder of your application project. Your folder structure should look like this.
Step4: Change the namespace of Standard Application.
Open Component.js file. You will see that the namespace which SAP follows for this application is hcm.mgr.approve.timesheet .
I am changing this to zhcm.mgr.approve.timesheet.cust . Do it for all the files.
Step5: That’s it. You are done!. You can check the application locally first and than transfer to NW.
Refer this link Extending a Fiori App – Simple Use case – Part 3
Make sure you use below parameter value
SAPUI5.Component=zhcm.mgr.approve.timesheet.cust
Thanks,
Parth Jhalani
Good Document.
Hi Parth,
Nice document. Thanks for sharing !
Regards,
Rohit
Hello Parth,
Thank you for this document. I am trying to copy a standard fiori appliaction “sales order create”. As per the documents i have changed the applcaiton “cus.sd.salesorder.create” to “zcus.sd.salesorder.create”.
but i dont understand what to change in LPD_CUST.
I have below doubt:
1. What is the role of the application namespace ? for example we SO create SAP use- jQuery.sap.declare(“cus.sd.salesorder.create.Configuration”);
2. In LPD_CUST – i have created zrole and assigned my new z application to it then given URL. and Application Alias. what is the role of Additional Information field.
3. What is the role of Semantic Object and Action. Do we have fixed action assigned to each semantic object ? in the application namespace declaration like “cus.sd.salesorder.create.Configuration“. this namespace is combination of semantic object and action ? like in this case salesorder is semantic object and create is action. because when i checked standard application these object and action is maintained.
4. My requirement is i want to copy standard application into z and change the code as per the given requirement.
Thank you in advance to answer my query.
Regards
Anand
Hi Parth,
Hope you are doing well.
I have same issue all the tile configuration and mapping change are not showing in Transport. If new catalogue will create then only the transport its coming inside transport.
Please let me know if you found the solution .
Regards,
Sulekha
|
https://blogs.sap.com/2015/01/14/create-copy-of-standard-fiori-applications/
|
CC-MAIN-2017-30
|
refinedweb
| 480
| 61.22
|
Subject: [Boost-announce] [boost] [log] Boost.Log formal review result
From: Vladimir Prus (ghost_at_[hidden])
Date: 2010-03-24 18:28:30!
On the other hand, some concerns about the ease of use and performance
and implementation details were raised. Of those, some can be easily
addressed as part of normal maintenance, while some seem to require
significant rework and may change the library quite consirably.
Therefore,
the library is accepted subject to several conditions -- listed below
under "Critical issues". Because the changes can be large, I think a
mini-require is required when those issues are addressed. To avoid
delays,
it's probably not necessary to formally schedule and conduct a mini-
review --
just posting a email asking for discussion will be sufficient.
Statistics
==========
There were roughly 300 emails during formal review (I have a mbox
archive
if anybody needs it).
The following persons submitted a review with a vote. Some of votes are
"provisional", this is not reflected below, but affects the list of
critical issues below.
- Boris Schaeling (yes)
- Roland Bock (yes)
- Ralf Globisch (yes)
- Sean Chittenden (yes)
- Darryl Green (no)
- Tom Brinkman (no)
- Barend (yes)
- Sam Gundry (yes)
- Vicente Botet (yes)
- Robert Stewart (yes)
- Alexander Arhipenko (yes)
- "M-Square" (yes)
Critical issues
===============
These issues must be addressed, and be passed through informal mini-
review,
before the library can be added to SVN.
- It appears that the 'trivial' logging is not sufficiently good to just
take and use. The library should provide an out-of-the-box mechanism
that:
- supports channel/severity attributes, without creating new logger
for
each severity. It also should be possible to filter out specific
channel by essentially poking at some "map", and without manually
composing a new filter that checks for a set of allowed channels
sequentally. I believe that at least Christian, Roland, Robert and
myself
requested this.
- has no observable effect on compile time. One second (or more)
that trivial.hpp
imposes is not acceptable.
- outputs to console by default, but permits changing that
- outputs only component/severity/message by default, but probably
permits
changing that.
- By default, the library should try hard to continue working no
matter what errors happen during processign a log record -- including
things like invalid attribute names or types, or other exceptions.
- The library should not reinvent wheels. In particular, custom
implementations
of TSS and RW mutex seems like a very bad idea. Use of a custom lambda
implementation was pointed by many as not great -- we already have a
couple,
so let's not add more to the mix.
- Library interface is too geared towards lambda. In particular,
implementing
formatters/filters as free-standing functions appears to require
considerably
more code. In particular, it should be possible to access an
attribute using a
single function call. Also, logging::extract taking a lambda for
callback
complicates matters, it's desirable to have a more direct variant.
Important issues
================
These issues are important enough to be mentioned here, but can be
addressed as convenient.
- The reported run-time performance can be improved. In particular the
performance with date attributes seems scary and 2x slowdown relative
to some other library in the 'most records are filtered out' case is
also concerning.
- I don't think it was satisfactory explained why 'attr' exists in two
namespaces, as opposed to being a single type that is used for both
formatting and filtering.
Other notes
===========
These issues seem important and should be considered, but might not even
be fixable within the current design.
- Several reviewers said the library is "too flexible" and this makes it
harder to understand. Probably nothing can be done about that at this
point, but interesting data point notwithstanding.
- It was suggested that the library include an API that another Boost
log
may use in a way that permits plugging another logging library should
end user of a Boost so desire. This seems a good idea, but I think
it's
up to Andrey to implement such API or not.
- Alternative design approaches were proposed, in particular (i)
permitting
user log records and templating/basing other components on a user-
defined
record type and (ii) using compile-time indexing to access attributes.
Also, it was proposed that named parameters not be necessary to use
the
library, and a more conventional interface be available.
It does not seem that implementing those suggestions is fully possible
without writing a different library from scratch, so it's up to Andrey
to consider those proposals.
- It was suggested to use newer Spirit to address poor compile times for
the library itself.
Thanks,
Volodya
_______________________________________________
|
http://lists.boost.org/boost-announce/2010/03/0256.php
|
CC-MAIN-2015-48
|
refinedweb
| 764
| 53.21
|
The Plum Hall Validation Suite for C is the industry's favorite set of C programs for testing and evaluating C language compilers (including interpreters). It's ideal for your organization if you are:
If you're responsible for the evaluation of three competing compilers, you can test each compiler with The Plum Hall Validation Suite for C and obtain a detailed inventory of bugs and "features" of each compiler. Because this suite was written in close association with the development of the ANSI/ISO C Standard, it is less likely to overlook significant areas of the language, when compared to internally-developed compiler-comparison benchmarks. And, The Plum Hall Validation Suite for C has no business association with any compiler vendor; it provides an informed but unbiased evaluation tool.
You may be responsible for internal support for several different C compilers. The Plum Hall Validation Suite for C can be used to provide your user community with detailed portability information like "Compiler A lacks such-and-such features and has the following special peculiarities . . .".
To the compiler implementer, The Plum Hall Validation Suite for C provides a collection of carefully chosen test cases -- currently over 56,000 lines of C source, with new sections added regularly under Maintenance. It can supplement internally-developed test suites with a fresh perspective outside the internal "cultural tradition" and has been written with a concern for the modern testing criterion of "positive marginal utility". In other words, each test case has a specific rationale for its inclusion. The Plum Hall Validation Suite for C is not "bulked up" with redundant examples.
The Plum Hall Validation Suite for C was written by specialists in the C language who are well-versed and recognized as major contributors to the development and evolution of the ANSI/ISO C Standard.
Each section of the suite is keyed to the corresponding section of the Standard and Plum Hall is committed to continue making The Plum Hall Validation Suite for C the most authoritative validator for the ANSI/ISO C Standard.
PRODUCT OVERVIEW
Each section of The Plum Hall Validation Suite for C builds upon the correctness established by the previous sections. This description will explain how each section of the suite works, and what assumptions are made about previous sections.
CONFORM - This section tests basic conformance to the C language Standard. By configuring the defs.h file appropriately, a compiler can be checked for conformance to the full ANSI/ISO Standard, or compatibility with several earlier features of C.
EXIN - The EXecutive INterpreter is a script language processor. When it is built and passes its own test set, the script processor is used as a basic tool in subsequent sections of the suite.
COVER - This section uses EXIN scripts to generate self-checking C programs that test coverage of all permutations of operators and data types.
LIMITS - EXIN scripts are used to determine the size of certain compile time limits, e.g., significant length of identifiers or how deeply include files may be nested.
EGEN - The Expression GENerator is a test program, written in C, which generates self-checking expressions of arbitrary complexity. It is the tool used by the STRESS section.
STRESS - Since it is impossible to test all possible legal expressions, a sampling approach is taken. Under the control of EXIN scripts, EGEN is used to generate complex self checking expressions. These can be completely random, or under the control of an expression template.
CONFORM
The CONFORM section of the Suite tests a compiler for conformance to the ANSI/ISO C Standard and consists of five C programs that test all of the required features of the language, preprocessor, and libraries.
The first two programs, ENVIRON and LANG, test the basic language and preprocessor. They are organized according to the section numbers of the ANSI/ISO Standard Document. PREC1 and PREC2 test operator precedence. All C language operators are tested in combination with all others. LIB tests the C library.
Each sub-section of the Standard has a corresponding function in these programs. Each program uses utility routines for checking that 2 integers are equal (iequals), that two addresses match (aequals), etc.
Errors are reported by writing a message of the form:
ERROR in c35.c line 234: (12) != (13)
Each program prints a summary of the form:
***** 2 errors found in LANG *****
CONFORM/ERRTESTS
The Standard requires that diagnostic messages be produced for a source file which violates a syntax or constraint rule. The "error-tests" portion of CONFORM contains little C source files, each of which violates one such rule. Each file is to be compiled in the test environment, and the list of errors is to be checked against the "checklist" files provided in this section.
An example, which violates the syntax rules of 3.5, Declarations:
/* 3.5 Syn SYNTAX-MANDATORY */ /* all sc and types precede the declarator */ main() { { int i, int j; } }
CONFORM/CAPACITY
The Standard requires that each conforming implementation demonstrate that it can meet the translation-time capacity limits. One such program is provided; successfully compiling and executing CAPACITY. C will satisfy this requirement of the Standard (according to the ANSI/ISO Standard, the Vendor is entitled to substitute a different demonstration, if desired).
CONFORM/EXPRTEST
Roughly 1 Megabyte of machine-generated expression-testing code is provided as part of the CONFORM tests. These tests have themselves been tested on many different machine sizes and architectures. They provide greater certainty that the code generator produces accurate, conforming results.
EXIN
Once a compiler has passed the CONFORM section of The Plum Hall Validation Suite for C, it can be assumed that the compiler handles all of the syntax and semantics of the C language. The next step is to build EXIN (the EXecutive INterpreter) and have it pass its own test suite.
EXIN is a script processing language, and is used for many of the more advanced tests in the Suite. The language processed by EXIN is inspired by sh and csh from the UNIX operating system. Source code for EXIN is included as part of the suite. The program has been ported to a wide variety of environments. (If the environment does not provide a mechanism for invoking a sub-process and returning to the parent process, then EXIN can be used to generate test files, but not to control their compilation and execution.)
EXIN takes its input from a file specified on the command line, and processes one line of input at a time. The syntax is similar to the C language. There is one data type, a text string, which can be evaluated numerically by built-in operators. There is high-level control flow (for loops, while loops, if blocks, and switch'es. Other programs can be executed (such as the compiler under test). EXIN can write text to files, and is commonly used to generate C programs.
A few examples of the EXIN language are presented below. When the symbol # is seen, the rest of the line is a comment. Comments will be used to explain what the examples do.
# The primitive data type is a string of characters. Here # a variable 'var' is assigned the string. set> pgm.c end for vars in i j k echo " printf(\"%l \", (long)$vars);" >> pgm.c end echo " }" >> pgm.c $COMPILE $LINK $RUN # End of example
The example produces this C program:
main() { int i; long j; short k; printf("%l ", (long)i); printf("%l ", (long)j); printf("%l ", (long)k); }
It then compiles, links, and executes the program. This is a very simple example, but it illustrates the principle by which EXIN scripts are used to generate and test C programs.
These examples present only a small part of the facilities of EXIN. It is a very powerful language, which is used throughout the Suite to automate long sequences of testing.
COVER
Once built, EXIN can be used to run the scripts in the COVER section. These scripts generate exhaustive coverage of simple expressions in the C language. "Data sets" are collections of data declarations and initializations used in the generation of a self-checking C program. The "scalar" data set, for example, contains declarations for:
char, unsigned char, signed char short, unsigned short int, unsigned int long, unsigned long float, double, long double
At the heart of the COVER section is an EXIN script which, given two data sets and a C language operator, generates all possible permutations. C operators (both unary and binary) can be covered with this script. There are options to declare the variables as either auto or static. Other data sets can be added as needed, but the current list of data sets is:
The COVER section contains scripts which allow the generation of C programs which check all possible permutations of:
These scripts can be restarted at any point. Each program generated by the COVER scripts reports errors of the form:
auto scalar plus auto scalar at line 234: (12) != (13)
Each program also prints a summary of the form:
***** 2 errors in auto scalar plus auto scalar *****
Here is an example of the kind of program generated by the COVER scripts. The data sets were chosen as scalar vs. scalar, and the operator is "plus" (binary +).
#include "types.h" main() { extern char *Filename; auto CHAR Ac = 7; #ifdef ANSI auto SCHAR Asc = 8; #endif auto SHORT As = 9; auto INT Ai = 10; auto UCHAR Auc = 11; auto USHORT Aus = 12; auto UINT Aui = 13; auto LONG Al = 14; auto ULONG Aul = 15; auto FLOAT Af = 16; auto DOUBLE Ad = 17; #ifdef ANSI auto LDOUBLE Ald = 18; #endif /* a second distinct data set would go here */ Filename = " auto scalar plus auto scalar "; iequals( __LINE__, Ac + Ac, 14 ); iequals( __LINE__, Ac + Ac, 14 ); #ifdef ANSI iequals( __LINE__, Ac + Asc, 15 ); iequals( __LINE__, Asc + Ac, 15 ); #endif iequals( __LINE__, Ac + As, 16 ); iequals( __LINE__, As + Ac, 16 ); iequals( __LINE__, Ac + Ai, 17 ); iequals( __LINE__, Ai + Ac, 17 ); iequals( __LINE__, Ac + Auc, 18 ); iequals( __LINE__, Auc + Ac, 18 ); iequals( __LINE__, Ac + Aus, 19 ); iequals( __LINE__, Aus + Ac, 19 ); iequals( __LINE__, Ac + Aui, 20 ); iequals( __LINE__, Aui + Ac, 20 ); lequals( __LINE__, Ac + Al, 21L); lequals( __LINE__, Al + Ac, 21L); lequals( __LINE__, Ac + Aul, 22L); lequals( __LINE__, Aul + Ac, 22L); dequals( __LINE__, Ac + Af, 23.); dequals( __LINE__, Af + Ac, 23.); /* .... excerpted from a 400 line file .... */
LIMITS
The purpose of the LIMITS section of the Suite is to determine the value of certain compile time limits. The ANSI/ISO standard specifies a set of "minimum maximums" that a conforming implementation must meet (see 2.2.4.1).
This section contains a set of scripts that determine what the actual value of these limits are (above or below the minimum requirement).
EGEN
EGEN is the Expression GENerator. Since it is impossible to test all possible C language expressions, the Suite provides this tool for generating complex expressions, and code to check that the right answer is calculated.
After passing the previous sections of the Suite, a compiler should be trustworthy in calculating the results of simple expressions. EGEN relies on this to generate self-checking expressions of arbitrary complexity. Each complex expression has its value calculated from the simpler components that make it up. For example, a compiler generating code for the expression
(a*b) + (c*d)
might have an error in keeping track of multiple registers and get the wrong answer. But calculated as
temp1 = a*b; temp2 = c*d; temp1+temp2
the right answer is more likely, given that expressions of this complexity have been exhaustively tested in the COVER section. By decomposing a complex expression into simpler pieces, EGEN expects to get the "right answer" and use that to check the compiler's result on the full complex expression. EGEN can also be invoked in a debugging mode that shows how each value in the decomposed expression was calculated.
EGEN requires several pieces of information:
The EGEN data set is a text file which describes the variables to be used in generating the expressions. Several data sets are provided with the STRESS section, and others can be created as desired.
The template is a list of operators or special tokens that specify the kind of expression to be generated. For example:
+ - binary plus operator - - binary minus operator * - binary multiply operator neg - unary minus operator () - parenthesis for grouping @ - EGEN randomly selects an operator {list} - EGEN randomly selects an operator from the list
The expression templates can contain all C language unary or binary operators, as well as the special operators @, (), and {}.
An example of an EGEN command line is:
egen -R23 -Dintegers -10 (+) * (-)
This sets the random number seed to 23, uses the data set defined in the file integers, and generates 10 self-checking statements of the form
(variable + variable) * (variable - variable)
EGEN randomly assigns variables from the data set to each variable, and tracks what the final value should be. Given the command line:
egen -Dinteger -10 {+= -= *=} @
EGEN would generate 10 statements of the form
variable OP1 variable OP2 variable
where each variable is randomly chosen from the data set, OP1 is randomly chosen from the set {+= -= *=}, and OP2 is randomly chosen as any C operator. EGEN generates code for the expression, code to check the result of the expression, and code to check the results of any side-effects.
Here is a real example from the output of
egen -Dinteger -4 {+= -=} {neg com} ( @ ) main() { extern char *Filename; int true = 1, false = 0; auto unsigned int ui; static unsigned int *pui; auto int i; static int *pi; auto short s; static short *ps; auto char c; static char *pc; auto unsigned long ul; static unsigned long *pul; auto long l; static long *pl; register int rint1; register int rint2; ui = 3; pui = &ui; i = 10; pi = &i; s = 13; ps = &s; c = 20; pc = &c; ul = 65000; pul = &ul; l = 130000; pl = &l; rint1 = 1; rint2 = 2; Filename = "main"; iequals( __LINE__, rint2 -= - (ui < c), 3); iequals( __LINE__, rint2, 3); iequals( __LINE__, *pi += - (s >>= ui), 9); iequals( __LINE__, *pi, 9); iequals( __LINE__, s, 1); iequals( __LINE__, rint1 += ~ (true ? *pc : *ps), -20); iequals( __LINE__, rint1, -20); lequals( __LINE__, *pl -= - (*pc /= *pui), 130006L); lequals( __LINE__, *pl, 130006L); iequals( __LINE__, *pc, 6); report(__FILE__); }
STRESS
The STRESS section is a collection of EXIN scripts and data setsfor EGEN. In the example below, the atest.gen data set has declarations for all C integral types. The script is intended to be run "forever" (e.g., in the background on a multi-tasking operating system). Periodically it can be checked to see if any compiler errors have been detected.
# INTX4 - this script generates expressions of # complexity 4 (4 operators) in a continuous loop. # It is intended to be run in the background, with # results being checked periodically. # It is invoked as "exin intx4 -<number> # The number is a random number seed. # Each generated file is limited to 5 statements # because they tend toward 0 if too many are # calculated into 1 file # $$<variable> does a rescan after expansion # Configuration section: set FILE = 'test$SEED' set COMPILE = "cc -c $FILE.c" set COMPILE_OK = '$error == 0' set LINK = 'cc -c $FILE.o -o $FILE' set LINK_OK = '$error == 0' set RUN = '$FILE' set RUN_OK '$error == 0' set CLEANUP = 'rm $FILE.*' set LOGFILE = 'intx4.log' if ($# != 1) echoerr "syntax: exin intx4 -<number> exit 1 end set SEED = $1 while (1) egen -R$SEED -Datest.gen -5 @ @ @ @ > $$FILE.c $$COMPILE if ($$COMPILE_OK) $$LINK if ($$LINK_OK) $$RUN >> $LOGFILE if ($$RUN_OK) $$CLEANUP end end end # each time through, the SEED += 1 set SEED = $eval($SEED + 1) end
|
http://www.plumhall.com/stec1.html
|
crawl-001
|
refinedweb
| 2,601
| 50.46
|
We are happy to share that Azure Service Bus is now able to send events. You can create Azure Event Grid subscriptions for your Service Bus namespaces, listen to these events, and react to the events by starting a receiver. With this feature, Service Bus can be used in reactive programming models.
Today, Azure Service Bus sends events for two scenarios:
- Active messages with no listeners available
- Deadletter messages available
Additionally, it uses the standard Azure Event Grid security and authentication mechanisms.
How often and how many events are emitted?
If you have multiple queues and topics/subscriptions in the namespace, you get at least one event per queue and subscription. The events are immediately emitted if there are no messages in the Service Bus entity and a new message arrives, or every two minutes unless Azure Service Bus detects an active receiver. Message browsing does not interrupt the events.
By default Azure Service Bus emits events for all entities in the namespace. If you want to get events for specific entities only, see the following filtering section.
Filtering, limiting from where you get events
If you want to get events from only one queue or one subscription within your namespace, you can use the "Begins with" or "Ends with" filters provided by Azure Event Grid. In some interfaces, the filters are called “Pre” and “Suffix” filters. If you want to get events for multiple, but not all queues and subscriptions, you can create multiple Azure Event Grid subscriptions and provide a filter for each.
In the current release, this feature is only for Premium namespaces and is available in all Event Grid regions. We will add support for Standard namespaces at a later point in time.
- To learn more, please review the full technical documentation.
- If you want to get started today, please see the examples provided on our documentation page.
|
https://azure.microsoft.com/ja-jp/blog/azure-service-bus-now-integrates-with-azure-event-grid/
|
CC-MAIN-2019-22
|
refinedweb
| 312
| 61.36
|
A new Early Access Preview build for WebStorm 2017.1 (171.3224) is now available! You can download it here and install it side-by-side with your current stable WebStorm version, or if you have the previous EAP build from the last week, you should soon get a notification in the IDE about a patch update.
Completion and navigation for Vue components
WebStorm now provides code completion for Vue components inside the template tag.
Cmd-click (or Ctrl-click on Windows and Linux) on the component name to jump to its definition.
Improved integration with ESLint
We’ve updated our integration with ESLint: now the IDE now communicates with ESLint as with a language service. We hope you’ll notice some performance improvements when working with ESLint.
Wrap variable declaration with single var
With a new code style option you can configure whether you’d like to keep long variable declarations with single var (or let, or const) on one line or on multiple lines.
This option is available under Preferences | Editor | Code Style – JavaScript or TypeScript – Wrapping and Braces – Variable declarations..
Please report your feedback to our issue tracker. To get notifications of new EAP builds as they become available, subscribe to the EAP channel in Preferences | Appearance & Behavior | System Settings | Updates.
Your WebStorm Team
I have a problem with Resolve conflicts dialog. Generally all >> and << links are gone. It's not usable anymore!
See screenshots
Thank you for reporting WEB-25509, we’ll take a look at this problem
In my regular javascript.js files I have the context menu option: “Fix ESLint problems” however this context menu option is not available in .vue files. Even though I get ESLint warnings and errors just fine in .vue files. Also hitting Alt+Enter on the warning pops up the dialog and allows me to select a fix.
(Webstorm 2017.1.4)
ESLint doesn’t support auto-fix on plugins with preprocessors like the one for Vue.js. Here’s a issue on the ESLint tracker:
Hi,
I use Vue with TypeScript and I separate my template files from components, so each template (which has a .vue extension) has a tag which points on TS component file.
I’ve created a custom component and I want to use it in my template; I’ve imported it in @Component() decorator in my TS file, started to type its name in a template, got a correct autocompletion hint, chose it and…BOOM! autocomplete removed the link to my component file from the template script tag, and instead put there some TS code that it thinks should be there (including imports, @Component() decorator, class declaration etc). What should I do to stop this behavior?
Hi Gregory,
can’t recreate.
My App.vue:
<template>
<div id="app">
<img src="./assets/logo.png" alt="">
</div>
</template>
<script lang="ts" src="./App.vue.ts"></script>
App.vue.ts:
import {Component, Vue} from 'vue-property-decorator';
@Component({
components: {
HelloWorld
},
})
export default class App extends Vue {
}
When I start typing
<Helloin App.vue, component is completed, but no additional code is added to the
<script>section.
Note that
HelloWorldcomponent is also defined in .ts file referenced from HelloWorld.vue.
Please can you record a screencast that shows up the issue?
No problem. Where do you want me to send it? (264kb)
You can upload it to some file server and provide a link here. For example, you can put it on our ftp server ( – anonymous login, .uploads directory has no permissions to list/download files, only for upload)
The FTP is inaccessible (from my browser at least), so here you have a youtube link:
Can’t reproduce using similar steps and code:( Please can you share a sample project that shows up the issue?
|
https://blog.jetbrains.com/webstorm/2017/02/webstorm-2017-1-eap-171-3224/?replytocom=295681
|
CC-MAIN-2019-51
|
refinedweb
| 627
| 63.49
|
File Systems
You can add volumes to systems without adding separate drive letters for each new volume, similar to the way Distributed file system (Dfs) links together remote network shares. Volume mount points are robust against system changes that occur when devices are added or removed from a computer.
A volume mount point can be placed in any empty folder of the host NTFS volume. The mounting is handled transparently to the user and applications. The version of NTFS included with Windows 2000 must be used on the host volume. However, the volume to be mounted can be formatted in any Windows 2000-accessible file system, including NTFS, FAT16, FAT32, CDFS, or UDF.
One volume can host multiple volume mount points. This allows the local administrator to easily extend the storage capacity of any particular volume on a Windows 2000 system. Users on the local system or connecting to it over a network can continue to use the same drive letter to access the volume, but multiple volumes can be in use simultaneously from that drive letter, depending on the folder used on the host. Windows 2000 automatically prevents resolution problems caused by changes in the internal device name of the target volume. A mount point is the target volume in the same way a drive letter is the target volume.
A useful example of volume mount points can be seen in the following scenario. A user recently installed Windows 2000 onto a relatively small drive C, and is concerned about unnecessary use of storage space on drive C. The user knows that the default document folder, My Documents, is on drive C, and she uses her computer extensively to create and edit digital photos, vector-based graphic art, and desktop publishing (DTP) files. Knowing that these types of documents can quickly consume a lot of disk storage space, the user creates a volume mount point to drive C under the My Documents folder called Art. Any subfolder of the Art folder actually resides on another volume, saving space on drive C.
Note
You need local Administrator rights to complete this task.
To create a volume mount point under C:\My Documents
If necessary, add a new hard disk to create a new volume.
Log on to the computer with an account that has local Administrator rights.
In Control Panel, double-click Administrative Tools .
In Administrative Tools , double-click Computer Management .
In Computer Management , double-click Disk Management .
If you want to use a previously existing volume as the volume mount point, skip to step 12. Otherwise, right-click in the unallocated space on the disk in which you want to create a new volume and choose Create Partition to start the Create Partition wizard. Follow the steps in the wizard to create an extended partition. Allocate at least as much space as you need to contain all of your art and DTP files.
You can also create another primary partition, and then skip to step 8.
Note
You do not have to use an entire extended partition for just one logical volume. Since extended partitions can contain many logical volumes, you might want to use all the remaining unallocated space for the extended partition and then allocate a portion of that for the volume to be used in this scenario. You can later create another one or more logical volumes out of the remaining free space in the extended partition.
If the disk has been upgraded to dynamic disk, you cannot see the options primary partition, extended partition, and logical volume in Disk Management. These terms only apply to basic disks. On dynamic disks you create simple volumes for this task. For more information about primary partitions, extended partitions, logical volumes, basic disks, and dynamic disks, see Disk Concepts and Troubleshooting in this book.
If you created an extended partition in step 6, right-click in the extended partition, and then choose Create Logical Drive . Use as much disk space for the new logical volume as you need to contain all of the games you plan to install on this computer.
At the Assign Drive Letter or Path screen of the Create Partition wizard, choose the option Mount this volume at an empty folder that supports drive paths , and then click Browse .
In Windows Explorer, expand drive C, navigate to the folder C:\Documents and Settings\ username \My Documents, and then click New Folder . In the folder name placeholder in the Explorer tree, type over the default name New Folder with the name Art , and then click OK . Click Next at the Create Partition wizard.
Format the new volume with NTFS by using the default-sized allocation units (NTFS is not required, but it is recommended). Enter a volume label for the new volume, or clear the default label in the Volume label text box for none. Click Next twice to finish the wizard. The new volume is automatically formatted after the volume is created.
Volumes and volume mount points can be addressed by multiple names in the file system namespace. To make the mounted volume accessible directly through a drive letter in Windows Explorer, in Disk Management, right-click the mounted volume, select Change Drive Letter and Path , and then click Add to assign a drive letter. You can also mount this volume to another folder on the same or another host volume. Click OK when done. Skip to step 15 of this procedure.
To mount previously existing volumes as a volume mount point on a folder of another volume, right-click the volume to be mounted, select Change Drive Letter and Path , and then click Add .
Select Mount in the NTFS folder , and then click Browse .
In Windows Explorer, expand drive C, navigate to the C:\Documents and Settings\ username \My Documents folder, click New Folder , and in the folder name placeholder in the Explorer tree, type over the default name New Folder with the name Art. Click OK twice to close the wizard.
In Windows Explorer, navigate to the C:\Documents and Settings\ username \My Documents\Art folder and create new folders such as Photos, LineArt, and DTP for the graphic arts documents.
Any bitmap files are accessed in the Photos folder on the user's computer, the volume mount point used to attach the volume to the My Documents folder on drive C directs all read and write requests to the Photos folder on the mounted volume. Any files stored in the My Documents\Art folder are stored in the root folder of the mounted volume. Any other folder created normally within Windows Explorer under the My Documents folder still resides on drive C.
Note
In Windows 2000, only NTFS folders are marked as junctions to provide a mapping function from one folder name to another. NTFS files are not marked in this manner.
The tool Mountvol can identify and manage volume mount points. For more information about Mountvol, see File System Tools later in this chapter.
|
https://technet.microsoft.com/en-us/library/cc938934.aspx
|
CC-MAIN-2018-05
|
refinedweb
| 1,162
| 60.85
|
Opened 11 years ago
Closed 11 years ago
Last modified 10 years ago
#547 closed enhancement (duplicate)
[patch] XMLRPC support for django
Description
I have a working XMLRPC implementation for django. Here is how to use it:
Add the following to urlpatterns:
urlpatterns = patterns('', (r'^xmlrpc/', 'myproject.apps.xrpc.views.xrpc.serve'), )
I have borrowed code heavily from SimpleXMLRPCServer, which comes with standard python distribution, so we have the same API as described in its documentation, other than the constructor. I have added some security enhancement, so every published method must contain a public attribute which must be set to True before we would serve it.
Here is an example xrpc.py:
from django.contrib.xmlrpc import SimpleXMLRPCView class c: def f(self): return "public func, will be served." f.public = True def g(self): return "private, wont be served." serve = SimpleXMLRPCView() serve.register_instance(c())
Finally an example of how to use it:
>>> import xmlrpclib >>> server = xmlrpclib.Server('') >>> server.f() 'public func, will be served.' >>> server.g() Traceback (most recent call last): File "<interactive input>", line 1, in ? File "C:\Python24\lib\xmlrpclib.py", line 1096, in __call__ return self.__send(self.__name, args) File "C:\Python24\lib\xmlrpclib.py", line 1383, in __request verbose=self.__verbose File "C:\Python24\lib\xmlrpclib.py", line 1137, in request headers ProtocolError: <ProtocolError for localhost:8000/xrpc/: 500 INTERNAL SERVER ERROR> >>>
Will attach the patch shortly.
Attachments (4)
Change History (12)
Changed 11 years ago by
Changed 11 years ago by
Oops, attached older patch, use this one.
comment:1 Changed 11 years ago by
Awesome! Just what I need here! Thanks!
Changed 11 years ago by
SimpleXMLRPCServer is better than xmlrpclib.SimpleXMLRPCServer!
comment:2 Changed 11 years ago by
I was working with source of xmlrpclib-1.0.1, later saw an enhanced version of SimpleXMLRPCServer in standard distribution [only tested this patch with Python 2.4]. The latest patch is much cleaner, very little code copying, and supports "register_introspection_functions" [which reminds me I have not made the xmlrpc introspection methods from the parent "public", expect another patch shortly], and is more object oriented. Now we have two Views in contrib.xmlrpc, SimpleXMLRPCView and SafeXMLRPCView, later looks for "public" attribute to be True before calling, while former does not.
Changed 11 years ago by
this one with public attribute set for SafeXMLRPCView instrospection methods.
comment:3 Changed 11 years ago by
This isn't necessary for 1.0.
comment:4 Changed 11 years ago by
comment:5 Changed 10 years ago by
How is it possible to raise an exception with this implementation of xmlrpc? I would like to send an error code (<fault>...) instead of a generic HTTP 500 server error code.
comment:6 Changed 10 years ago by
Hi all
im fine, gl all!
comment:7 Changed 10 years ago by
comment:8 Changed 10 years ago by
How is it possible to raise an exception with this implementation of xmlrpc? I would like to send an error code (<fault>...) instead of a generic HTTP 500 server error code.
Raise an instance of the
xmlrpclib.Fault class. Example here: Pingbacks: XML-RPC and Django.
Here is the patch.
|
https://code.djangoproject.com/ticket/547
|
CC-MAIN-2016-40
|
refinedweb
| 528
| 58.79
|
QML is a high level, scripted language. Its commands, more correctly elements, leverage the power and efficiency of the Qt libraries to make easy to use commands that perform intuitive functions. Draw a rectangle, display an image at a position and so on. Behind these elements are complex C++ libraries that efficiently perform the action. As with any graphical application, always consider that this ability to easily build graphically rich applications means that some care may be needed to prevent performance problems.
The language also allows more flexibility of these commands by using Javascript rather than C++ to add new layers of logic to your application. Javascript is easier to learn than C++ and can be embedded into the QML files or imported from a separate file.
In QML the types of various 'objects' are referred to as elements.
An element usually has various properties that help define the element. For example, if we created an element called Circle then the radius of the circle would be a property.
The basic syntax of an element is
Here we are defining a new object. We specify its 'type' first as SomeElement. Then within matching braces { ... } we specify the various parts of our element.
The id is a unique identifier for the element, it must start with a lower case letter and only contain letters, numbers and underscores. It is this particular object's name. If this SomeElement element was a Rectangle instead and it was one of many then the optional unique id would allow us to manipulate each element individually.
Each visual element is ultimately based on, or inherits from, an element called Item. Item has certain properties and actions that may be useful. The properties have default values so you need only specify the ones you will need.
Take a simple element such as a Rectangle. It has an id, we will call it myRectangle, it has a width and a height. Imagine that we want a rectangle that is 500 pixels by 400 pixels in the x and y directions (horizontal by vertical).
We can implement this Rectangle with these properties this way
This is a valid QML script. To run it, copy it and save it to a file, say myexample.qml, and on the command line run the following command:
qmlviewer myexample.qml
On Mac OS X, open the "QMLViewer" application instead and open the myexample.qml file, or run it from the command line:
QMLViewer.app/Contents/MacOS/QMLViewer myexample.qml
It will create a very boring rectangle in its own window.
We can now add some color and text to make a Hello World QML program.
Rectangle has the property color to produce a background color.
Text is handled by a different element called Text. We need to create a Text object inside the Rectangle and set its text property to "Hello World!". So to set the text to "Hello world" and the background colour to light gray,
From now on we will not always show the import statement for Qt but it should still be there when you create your QML scripts.
To make our Hello World example a little nicer set the position of the text to be at pixel position x = 100, y = 100 within the displayed window. This position belongs to the Text element so we set the position inside its definition. Note that we separate different QML statements on the same line with a semi-colon, or we could have simply put each statement on a new line
Not only did we reposition the text, but the text was altered by adding HTML tags to change the font size. The text color was also changed from the default black to dark green by using a standard string for the color's SVG name.
We could also have used a hexadecimal string for the RGB (red-green-blue, as #rrggbb) values of the color similar to the method used in HTML. For example, mostly blue with a green tint,
All of these changes occurred within the Text object which is the scope of these property changes.
Other objects may use the information but it belongs to the element where the property has been defined.
To add an image to our little application we use the Image element. An Image uses a path to an image file, and has properties to control the aspect ratio, the image size, to tile the area amongst others. The source of the image, the path to the file, is a URL. Therefore the file can be local: mydir/myimage1.png. Or it can be remote: "".
This displays the image, as we would expect, at the top left of the window. The position of the default x = 0, y = 0 coordinate. The example here uses a PNG file, but it could have been one of various supported formats, including JPG and GIF.
Let us reposition the image and enlarge it. Place it at the same 'x' offset as the "Hello world again" text, but put it another 50 pixels below the text, also make it 150 by 150 pixels in size,
Adding the Hello World example, with the text and the image example we can write a simple piece of QML that starts to look a bit better.
The result is still quite simple
Using absolute positioning, such as saying x = 100 and y = 150, works well until the user or developer stretches or increases the size of the window. Then the positions need to be recalculated. What would be nice would be a relative means of positioning of objects in a window or rectangle. For example, we want to place an image at the bottom of a rectangle, we would like to specify the image's location as the 'bottom of the window', not a specific coordinate. We can do this with the anchors property, which objects inherit from Item.
The anchors property is really a property group. It is a collection of related properties. It has properties within it which can be used by means of the dot notation.
The dot notation uses object ids and property names to use a particular object or property. Say I have a rectangle r1, which contains a rectangle r2, which contains an Item item1, which has an 'x' property I want to change. I just use the dot notation to identify it: r1.r2.item1.x
If we want to position an image at the bottom of the rectangle it is inside. I have to specify that the bottom of the image is also at the bottom of the rectangle
This places the logo at the bottom left of the window.
We would like it centered and not touching the bottom of the window, for aesthetic reasons. For the centering we use the horizontalCenter property, and to prevent the touching of the image to the bottom of the rectangle, the bottomMargin property is used. So the new actions for the script are
Encoded into QML the script becomes
Run this and resize the window. You will see that now the position of the image adjusts during the resize.
You can also add another object say a block of descriptive text and place it above or below the image or to the side. This code places some text just above the image
Note: anchors is a property group, to be used within the object. When referencing these properties from another object we use the property directly, instead of saying:
myRectangle.anchors.top // Wrong
we use
myRectangle.top // Correct
We can transform a graphical object to get additional effects. Rotate a piece of text by 180 degrees to display upside-down text. Rotate an image by 90 degrees to lay it on its side. These transformations require additonal information.
For rotation, the additional information includes: the origin relative to the object being rotated, the axis of rotation, and the angle in degrees to rotate the image through in a clockwise direction. The axis does not have to be the z-axis, the line between your eyes and the image, it could be along the vertical y-axis or the horizontal x-axis. We have three dimensions to play with. For simplicity in this example we will rotate about the z-axis by 90 degrees in a negative direction, anti-clockwise.
Rotation of text was also suggested. It could also be useful to scale the text. We can do both. The transform property is a list of Transform elements, so using the list syntax
myList: [ listElement1, listElement2, ... } ]
we can produce a list of transformations.
The text will be rotated by 45 degrees anti-clockwise and scaled vertically by a factor of 1.5 and by 1.2 horizontally.
Using the example above as the basis for this we have,
The code block in image1 starting with transform specifies that the transform property will be a Rotation through -90 degrees, which is anti-clockwise, about the z-axis running through the center of the image at (75,75), since the image is 150 x 150 pixels.
The other transformation available is Translate. This produces a change in position of the item.
Note: In a list of transformations the order of the transformations is important. In the above example try swapping around the Scale transform with the Rotation transform, remember to remove or add the comma. The results are acceptable for our little test but not the same.
Animation in QML is done by animating properties of objects. Properties that are numbers, colors, Rectangles, points and directions. In QML these are QML Basic Types named as real, int, color, rect, point, size, and vector3d. There are a number of different ways to do animation. Here we will look at a few of them.
Previously we have used a rotation transformation to change the orientation of an image. We could easily animate this rotation so that instead of a straight rotation counter-clockwise of 90 degrees we could rotate the image through a full 360 degrees in an animation. The axis of rotation wont change, the position of the center of the image will not change, only the angle will change. Therefore, a NumberAnimation of a rotation's angle should be enough for the task. If we wish for a simple rotation about the center of the image then we can use the rotation property that is inherited from Item. The rotation property is a real number that specifies the angle in a clockwise direction for the rotation of the object. Here is the code for our animated rotating image.
The transformOrigin: Item.Center is redundant since this is the default axis of rotation anyway. But if you change Center to BottomRight you will see an interesting variation.
Also if instead the Rotation transformation had been used then we would have more control over the various parameters. We could vary the axis, to be not just a different offset from the z-axis but along the y-axis, x-axis or combination. For example, if the task had been to animate the rotation about the y-axis passing through the center of the image then the following code would do it.
Here there is a rectangle 600 by 400 pixels. Placed within that rectangle is an image 100 by 100 pixels. It is rotated about the center of the image about the y-axis so that it looks as if it is rotating about an invisible vertical string holding it up. The time it takes to complete the rotation is 3 seconds (3,000 milliseconds). The NumberAnimation is applied to the angle taking it from 0 (no change) to 360 degrees, back where it started. Strictly speaking it isn't necessary to go from 0 to 360 since the same location is duplicated, but it makes it easier to read in this example and it has no visible effect on the animation. The number of loops that the animation will execute is set to Animation.Infinite which means that the animation is in an endless loop.
To see an interesting variation. Change the axis to axis { x:1; y:1; z:1 }. This is a line coming from the center of the image downwards to the right and out of the screen. Although the change is simple the rotation seems complex.
For a more complex animation we will need two images. The first image will be placed at the center of a window (Rectangle) and the second image will be at the upper left of the window. The animation will move the second image from the top left of the window to the bottom right. In doing so we will be animating the position and the size of the image.
First create two images
We will add to 'image1' a SequentialAnimation from x = 20 to the target of x = 450. The 'from' values will be used because we will be repeating the animation, so the object needs to know where the original position is, both x and y. The SequentialAnimation of x will set it to repeat by indicating that the number of animation loops is infinite, meaning that the 'loop' counter will be set to a value Animation.Infinite that indicates an endless cycle. Also there will be a NumberAnimation to vary the numeric property between the x values and over a given duration. After the NumberAnimation there will be a PauseAnimation that will pause the animation for 500 milliseconds (half a second) simply for the visual effect.
A similar block of code is written for the animation of the 'y' value of the position.
We will also animate the scale of the object, so as it goes from top left to bottom right of the window it will become smaller until about midway, and then become larger. To complete the animation we will set the 'z' values of the images. 'z' is the stacking order, the z-axis effectively points out from the screen to your eyes with the default value of 'z' being 0. So if we set the Rectangle to have z with value zero, just to be sure, and image1 to 1 and image2 to 2 then image2 will be in the foreground and image1 in the background. When image1 passes image2 it will pass behind it. The completed code looks like
The easing.type has many options, expressed as a string. It specifies the kind of equation that describes the acceleration of the property value, not necessarily position, over time.
For example, InOutQuad means that at the start and the end of the animation the 'velocity' is low but the acceleration or deceleration is high. Much like a car accelerating from stop, and decelerating to stop at the end of a journey, with the maximum speed being in the middle. Examine the easing documentation and the various graphs that show the effect. The horizontal axis, 'progress', can be thought of as time. The vertical axis is the value of the particular property.
In discussing animation we need to describe three objects: State, MouseArea and Signals. Although independent of the animation elements, animation delivers some of the best examples that illustrate these new elements.
A state is a defined set of values in the configuration of an object and often depends on the previous state. For example, a glass could be in a state we call 'HalfFull' if it is being filled with a liquid and has reached half of its total capacity. We could also have a state called HalfEmpty which is the state that occurs when the amount of liquid drops to half of the glass's capacity. Both states represent the same amount of liquid, but we consider them different. Likewise, states in a program represent not just values but may include how the current values were reached.
When a state changes a transition occurs. This is an opportunity to make changes or take actions that depend on the movement to the new state. For example, if we had a scene in the country where the state variable has two states "daylight" and "night". Then when the state changes to "night" at this transition the sky would be made dark, stars would be shown, the countryside would be darkened. And when the state changes to "daylight" the opposite changes would be made: the sky is now blue, the scenery is green, there is a sun in the sky.
Here is a simple QML program that shows the change of state in the above example. We have two rectangles, the top one is the 'sky' and the bottom one is the 'ground'. We will animate the change from daylight to night. There will be two states, but we only need to define one since 'daylight' will be the default state. We will just go to 'night' by clicking and holding the left mouse button down, releasing the mouse button will reverse the process
Several new things appear in this sample. Firstly, we use a MouseArea element to detect mouse clicks in the mainRectangle. Secondly, we use the list notation [ thing1 , thing2, ... ] to build a list of states and a list of transitions.
MouseArea defines a region that will respond to mouse clicks. In this case we are only concerned with when the mouse is pressed or not pressed, not the particular button or other details. The area of the MouseArea is the entire main window, mainRectangle, so that clicking anywhere in this region will start the animation. Since we are using the 'pressed' mouse state, then the animation will move from 'daylight' to 'night' only while the mouse button remains pressed.
When the button is released the 'daylight' state is entered and the transition from 'night' to 'daylight' is triggered causing the animation to run. The transition specifies the duration in milliseconds of the ColorAnimation, while the state specifies the color of the new state.
The PropertyChanges command is the way that we nominate which properties will change in a change of state, and what new value the property will take. Since, for example, we want the 'sky' region to turn to dark blue and the 'ground' region to turn to black for the 'night' state, then the rectangles for those regions are the 'target' and the property in the target is 'color'.
Signals are simply events that can be hooked up to actions we want performed. In QML they are usually preceded by the word 'on', for example in the animation using a MouseArea the signal was onPressed. If you look at the C++ documentation you will see a lot of talk about Signals and Slots. Signals are connected to Slots. The signal represents an event and the Slot is the function that does something based on that event. You can also have Signals connected to other Signals, so that one Signal (event) triggers another Signal (event), and so forth. It is nice to know this is what happens beneath the QML layer but not essential for using QML.
Most elements do not have Signals associated with them. However, a few like the Audio element have many signals. Some of the Audio signals are used to represent events such as when the audio is stopped, play is pressed, paused, and reaching the end of the media. They allow the developer to connect, for example, the press of a user interface button (perhaps a MouseArea) to some QML that will handle this event.
In the Qt examples/declarative/ui-components folder you will find a folder dialcontrol which contains the dialcontrol example.
In essence this small application has a sliding bar that you can slide using a mouse, and a graphical dial that responds to the position of the slider.
The code for the example is in two parts: Dial.qml and dialcontrol.qml.
Dial.qml can be found in the content sub-directory. It defines a Dial component similar to an odometer. Eventually, the example will hook up a slider component so that moving the slider will change the position of a needle on the dial.
The code for the Dial, identified by the name of the file, contains four images in overlapping order: the background (numbers and divisions), the shadow of the needle, the needle itself, and finally the 'glass' overlay (containing transparent layers).
The needle_shadow.png image has a Rotation assigned to the transform attribute of the Image. The rotation is set to match the angle of the needle image angle value needleRotation.angle. Both the needle and the needle_shadow have the same default x and y values but the rotation origin for the needle is slightly different so that a shadow will be evident as the needle moves.
Image { x: 96 y: 35 source: "needle_shadow.png" transform: Rotation { origin.x: 9; origin.y: 67 angle: needleRotation.angle } }
And the needle
Image { id: needle x: 98; y: 33 smooth: true source: "needle.png" transform: Rotation { id: needleRotation origin.x: 5; origin.y: 65 //! [needle angle] angle: Math.min(Math.max(-130, root.value*2.6 - 130), 133) Behavior on angle { SpringAnimation { spring: 1.4 damping: .15 } } //! [needle angle] } }
The final image is the overlay which simply has a position defined.
Image { x: 21; y: 18; source: "overlay.png" }
dialcontrol.qml in the examples/declarative/ui-components/dialcontrol directory is the main file of the example. It defines the visual environment that the Dial will fit into. Because the Dial component and the images live in the content sub-directory we will have to import this into dialcontrol.qml. So the start of the file looks like
import Qt 4.7 import "content"
The visual space is bound by a 300 by 300 pixel Rectangle which is given a gray color. Inside this rectangle is our component Dial and a Rectangle. Inside the rectangle called 'container' is another rectangle with the interesting name 'slider'.
Rectangle { color: "#545454" width: 300; height: 300 // Dial with a slider to adjust it Dial { id: dial anchors.centerIn: parent value: slider.x * 100 / (container.width - 34) } Rectangle { id: container anchors { bottom: parent.bottom; left: parent.left right: parent.right; leftMargin: 20; rightMargin: 20 bottomMargin: 10 } height: 16 radius: 8 opacity: 0.7 smooth: true gradient: Gradient { GradientStop { position: 0.0; color: "gray" } GradientStop { position: 1.0; color: "white" } } Rectangle { id: slider x: 1; y: 1; width: 30; height: 14 radius: 6 smooth: true gradient: Gradient { GradientStop { position: 0.0; color: "#424242" } GradientStop { position: 1.0; color: "black" } } MouseArea { anchors.fill: parent drag.target: parent; drag.axis: Drag.XAxis drag.minimumX: 2; drag.maximumX: container.width - 32 } } } }
The Dial component, named 'dial, is anchored to the center of the main rectangle. The value attribute of 'dial' is set to a value based on the 'slider' horizontal position and the 'container' width. So changes to the 'slider' position will change the Dial value which is used in Dial to compute the rotation of the needle image. Notice this piece of code in Dial where the change in value modifies the position of the needle.
angle: Math.min(Math.max(-130, root.value*2.6 - 130), 133) Behavior on angle { SpringAnimation { spring: 1.4 damping: .15 } }
This is part of the needleRotation that rotates the needle and causes the rotation of its shadow. SpringAnimation is an element that modifies the value of that rotation angle and mimics the oscillatory behavior of a spring, with the appropriate spring constant to control the acceleration and the damping to control how quickly the effect dies away.
The 'container' is light gray with a color gradient defined using GradientStop. The gradient is applied vertically. If you need a horizontal gradient then you could apply the vertical gradient and then rotate the item by 90 degrees.
The 'slider' is dark gray and also has a vertical color gradient. The most important thing about the 'slider' is that it has a MouseArea defined, which specifies a drag.target on itself along the X-axis. With minimum and maximum values on the X-axis defined. So we can click on the 'slider' and drag it left and right within the confines of the 'container'. The motion of the 'slider' will then change the value attribute in Dial as discussed already.
Also notice the use of a radius value for a rectangle. This produces rounded corners. That is how the 'container' and 'slider' are displayed with a pleasant rounded look.
|
http://idlebox.net/2010/apidocs/qt-everywhere-opensource-4.7.0.zip/qml-intro.html
|
CC-MAIN-2013-48
|
refinedweb
| 4,070
| 63.8
|
sonarsonar
A tantivy based search engine for Node.js
ExampleExample
const Sonar ={const catalog = './data'const schema =const index = await catalogconst docs =await indexconst results = await indexconsole}{returnid: '0' title: 'Hello world!' body: 'tell me more'id: '1' title: 'Ola mundo!' body: 'que pasa pues'}{returnname: 'title'type: 'text'options:indexing: record: 'position' tokenizer: 'en_stem'stored: truename: 'body'type: 'text'options:indexing: record: 'position' tokenizer: 'en_stem'stored: truename: 'id'type: 'text'options: indexing: null stored: true}
InstallationInstallation
npm install @archipel/sonar
A
postinstall script automatically tries to download a precompiled binary for the rust/tantivy part. If unsuccessfull the script will try to compile it if a rust toolchain is present.
APIAPI
const catalog = new Sonar(storage)
storage is a file system path where the index will be stored.
const index = await catalog.openOrCreate(indexName, schema)
indexName is a string to identifiy the index. It should only contain characters valid in file system paths.
schema is the index schema, expressed as a JSON-serializable object following the tantivy schema definition. Documentation is not centralized atm, see example above.
const index = await catalog.create(indexName, schema, opts)
Create an index. Will throw if an index by this
indexName exists already.
opts are:
ram: If true create an in-memory index
await index.add(docs)
docs is an array of documents with the same structure as the index schema.
const results = await index.query(query, [limit], [snippetField])
Query the index. At the moment only string queries are supported, see tantivy docs for details on the supported grammar.
limit is the max number of documents to return (default 10).
snippetField is the name of a field for which to return a result snippet with keywords highlighted (as HTML, with
<b> tags)
const results = await catalog.multiQuery(query, indexes)
Query all indexes in the catalog.
indexes is an array of index names.
To be expanded
Implementation detailsImplementation details
The rust part is a wrapper around tantivy. It compiles to a binary. The binary is invoked with a storage path as only argument. It listens for newline-delimited JSON messages on STDIN, and replies in the same format.
The node part spawns the rust binary and communicates over the STDIO pipe. It adds a higher-level API around this simple RPC mechanism.
A npm
postinstall step will try to download a precompiled binary of the rust part from Github releases. The binaries are compiled and deployed via Travis. If it cannot find a matching binary, it will try to compile if a rust toolchain is available. If the environment variable
RUST_ENV=development is present,
cargo run (without
--release) will be invoked instead.
|
https://www.npmjs.com/package/@arso-project/sonar-tantivy
|
CC-MAIN-2022-05
|
refinedweb
| 437
| 50.94
|
[ aws . lex-runtime ]:
In addition, Amazon Lex also returns your application-specific sessionAttributes . For more information, see Managing Conversation Context .
See also: AWS API Documentation
See 'aws help' for descriptions of global parameters.
post-text --bot-name <value> --bot-alias <value> --user-id <value> [--session-attributes <value>] [--request-attributes <value>] --input-text <value> [--cli-input-json <value>] [--generate-cli-skeleton <value>]
--bot-name (string)
The name of the Amazon Lex bot.
--bot-alias (string)
The alias of the Amazon Lex bot.
--user-id (string)
The ID of the client application user. Amazon Lex uses this to identify a user's conversation with your bot. At runtime, each request must contain the userID field.
To decide the user ID to use for your application, consider the following factors.
- The userID field.
--session-attributes (map)
Application-specific information passed between Amazon Lex and a client application.
For more information, see Setting Session Attributes .
Shorthand Syntax:
KeyName1=string,KeyName2=string
JSON Syntax:
{"string": "string" ...}
--request-attributes (map)
Request-specific information passed between Amazon Lex and a client application.
The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes with the prefix x-amz-lex: .
For more information, see Setting Request Attributes .
Shorthand Syntax:
KeyName1=string,KeyName2=string
JSON Syntax:
{"string": "string" ...}
--input-text (string)
The text that the user entered (Amazon Lex interprets this.
intentName -> (string)
The current user intent that Amazon Lex is aware of.
slots -> (map)
The intent slots that Amazon Lex detected from the user input in the conversation. .
key -> (string)
value -> (string)
sessionAttributes -> (map)
A map of key-value pairs representing the session-specific context information.
key -> (string)
value -> (string)
message -> (string)
The message to convey to the user. The message can come from the bot's configuration or from a Lambda function.
If the intent is not configured with a Lambda function, or if the Lambda function returned Delegate as the dialogAction.type.
messageFormat -> (string)
The format of the response message. One of the following values:
- PlainText - The message contains plain UTF-8 text.
- CustomPayload - The message is a custom format defined by the Lambda function.
- SSML - The message contains text formatted for voice output.
- Composite - The message contains an escaped JSON object containing one or more messages from the groups that messages were assigned to when the intent was created.
dialogState -> (string)
Identifies the current state of the user interaction. Amazon Lex returns one of the following values as dialogState . The client can optionally use this information to customize the user interface.
- ElicitIntent - Amazon Lex wants to elicit user intent. For example, a user might utter an intent ("I want to order a pizza"). If Amazon Lex cannot infer the user intent from this utterance, it will return this dialogState.
- ConfirmIntent - Amazon Lex is expecting a "yes" or "no" response. For example, Amazon Lex wants user confirmation before fulfilling an intent. Instead of a simple "yes" or "no," a user might respond with additional information. For example, "yes, but make it thick crust pizza" or "no, I want to order a drink". Amazon Lex can process such additional information (in these examples, update the crust type slot value, or change intent from OrderPizza to OrderDrink).
- ElicitSlot - Amazon Lex is expecting a slot value configured for the intent has successfully fulfilled the intent.
- ReadyForFulfillment - Conveys that the client has to fulfill the intent.
- Failed - Conveys that the conversation with the user failed. This can happen for various reasons including that the user did not provide an appropriate response to prompts from the service (you can configure how many times Amazon Lex can prompt a user for specific information), or the Lambda function failed to fulfill the intent.
slotToElicit -> (string)
If the dialogState value is ElicitSlot , returns the name of the slot for which Amazon Lex is eliciting a value.
responseCard -> (structure)
Represents the options that the user has to respond to the current prompt. Response Card can come from the bot configuration (in the Amazon Lex console, choose the settings button next to a slot) or from a code hook (Lambda function).
version -> (string)The version of the response card format.
contentType -> (string)The content type of the response.
genericAttachments -> (list)
An array of attachment objects representing options.
(structure)
Represents an option rendered to the user when a prompt is shown. It could be an image, a button, a link, or text.
title -> (string)The title of the option.
subTitle -> (string)The subtitle shown below the title.
attachmentLinkUrl -> (string)The URL of an attachment to the response card.
imageUrl -> (string)The URL of an image that is displayed to the user.
buttons -> (list)
The list of options to show to the user.
(structure)
Represents an option to be shown on the client platform (Facebook, Slack, etc.)
text -> (string)Text that is visible to the user on the button.
value -> (string)The value sent to Amazon Lex when a user chooses the button. For example, consider button text "NYC." When the user chooses the button, the value sent can be "New York City."
|
https://docs.aws.amazon.com/cli/latest/reference/lex-runtime/post-text.html
|
CC-MAIN-2018-47
|
refinedweb
| 840
| 58.69
|
Opened 4 years ago
Closed 2 years ago
Last modified 2 years ago
#8065 closed defect (duplicate)
Database schema is incorrect or casts are needed (PostgreSQL 8.4 database)
Description
The database schema you use during upgrade seems to have incorrect field types:
SCHEMA = [ Table('subscription', key='id')[ Column('id', auto_increment=True), Column('time', type='int64'), Column('changetime', type='int64'), Column('class'), Column('sid'), Column('authenticated', type='int'), Column('distributor'), Column('format'), Column('priority', type='int'), Column('adverb') ], Table('subscription_attribute', key='id')[ Column('id', auto_increment=True), Column('sid'), Column('authenticated', type='int'), Column('class'), Column('realm'), Column('target') ] ]
Specifically:
- What type should have 'authenticated' field? It's declared as int but used as bool. Due to that in many places I have a crash like following:
File "/usr/local/lib/python2.6/dist-packages/TracAnnouncer-0.12.1.dev-py2.6.egg/announcer/model.py", line 350, in do_select """, (sid,authenticated,klass)) File "/usr/lib/python2.6/dist-packages/trac/db/util.py", line 122, in execute return self.cursor.execute(sql_escape_percent(sql), args) ProgrammingError: operator does not exist: integer = boolean LINE 5: AND authenticated=true ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Or maybe the filed type is correct but explicit type casts should be added indeed?
- What type should have 'time' fields?
File "/usr/local/lib/python2.6/dist-packages/TracAnnouncer-0.12.1.dev-py2.6.egg/announcer/model.py", line 79, in do_insert subscription['class'])) File "/usr/lib/python2.6/dist-packages/trac/db/util.py", line 122, in execute return self.cursor.execute(sql_escape_percent(sql), args) ProgrammingError: column "time" is of type bigint but expression is of type timestamp with time zone LINE 5: VALUES (CURRENT_TIMESTAMP, CURRENT_TIMESTAM... ^ HINT: You will need to rewrite or cast the expression.
I have fixed that with
VALUES (EXTRACT(EPOCH FROM CURRENT_TIMESTAMP), EXTRACT(EPOCH FROM CURRENT_TIMESTAMP), %s, %s, %s, %s, %s, %s, %s)
But I don't know if it's the correct way.
Probably there are other similar bugs that should be fixed as well.
Attachments (3)
Change History (17)
comment:1 follow-up: ↓ 2 Changed 4 years ago by olistudent
Changed 4 years ago by olistudent
comment:2 in reply to: ↑ 1 Changed 4 years ago by dbely
Replying to olistudent:
I tried to fix the issues you mentioned above. Attached patch is what I'm running at the moment. Don't know if I catched up all errors...
btw. The authenticated field in trac's session table is int, too.
Thanks. This part looks like to be working. Since then I've found another similar problem: "delete ticket <number>" command crashes trac-admin with error
File "/usr/local/lib/python2.6/dist-packages/Trac-0.12.2dev_r10363-py2.6.egg/trac/ticket/admin.py", line 841, in do_remove ticket.delete() File "/usr/local/lib/python2.6/dist-packages/Trac-0.12.2dev_r10363-py2.6.egg/trac/ticket/model.py", line 421, in delete listener.ticket_deleted(self) File "/usr/local/lib/python2.6/dist-packages/TracAnnouncer-0.12.1.dev-py2.6.egg/announcer/subscribers.py", line 833, in ticket_deleted self.env, klass, 'ticket', ticket.id) File "/usr/local/lib/python2.6/dist-packages/TracAnnouncer-0.12.1.dev-py2.6.egg/announcer/model.py", line 326, in delete_by_class_realm_and_target @env.with_transaction(db) File "/usr/local/lib/python2.6/dist-packages/Trac-0.12.2dev_r10363-py2.6.egg/trac/db/api.py", line 73, in transaction_wrapper fn(ldb) File "/usr/local/lib/python2.6/dist-packages/TracAnnouncer-0.12.1.dev-py2.6.egg/announcer/model.py", line 334, in do_delete """, (realm, klass, target)) File "/usr/local/lib/python2.6/dist-packages/Trac-0.12.2dev_r10363-py2.6.egg/trac/db/util.py", line 65, in execute return self.cursor.execute(sql_escape_percent(sql), args) ProgrammingError: operator does not exist: text = integer LINE 5: AND target = 508 ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. ProgrammingError: operator does not exist: text = integer
I have fixed this with
def delete_by_class_realm_and_target(cls, env, klass, realm, target, db=None): @env.with_transaction(db) def do_delete(db): cursor = db.cursor() cursor.execute(""" DELETE FROM subscription_attribute WHERE realm = %s AND class = %s AND target = %s - """, (realm, klass, target)) + """, (realm, klass, str(target)))
but probably that's not the only place affected.
Changed 4 years ago by stephen.anderson@…
Alternate patch that should work on everything except SQLite
comment:3 Changed 4 years ago by anonymous
One problem with olistudent's patch is I don't think EXTRACT(EPOCH...) works on anything but Postgres. I've attached an alternate patch that calculates times the same way that tickets do.
The problem with it is my patch uses a table type of "boolean", which the Trac db adapter for SQLite currently can't handle - SQLite turns booleans into numeric values, and the adapter can't cast them back.
Changed 4 years ago by stephen.anderson@…
Updated (merged) patch that should work on all DBs, and fixes the error on ticket delete
comment:4 Changed 4 years ago by stephen.anderson@…
I've merged olistudent's changes together with mine and uploaded it as a new patch, which should:
- Work on all DBs
- Fix the ticket delete problem (which was caused by trying to refer to page.name instead of ticket.id within the Subscriber)
comment:5 follow-ups: ↓ 7 ↓ 10 ↓ 14 Changed 3 years ago by sgeulette
Hi, I have all those problems and the proposed patch corrects all. Why doesn't patch the code ? I have tried to commit but it's forbidden...
comment:6 Changed 2 years ago by anonymous
comment:7 in reply to: ↑ 5 Changed 2 years ago by rjollos
- Cc hasienda added; anonymous removed
Hi, I have all those problems and the proposed patch corrects all. Why doesn't patch the code ? I have tried to commit but it's forbidden...
The plugin hasn't been maintained in some time, but now the goal must be to make sure we are fixing it the correct way, and that it works on all supported DBs, rather than pushing a fix which corrects one problem and creates another. For that, you will have to bear with us, while we make sure to get the correct fix in place. We appreciate your patience and feedback when we get a fix in place.
comment:8 follow-up: ↓ 9 Changed 2 years ago by rjollos
- Resolution set to duplicate
- Status changed from new to closed
There are 3 issues discussed in this ticket:
- The authenticated variable is not properly cast from a bool to an int in model.py. This issue is documented in #10384.
- There is concern that non-naive timestamps are not correctly cast to bigint. This issue is documented in #7975.
- Error deleting tickets, which also appears to be a casting problem. This issue is documented in #8577.
Since all of the issues in this ticket have been captured at finer granularity in other tickets, this one is being closed as a duplicate, and concerned parties are asked to follow the cited tickets.
comment:9 in reply to: ↑ 8 Changed 2 years ago by hasienda
- Keywords patch database API added
Since all of the issues in this ticket have been captured at finer granularity in other tickets, this one is being closed as a duplicate, and concerned parties are asked to follow the cited tickets.
Thanks Ryan for starting ticket triage and linking related issues for ease of tracking issues down to the root cause and resolving it.
Ok, but should anyone still want to re-open, please change ticket owner to myself, or expect no response for quite a long time.
comment:10 in reply to: ↑ 5 Changed 2 years ago by hasienda
Hi, I have all those problems and the proposed patch corrects all. Why doesn't patch the code ? I have tried to commit but it's forbidden...
Almost there. I really appreciate the work done in this ticket. The fix is quite complete, but i.e. it doesn't care for existing wrong values in the Trac db table, right? So this fix has to go in concert with a clean-up script to set a known-good state. I'll have it ready in a few days as part of a major db code rework. Stay tuned.
comment:11 Changed 2 years ago by hasienda
(In [12302]) TracAnnouncer: Part 7 of 7 - Finally: Go from present to future, refs #5774, #7975, #8065, #9742 and #10384.
Now we've bridged the gap and provide an upgrade path for each historic schema revision of this plugin, while data migration is incomplete yet, especially regarding subscription attributes stored in session_attribute (before v3). Due to component name changes the conversion will be rather complicated, and therefore corresponding research and development is postponed to a future date and will largely depend on explicit demand as well.
(Due to erroneously writing #8056 this didn't get here.)
comment:12 Changed 2 years ago by hasienda
(In [12303]) TracAnnouncer: Convert type to match db table definitions, refs #7975, #8065 and #10384.
These changes are based on work by olistudent, Stephen Anderson and rea. I made sure, that we respect PEP8 as well, at least as far as Trac core does.
Thanks to all of you for testing, reports and suggestions towards a portable fix, and - ultimately - patience to get it finally resolved.
comment:13 Changed 2 years ago by hasienda
(In [12304]) TracAnnouncer: Correctly convert id for ticket resources, refs #8065 and #9154.
I tried to fix the issues you mentioned above. Attached patch is what I'm running at the moment. Don't know if I catched up all errors...
btw. The authenticated field in trac's session table is int, too.
|
http://trac-hacks.org/ticket/8065
|
CC-MAIN-2015-06
|
refinedweb
| 1,639
| 55.95
|
41480/how-to-get-sql-configuration-in-spark-using-python
You can get the configuration details through the Spark session. What you have to do is, first create a spark session and then use the set command to get the configuration details. For example:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('abc').getOrCreate()
spark.sql("SET -v").show(n=200, truncate=False)
First create a Spark session like this:
val ...READ MORE
You aren't actually overwriting anything with this ...READ MORE
you can access task information using TaskContext:
import org.apache.spark.TaskContext
sc.parallelize(Seq[Int](), ...READ MORE
In case Yarn does not support schemes ...READ MORE
The glom function is what you are looking for:
glom(self): ...READ MORE
Hi,
I am trying to run following things ...READ MORE
Instead of spliting on '\n'. You should ...READ MORE
You can also use the random library's ...READ MORE
You will need to use Spark session ...READ MORE
Try the below-mentioned code.
sparkR.session()
properties <- sql("SET -v")
showDF(properties, ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.
|
https://www.edureka.co/community/41480/how-to-get-sql-configuration-in-spark-using-python?show=41481
|
CC-MAIN-2021-49
|
refinedweb
| 201
| 52.46
|
Examine the Components of Structured Investment Products
Opponents of structured investment products in the UK love to talk up the risks and then in a solemn voice intone that they’re fiendishly complex and the work of clever rocket scientists out to diddle the poor unsuspecting investor.
Some structured investments are, indisputably, poorly built, horribly complex and of debateable value (especially those sold on main street by big banks and mutuals). But, in reality most products sold direct to investors through advisers or listed on a stock exchange are fairly transparent in their construction.
Peer under the bonnet of nearly all structured investments and you find a common set of components; you don’t need to worry too much that they exist just understand what’s involved.
Add up these differing components to a structured product and you can quickly see that an issuer can derive a number of different sources of income or capital gain (premiums from issuing the barrier put, forgone dividends contained within the call that tracks an index, plus the difference between the zero coupon bond value at maturity less the sum paid upfront), which all go towards funding the cost of the upside call plus any bank charges and fees.
Discover the call option
The most important working bit of a structured investment component is a call option. This derivative-based option pays the upside return via the annual defined return (say, 5 per cent per annum) or the geared participation rate (say, 5 times the index return).
Underwriting an option that promises to pay out, say, 5 per cent per annum for the next five years doesn’t come free! The call option costs the structured-product issuer real, hard money and other parts of the structure have to pay for it.
Luckily this isn’t completely a black and white case of a call issuer funding the 5 per cent per annum for the next five years. The call option may perhaps track the FTSE 100 index, which can be good news for the call option issuer.
Some profit is to be had by selling away the likely flow of dividends that an investor would have received if the option had tracked the underlying index. Over a five-year period, for instance, the combined companies within the FTSE 100 index may pay out as much as 20 per cent in compound dividend return.
The issuer of the call option pockets that return as part payment for guaranteeing to make an upside return, in turn selling on that dividend participation in the dividend futures markets.
In addition, remember that the call option may never be triggered; that is, markets fall disastrously and the barrier is breached. If that’s the case, the call option is never used, no return is ever paid out and the issuer of the (upside) call option simply pockets the premium income and moves on to the next deal.
In these circumstances guaranteeing to pay out 5 per cent per annum on the upside may seem like a reasonable bet.
Enjoy the downside: The put option
Another option lurking around is called a put option, which is linked to the barrier that’s usually set at around 50 per cent or 40 per cent of the initial index level of the FTSE 100 or S&P 500 when the structure is issued.
In reality, this barrier is a downside or put option, which means that someone (probably a pension fund) has been willing to write an option that pays out a generous premium in return for making a big profit as markets dive by more than 50 per cent over the duration of the structure.
If the barrier isn’t breached the option expires worthless and the structured-product issuer pockets the premium to help pay its costs and fund the cost of the call option. The premium from writing these downside options isn’t huge but pension funds are keen buyers because these options give them some opportunity to make money in a collapsing stock market.
Get insurance: The zero coupon bond
Sitting at the heart of the zero coupon bond structure is a bond the bank issues behind the structured product. In effect, this bond guarantees that your initial investment (say, £100) is paid back in full as long as the barrier isn’t breached. Think of it as the insurance policy on paying you back your initial investment.
But insurance doesn’t come free and the bank has to fund it by going to the markets using something called a zero coupon bond. This bond is like any other bond issued by a bank with one big exception – it doesn’t pay a coupon every year but rolls up the annual cost at maturity.
Assume the bank wants to make a payout of £100 in five years’ time to fund your structured product. Given its current credit rating it discovers that it can issue a zero coupon bond that promises to pay out £100 in five years’ time but which costs just £80 today; that is, the £20 difference is the cost of funding that loan through annual interest rolled up over five years.
A risky bank (that is, one that is regarded as more likely to have problems repaying its debts by the markets) may discover that its high yields work in its favour – it may only have to pay £70 today to make £100 in five years’ time. The key, though, is that the zero coupon bond issued by the bank (it hopes) pays out the initial investment of the investor.
The difference between the eventual cost of the zero coupon bond (£100) and the initial cost (between £70 and £80) represents the cost of borrowing, which is in turn ploughed back into the structured investment to pay for the upside call option.
|
http://www.dummies.com/how-to/content/examine-the-components-of-structured-investment-pr.html?cid=RSS_DUMMIES2_CONTENT
|
CC-MAIN-2015-40
|
refinedweb
| 978
| 56.93
|
Download presentation
Presentation is loading. Please wait.
Published byNicholas Hayes Modified over 3 years ago
1
E-FILING of applications & returns under COMPANIES Act, 1956
Saturday, 17th August, 2013 E-filing issues under Companies Act, 1956 A Presentation by KAUSHIK M. JHAVERI PRACTISING COMPANY SECRETARY CS KAUSHIK M JHAVERI
2
DISCLAIMER Views contains in the Presentation
are the personal views of presenter and should not be construed as Professional Advice. To Avoid any doubts, Participants are requested to Cross Check all prevailing facts/ laws & Notifications from the Regulators. CS KAUSHIK M JHAVERI
3
who do not know how to Read or write……..
The ILLITERATE of the 21st CENTURY are not those ………. who do not know how to Read or write…….. but those who refuse……. to Learn, Unlearn and Relearn. Arthur Koestler CS KAUSHIK M JHAVERI
6
BOMBAY HIGH COURT TO HAVE STARTED E-COURTS IN MUMBAI
On the occasion of Independence Day Bombay HC started the 1st ever E-Court facility The E-courts is a CG initiative to computerize district and subordinate courts To begin with – all matters on original side pertaining to Company Court i.e. proceeding u/s 391 of Companies Act, 1956 Advocates to lodge soft copies of the proceedings by pen drive/ Compact Disc Date of presentation of such pen drive will be deemed to be date of presentation for all purpose including for the purpose of limitation. However , being the initial stage, advocates will also lodge a hard copy of the above petition with the soft copy Under the said project 2,249 courts in 969 court complexes are expected to be computerized by March 31, 2014 6 CS KAUSHIK M JHAVERI 6
7
Pre – requisites Hardware and Software for e-filing
Windows 2000 / Windows XP/ Windows Vista/ Windows 7 Web Browser-Internet Explorer v6.0 and above Internet access Adobe Reader V 9.4 ( Software is freely available on MCA Portal for day to day use)- (For filling up Eforms) WinZip 8.0 - (For opening the downloaded Eforms) Java Runtime Environment (JRE)- (For uploading the Eforms on MCA website.) Printer (for printing paid copy of challan) Digital Signature Scanner (for scanning of documents to be filed as attachments to e Form (Scanning to be done in 200 dpi to avoid MB problem) CS KAUSHIK M JHAVERI 7 7
8
CORPORATE IDENTITY NUMBER [CIN]
Components of CIN: 1. U – Unlisted Company e.g.- U MH 1997 PLC or L – Listed Company e.g- L MH 1973 PLC 2. 5 Digit Code Number – As per the activity of the Company. 3. Name of State in which Company is registered in Two letters e. g MH for Maharashtra , WB for West Bengal etc. CS KAUSHIK M JHAVERI
9
CORPORATE IDENTITY NUMBER [CIN] (Conti…)
4. Year of Incorporation. e.g. a.) U45203WB2007PTC112537 b.) U15174GJ1996PTC029369 5. Status of the Company i.e Private/Public/ Section 25 Company/Foreign Subsidiary Company e.g PTC/PLC etc. 6. Six Digit Company Registration Number. E.g U15174GJ1996PTC029369 CS KAUSHIK M JHAVERI
10
CIN OF DIFFERENT TYPES OF COMPANIES.
SR. NO. TYPE OF COMPANY [Sample] CIN 1. Private Company Red Chillies Entertainments Private Limited U92130MH2002PTC135790 2. Unlisted Public Company IDFC Asset Management Company Limited U65993MH1999PLC123191 3. Listed Public Company Hindustan Unilever Limited L15140MH1933PLC002030 4. Section 25 Company Bombay Incorporated Law Society of India U99999MH1895NPL000121 CS KAUSHIK M JHAVERI
11
CIN OF DIFFERENT TYPES OF COMPANIES (Cont…)
SR. NO. TYPE OF COMPANY CIN 5. Subsidiary of Foreign Company incorporated in India. Emhart Technologies India Private Limited U72900MH2008FTC186575 6. Part IX Company Expanded Polymer Systems Private Limited U24134MH2007PTC175657 7. FCRN of Foreign Company having branch in India Richards Hogg Lindlay (India) Limited (Company Incorporated in Hong Kong) F00888 CS KAUSHIK M JHAVERI
12
Company Master Data Company Master data is statement providing basic and key information relating to each company Registered with Registrar of Companies of respective states across India. It includes following details: 1. CIN 2. ROC Code – (State in which company is Registered) 3. Registration Number 4. Company Category : (For e.g. Company Limited by Guarantee/ Company Limited Shares) 5. Company Subcategory : (For e.g. Indian Non – Government Company/ Company Licensed under Section 25/ Subsidiary of Foreign Company ) CS KAUSHIK M JHAVERI
13
Company Master Data (Cont)
6. Class of Company : (Whether Private/ Public) 7. Authorized & Paid up Capital 8. Number of Members ( Applicable to Section 25 Company) 9. Date of Incorporation 10. Registered Office Address 11. ID of the company 12. Whether Listed (At Stock Exchange) or not 13. Date of Last AGM 14. Date of Balance Sheet last filed 15. Status of the Company- Active, inactive, merged etc. CS KAUSHIK M JHAVERI
14
MASTER DATA OF PRIVATE LTD. COMPANY
CS KAUSHIK M JHAVERI
15
MASTER DATA OF PUBLIC LTD. COMPANY
CS KAUSHIK M JHAVERI
16
MASTER DATA OF SEC.25 COMPANY
CS KAUSHIK M JHAVERI
17
DIRECTOR’S IDENTIFICATION NUMBER (Revised Process w.e.f 25.12.2012)
Every Individual either Indian or NRI intending to be appointed as director of an Indian company or the existing Directorship is required to make an application for allotment of DIN DIN is mandatory pre-requisite for filing of every E-forms under Companies Act. With effect from 27th March, 2011, only online application of DIN is being accepted. CS KAUSHIK M JHAVERI 17
18
REQUIREMENTS FOR OBTAINING DIRECTOR’S IDENTIFICATION NUMBER (DIN)
I. Requirement of obtaining DIN of Indian /Foreign Directors Scanned copies of the following documents duly attested by Practising Company Secretary or Chartered Accountant should be attached. A. IDENTITY PROOF (Any one) PAN Card (Mandatory for Indian Directors), Driving License, Passport (Mandatory for Foreign Director), Voter Id Card B. RESIDENCE PROOF (Any one) Driving License, Passport, Voter Id Card, Telephone Bill, Ration Card, Electricity Bill, Bank Statement C. One Passport Size Photograph (Scanned in JPG format) D. Valid and active ID of the Director. E. Mobile Number of Applicant. F. Whether Resident in India or not G. Education Qualification of Applicant. H. Current Occupation of Applicant CS KAUSHIK M JHAVERI
19
REQUIREMENTS FOR OBTAINING DIRECTOR’S IDENTIFICATION NUMBER (DIN)
Note: In Case of Indian Director, Identity Proof provided should contain the Father’s Name in it else any other proof which contains Father’s name should be provided separately as under. Birth Certificate Marriage Certificate Any other proof which contains Father’s Name In case of Foreign Director, Fathers name proof is not required. CS KAUSHIK M JHAVERI
20
Revised Procedure for Obtaining On- line DIN
1. E-Form DIN-1 has to be filed with all filled up information with duly attested Identity and Residence proof as mentioned in earlier slides. Physical documents are discontinued for submission at DIN Cell, New Delhi. 2. The eForm DIN - 1 shall have to be digitally signed and shall be uploaded on MCA21 portal. CS KAUSHIK M JHAVERI
21
Digital Signature on DIN Form
CS KAUSHIK M JHAVERI
22
Additional requirement in DIN 1
New Amendment & Introduction - Copy of the verification by applicant in Form DIN - 1 The format of verification is provided in the Annexure – 1 to DIN Form. Affidavit from the applicant has to be notarized : Indian Applicant – On non- judicial stamp paper of Rs. 100/- Foreign Applicant - In the Home Country of the Applicant CS KAUSHIK M JHAVERI
23
I further confirm that:
VERIFICATION OF THE APPLICANT IN CASE OF FORM DIN – 1 AS PER ANNEXURE 1 OF THE DIN RULES I, _______, (name of applicant) Son/ Daughter* of ________ (applicant’s father’s name), born on _______, (date of birth), resident of _________ (present residential address of the applicant) hereby confirm and verify that the particulars given in the Form DIN – 1 are true and correct and also are in agreement with the documents being attached to the Form DIN -1. I further confirm that: The photograph and documents being attached to the Form DIN – 1 belong to me. I further confirm that all required documents have been duly attested by me or duly attested by either Public Notary or a Gazetted officer of a Government and are attached to the Form DIN-1 and I am not restrained /disqualified/ removed of, for being appointed as director of a company under the provisions of Companies Act, 1956 including Sections 203, 274, 284 and 388 (E) of the said Act or for being appointed as a designated partner of a Limited Liability Partnership under the provisions of the Limited Liability Partnership Act, 2008 including section 5 of the said Act and. I have not been declared as proclaimed offender by an Economic Offence Court or Judicial Magistrate Court or High Court or any other Court and I have not been already allotted a Director Identification Number (DIN) under Section 266B of the Companies Act, 1956 or a Designated Partner Identification Number (DPIN) under section 7 of the Limited Liability Partnership Act, 2008. Mr./Ms _____ CA/ CS/ CWA in practice has been authorized to digitally sign DIN application on my behalf. *Note: Strike out whichever is not applicable. Signature: (name) CS KAUSHIK M JHAVERI
24
STATUS OF APPROVAL OF DIN IN DIFFERENT CASES
Upon upload and successful payment, In case Form DIN 1 is signed by a practising professional and details have not been identified as potential duplicate, Approved DIN shall be generated and if the details have been identified as potential duplicate, Provisional DIN shall be generated. CS KAUSHIK M JHAVERI
25
APPROVAL OF DIN (Cont…)
In case Form DIN 1 is signed by Secretary (who is member of ICSI), in whole-time employment, of existing company in which applicant is proposed to be Director or details have been identified as a potential duplicate, provisional DIN shall be generated. In this case, the MCA DIN cell will examine the e-Form DIN 1 and same shall be disposed of within one or two days. CS KAUSHIK M JHAVERI
26
Requirement of DIN Form Indian Director V/S Foreign Director
Sr. No. Indian Director Foreign Director 1. Pan Card is mandatory as proof. Passport is mandatory in case of Foreign Director 2. Proof of Father’s name is mandatory to be provided. Proof of Fathers name is not mandatory. 3. Proof’s can be self attested, notarized or can be attested by Practicing CA or CS Proofs has to be notarized in Home country in case of prospective Foreign directors or it can be attested by Managing Director /CEO/ CS in Employment, if any for existing Directors CS KAUSHIK M JHAVERI
27
INTIMATION OF CHANGE IN PARTICULARS OF DIRECTOR TO BE GIVEN TO THE MINISTRY OF CORPORATE AFFAIRS (DIN – 4) Purpose : For making following correction / Change in approved DIN Director Name/ Designated Partner Name. Father’s Name. Nationality Date of Birth Gender Income – Tax PAN Voters Identity Card Number Passport Number Driving License Number ID/ Mobile Permanent residential address Present residential address. Photograph Residential Status Verification as per Annexure 1 of DIN rules. Verification as per Annexure 2 of DIN rules 2. Select the type of change(s). Based on the type of change, appropriate field’s) shall be enabled. CS KAUSHIK M JHAVERI
28
POINTS TO BE NOTED IN DIN 4
1. No filing fees 2. No requirement for physical submission of DIN documents at DIN Cell, NOIDA 3. It shall be mandatory to enter following in all cases: i. ID and ii. mobile number 4. Copy of Verification by the director to be attached as mentioned in Annexure – 2 5.. . CS KAUSHIK M JHAVERI
29
Verification of director/ designated partner in case of Form DIN-4 as per Annexure- 2 of the DIN rules I, … (name of director/ designated partner), Son/Daughter* of …………. (director’s/ designated partner’s father’s name), born on…….. (date of birth), resident of ………….…….. (present residential address of the director/ designated partner) hereby confirm and verify that the particulars given in the Form DIN-4 are true and correct and also are in agreement with the document being attached to the Form DIN-4. (i) I have applied for change of:- a) Director/ Designated Partner Name (along with proof and in case of change of name a copy of Notification published in the Gazette) b) Father’s name (along with proof) c) Nationality (along with proof) d) Date of Birth (along with proof and in case of change in date of birth, copy of Notification published in the Gazette) e) Gender (along with proof) f) Income –Tax Permanent Account Number (along with proof) g) Voters Identity Card Number (along with proof) h) Passport Number (along with proof) i ) Driving License Number (along with proof) j) ID/ Mobile (along with declaration) k) Permanent residential address (along with proof) l) Present residential address (along with proof) m) Photograph of director/ designated partner n) Residential status o) Verification as per Annexure-1 of DIN rules p) Verification as per Annexure-2 of DIN rules I further confirm that (iii) I am not restrained/ disqualified/ removed of, for being appointed as director of a company under the provisions of Companies Act, 1956 including Section 203, 274, 284 and 388 (E) of the said Act or for being appointed as a designated partner of a limited liability partnership under the provisions of the Limited Liability Partnership Act, 2008 including section 5 of the said Act and (iv) I have not been declared as proclaimed offender by any Economic Offence Court or Judicial Magistrate Court or High Court or any other Court and (v) I have no any other allotted Director Identification Number (DIN) other than DIN in which changes are intimated under Section 266 B of the Companies Act, 1956 or a Designated Partner Identification Number (DPIN) under section 7 of the Limited Liability Partnership Act, 2008. (vi) Mr/ Ms ……………… CA/ CS/ CWA in practice has been authorised to digitally sign DIN application on my behalf. *Note: Strike out whichever is not applicable. Signature: (Name) CS KAUSHIK M JHAVERI
30
SUMMARY OF DIN FORMS Sr. No DIN Form Matter Time Limit of Filing
Filing Fees 1 DIN 1 Application for Allotment of DIN It has to be applied before being appointed as Director. Rs. 100/- for each Application 2 DIN 2 Intimation of allotment of DIN to the Company by the Director Within One Month of receipt of intimation from Central Government Not Applicable 3 DIN 3 Intimation of DIN by the Company to the Registrar Within one week of receipt of intimation from Directors Based on Authorized Share Capital ** DIN 2 and DIN 3 is applicable only if date of appointment is before 4 DIN 4 Intimation of Change in particulars of Director to be given to the Central Government Within 30 days of date of change in particulars. Not applicable Applicability of DIN: Existing Directors appointed before 1st July, DIN 1, DIN 2 and DIN 3 Existing Directors appointed after 1st July, 2007 – DIN 1 New Directors – DIN 1 DIN 4 : DIN 4 is used when some changes in particulars of directors is to be made. Ex: 1. Change in name 2. Change in Present address 3. Change in Permanent address 4. Change in Date of Birth 5. Change in Nationality etc. CS KAUSHIK M JHAVERI 30
31
Amendments in Form 18 Form 18 revised to include the following point: whether registered office is : 1. owned by director. 2. owned by company. 3. owned by any other entity 4. taken on lease. Following documents to be attached in form 18: 1. Proof of registered office address 2. NOC from director if registered office owned by director 3. A proof that company is permitted to use registered office if it is owned by other entity 4. Copy of the Regional Director order (if shifting of registered office is from one state to another or change from one ROC to another within the same state)
32
CASE STUDIES ON CHANGE OF REGISTERED OFFICE
Sr. No Cases of Change in Registered Office Nature of Approval require Nature of Resolution Forms Applicable. Which Region CLB involved 1. Thane to Mulund ? 2. Dahisar to Mira road 3. Coimbatore to Chennai 4. Dahisar to Vashi 5. Mumbai to Ahemdabad 6. Pune to Mumbai 7. Mumbai to Punjab 8 Delhi to Haryana (ROC Delhi) CS KAUSHIK M JHAVERI
33
CHANGE IN REGISTERED OFFICE OF THE COMPANY (Sec 17, 17(1) &146)
Location Section Forms Applicable Time Limit Resolution require Change within the local limit of City, town or Village. Sec 146 Form 18 30 Days Board resolution Change outside the Local Limit of City, town or Village i. Form 18 ii. Form 23 Board Resolution Special Resolution Change of Registered office from jurisdiction of one ROC to Jurisdiction of another ROC within a same state. Section 17A Form 23 Form 1AD RD Approval Change of Registered office from One State to Another State Form 17 Form 24AAA Central Government Approval (Delegated power from CLB to RD vide Notification dated ) CS KAUSHIK M JHAVERI
34
SHIFTING OF REGISTERED OFFICE (Sec 146 & 17, 17A)
There are Five different Situation in Shifting of Registered office of the Company. 1. Change within local limit of City, Town or Village 2. Change outside Local Limits of City, town or Village 3. Change in office of ROC within same State. 4. Change in state within office of same ROC. 5. Change in State outside office of existing ROC. CS KAUSHIK M JHAVERI
35
Particulars of Appointment of Director/Managing Director/Manager/Secretary (Sec. 303)
Form 32 can be filed for following purposes. Appointment Change in Designation Resignation Vacation of Office Removal etc. Approved DIN number and Active ID of the Director is Mandatory to File Form 32 As per New introduced Form 32 on 14th March, 2010, Directors resigned before and not obtained DIN can also intimate to ROC regarding resignation without obtaining DIN CS KAUSHIK M JHAVERI
36
Creation/Modification and Satisfactions of Charges (Sec 125, 138)
Sr. No Type of Form Time Limit Fees Attestation of Practising Professionals 1. Form 8 for Creation of Charge i. 30 Days i. Normal fees Attestation of CA/CS is now required ii. Additional 30 days. ii. Late fees iii. If delay is for more than 60 days iii. CLB petition u/s 141 for condonation of Delay 2. Form 8 for Modification of charge 3. Form 17- Satisfation of Charge Attestation of CA/CS is required ii. If delay is for more than 30 days CS KAUSHIK M JHAVERI
37
Appointment/Re-Appointment… of Auditor [Sec 224]
1. As per Sec 224(5), The First Auditor of the Company shall be appointed by the Board of Directors within one month of the date of registration of the Company. 2. It is mandatory for the company to inform to Auditor about his re-appointment within 7 days of AGM in which he has been appointed. [Sec.224(1)] 3. Form 23B has to be filed by Auditor within one month of the receipt from the company of the intimation of his re-appointment, with ROC about his re-appointment as Auditor.[Sec.224(1A)] 4. Form 23B has to be filed before filing of Form 23AC, as SRN no. of form 23B is pre-requisite for filing E- Form 23AC. CS KAUSHIK M JHAVERI
38
Appointment/Re-Appointment… of Auditor [Sec 224] cont…
5. Re - appointment letter received from the Company is to be scanned and attached to E-form 23B 6. Now ROC fees is to be paid on filling of Form 23B vide circular dated 21st June, ROC fees payable on filling of Form 23B is based on the Authorised Capital of The Company. (The same can be calculated through fees calculator available on MCA site. ) (Earlier no fees was payable on filling of Form 23B) Incoming auditor has to ensure filing and provide SRN to Company Secretary/ Management. CS KAUSHIK M JHAVERI
39
ANNUAL FILING Sr. No. Document Forms Applicability 1 Balance-Sheet
Every Company incorporated under the Companies Act 1956, are required to file Balance Sheet (us/ 210), Annual return (u/s 159) and Compliance Certificate (u/s 383 A (1)), as applicable Sr. No. Document Forms Applicability 1 Balance-Sheet Form 23AC all Companies 2 Profit & Loss Account/ Income & Expenditure Statement Form 23ACA 3 Annual Return Form 20B Companies having share capital 4 Form 21A Companies without share capital 5 Compliance Certificate Form 66 Companies having paid up capital of Rs. 10 lakhs & more but less than to Rs. 5 Crore (As per Circular dated 15th March, 2009) CS KAUSHIK M JHAVERI
40
Compliance Certificate(Form 66)
Purpose: Form 66 – Form for filing Compliance Certificate with Registrar Filed by: the company Filing Fees : Based on Authorized Share Capital Due Date of filing: within 30 days from the date of Annual General Meeting. CS KAUSHIK M JHAVERI
41
Form 23AC & 23ACA (vide MCA circular No. 30/2012)
Purpose: Form 23AC - Form for filing Balance Sheet and other documents with the Registrar Form 23ACA - Form for filing Profit and Loss account and other documents with the Registrar Filed by: the company Filing Fees : Based on Authorised Share Capital Due Date of filing: within 30 days from the date of Annual General Meeting. CS KAUSHIK M JHAVERI
42
Revised Form 23AC In case the start date of financial year is on or after , then details are to be entered in ‘BALANCE SHEET (As per Schedule VI to the Companies Act, 1956 applicable for the financial year commencing on or after ) In case start date of financial year is before , then details are to be entered in ‘BALANCE SHEET (Applicable for financial year commencing before ) (Applicable only in case of pending filing of previous year upto ) CS KAUSHIK M JHAVERI
43
Highlights of e-Form 23AC: (Related to Balance sheet)
Sr. No. Page No. of revised Form 23AC Revision in Form 23AC Previous Form 23AC 1. Pg. No. 4 Category of auditors whether individual or firm is required to be mentioned. In case of firm, name and membership number of member representing the firm is to be mentioned. No such category was provided 2. Pg. no. 5 Details of Money received against share warrants needs to be filled up No such details was required 3. Details of Non Current Liabilities is to be provided under following heads: Long term borrowings Deferred tax liabilities. Other long term liabilities Long Term provisions Break up of Secured Loan and Unsecured Loan was required 4. Pg. no.5 Details of Current Liabilities : Short term borrowings Trade Payables Other Current Liabilities Short term provisions The details of Current Liabilities and Provision were shown under the heading of Application of Funds. CS KAUSHIK M JHAVERI
44
Highlights of e-Form 23AC: (Related to Balance sheet)
Sr. No. Page No. of revised Form 23AC Revision in Form 23AC Previous Form 23AC 5. Pg. no. 5 Details of Assets divided as Non Current Assets and Current Assets No such bifurcation was required 6. Details of Fixed Assets is to be provided under the following heads: Tangible asset Intangible asset Capital work in progress Intangible asset under development Separate details of Intangible assets and Intangible asset under development was not required 7. Pg. no.5 Non - current Investment is to be shown separately, while current investment is to be mentioned in current asset. No such bifurcation was required 8 Pg. no. 6 Long term loans and advances and Other non- current assets to be mentioned 9. Pg. no. 7 & 8 Details of following schedules of balance sheet is to be provided separately: Long Term Borrowing (unsecured) Short Term Borrowing (unsecured) Long Term Loans and advances (unsecured, considered good) Long Term loans and advances (doubtful) Trade receivables Earlier it was not required to provide the details of schedules of Balance Sheet CS KAUSHIK M JHAVERI
45
Highlights of e-Form 23AC: (Related to Balance sheet)
Sr. No. Page No. of revised Form 23AC Revision in Form 23AC Previous Form 23AC 10. Pg. no. 8 & 9 Total number of Financial Parameters are extended to 45 Earlier financial parameters were only 15 11. Pg. 9 Details of Share Capital Raised during the reporting period: Private placement arising out of conversion of debentures/ preference shares & other private placement Preferential allotment arising out of conversion of debentures / preference shares and Other preferential allotment Employee Stock Option Plan (ESOP) Earlier there was no such bifurcation was required for following: 1. Private Placement 2. Preferential allotment 3. ESOP details was not required 12. Pg. no. 10 Details w.r.t Companies (Auditor's Report) Order, 2003 (CARO) is required to be provided No such details were required to be provided. 13. Pg. no. 11 Details related to cost audit of principal products or activity groups under cost audit is to be filled up CS KAUSHIK M JHAVERI
46
Highlights of e-Form 23ACA: (Related to P & L Account)
Sr. No. Page No. of revised Form 23ACA Revision in Form 23ACA Previous form 23ACA 1. Pg. no. 2 & 3 Details of consumption of stores & spare parts now shifted into Financial Parameters. Following other details to be provided: Profit before exceptional and extraordinary items and tax Details of exceptional items Extraordinary items current and deferred tax profit/loss from continuing / discontinuing operations No such details were required to be provided 2. Pg. no. 5 Details of Schedule of earning in Foreign Exchange and expenditure is to be provided Only amount of earning of foreign exchange and expenditure was to be provided 3. Details of Principal products or services of the company. The list of ITC/ NPCS code is provided on the MCA website Earlier no such list was provided CS KAUSHIK M JHAVERI
47
COMMON challenges – EXCEEDING MB SOLUTION- Additional Attachment
If the file size of Form 23AC exceeds 2.5MB,use the Additional Attachment Sheet available in the Annual Filing Corner of MCA Portal. CS KAUSHIK M JHAVERI
48
Additional Attachment (Cont…)
2. Enter the CIN and click ‘Pre-fill’ button to automatically fill the name and address of the Company in the eForm. 3. Fill the date of relevant Balance Sheet. 4. Select the type of document from the dropdown list and click ‘Attach’ button to ‘browse and select’ the file to be attached. At a times we can attach only 5 documents 5. Fill the signatory details i.e. Designation and DIN/ Membership No. 6. Affix the Digital Signature Certificate of the signatory CS KAUSHIK M JHAVERI
49
Additional Attachment (Cont…)
7. Click ‘Verify’ button. In case of any error, rectify the same and repeat this step. 8. Please ensure that size of ‘Additional Attachment Sheet’ does not exceed 2.5 MB. 9. If there are more than 5 attachments, then follow (2 to 7) steps once again. We can upload maximum two ‘Additional Attachment Sheet’ against one Form 23AC. 10. After uploading of Form 23AC on MCA portal, system will prompt for following options: - File Form 23ACA - File additional attachments to Form 23AC 11. Select the second option and upload saved ‘Additional Attachment Sheet’. CS KAUSHIK M JHAVERI
50
Additional Attachment (Cont…)
12. After uploading of one ‘Additional Attachment Sheet’, system will again prompt for making a selection. If we have the second ‘Additional Attachment Sheet’ for uploading, select the second option again and upload the same. Otherwise select the first option and upload Form 23ACA to complete the filing and proceed to ‘payment option’ screen. 13. If we have uploaded two ‘Additional Attachment Sheets’ system will prompt you to file Form 23ACA to complete the filing and proceed to ‘payment option’ screen. 14.In Form 23AC,23ACA and Form 20B at place for membership number or COP number of Practising Professional, Put COP number only as the membership number is not accepted by the system. 15. If Balance Sheet figures are in Thousand, In 23AC, 23ACA put original figures in Rs. And not the converted figures from Thousand to Rupees. CS KAUSHIK M JHAVERI
51
Applicability: (Phase I)
Filing of Balance Sheet and Profit & Loss Account in XBRL Mode (Vide MCA Circular No. 16/ 2012 dated ) Applicability: (Phase I) i. All companies listed with any Stock Exchange(s) in India & their Indian Subsidiaries; or All Companies having paid up capital of Rs. 5 Crores and above; or All Companies having turnover of Rs. One Hundred Crores and above; or All companies who were required to file their financial statements for FY , using XBRL mode. (Any change in status of above applicability subsequently will also have to file the forms in XBRL form) For Financial Statements closing on or after CS KAUSHIK M JHAVERI
52
Filing of Balance Sheet and Profit & Loss Account in XBRL Mode conti..
Companies falling under following categories are exempted: (Vide MCA Circular 16/2012 dated ) Banking Companies Insurance Companies Power Companies Non – Banking Financial Companies (NBFCs) CS KAUSHIK M JHAVERI
53
Filing of Balance Sheet and Profit & Loss Account in XBRL Mode conti..
Verification & Certification of the XBRL Document : Practising Company Secretaries Practising Chartered Accountant Practising Cost Accountant CS KAUSHIK M JHAVERI
54
Annual Return (Form 20B & Form 21A)
Purpose: Form 20B – for Companies having a share capital Form 21A- for Companies not having share capital Filed by: the company Filing Fees : Based on Authorized Share Capital Due Date of filing: within 60 days from the date of Annual General Meeting. CS KAUSHIK M JHAVERI
55
POINTS TO BE KEPT IN MIND FOR FILLING UP FORM 20B
Date of AGM and Due date of AGM should match with uploaded Form 23AC and 23ACA, otherwise the Form will not get accepted on Portal Indebtedness Figure to be shown in rupees and as on the date of AGM. Details of All the Directors on Board as on the date of AGM to be filed up in Form 20B. Details of Directors who have resigned from the last AGM to current AGM to be filled in Column V, point 13. Mandatory Attachments Manually signed Annual Return (Schedule V) CS KAUSHIK M JHAVERI
56
POINTS TO BE KEPT IN MIND FOR FILLING UP FORM 21A
Number of Members in Master Data is to be corrected every year before filing Form 21A Statement of Indebtedness as on the date of AGM is mandatory to Attach in this Form. Mandatory Attachments. Manually signed Form 21A in a prescribed format Indebtedness Figure statement as on the date of AGM List of members as on the date of AGM. CS KAUSHIK M JHAVERI
57
Pre-Requisite of SRN No. in following forms
Sr. No. Forms Pre-requisite SRN No. of : Matter 1. Form 18 Form 23 In case of change in registered office from i. the local limit of one city, town or village to another city town or village 2. Form 1AD i. From Jurisdiction of One ROC to another ROC, within the same state. 3. Form 1AD 4. Form 21 i. One state to another state 5. Form 1B In case of Change of name of Company CS KAUSHIK M JHAVERI
58
Pre-Requisite of SRN No. in following forms
Sr. No. Forms Pre-requisite SRN No. of : Matter 6. Form 5 Form 23 In case of Increase in authorized capital with alteration in Articles of Association. 7. Form 2 In case of Special Resolution passed u/s 81 8. Form 23AC Form 66 In case Compliance Certificate is applicable to the Company, Paid SRN number of Form 66 to be filled in Form 23AC CS KAUSHIK M JHAVERI
59
E-form Application & Fees
Sr. No. Applicable e-form Purpose Filed with ROC filing fees (Rs.) 1. 24A Application u/s 297 – Prior Approval from Concerned Regional Director Concerned Regional Director 2,000 2. 24AAA Petition u/s 17 – Shifting of Registered Office 3. 24AB Application u/s 295 – Form for filing application for giving loan, Providing security or guarantee in connection with loan MCA New Delhi, Shastri Bhavan 4. 25A Application to CG for approval of appointment or reappointment and remuneration or increase in remuneration or waiver of excess payment of Managing or whole -time director or manager MCA New Delhi, Shastri Bhavan (Central Government)
60
SELECTIVE IMPORTANT E-FORMS FOR CA
SR. NO. DESCRIPTION E-FORMS Approval Services (Headquarters) 1. Application to Central Government for modification in the matters to be stated in the company's balance sheet or profit and loss account Form 23AAA 2. Application for exemption from attaching the annual accounts of the subsidiary companies Form 23AAB 3. Application to Central Government for not providing depreciation Form 23AAC 4. Form of application for approval for declaration of dividend out of reserves Form [u/s 205A (3)] CS KAUSHIK M JHAVERI
61
SELECTIVE IMPORTANT E-FORMS FOR CA (Cont….)
SR. NO. DESCRIPTION E-FORMS APPROVAL SERVICES (HEADQUARTERS) 5. Form of application to the Central Government for appointment of cost auditor Form 23C COMPLIANCE RELATED FILING 6. Information by Auditor to Registrar Form 23B 7. Return of appointment of Managing Director or Whole time Director or Manager Form 25C 8. Form for filing cost audit report and other documents with the Central Government Form (Form 1- CAR) CS KAUSHIK M JHAVERI
62
SELECTIVE IMPORTANT E-FORMS FOR CA (Cont….)
SR. NO. DESCRIPTION E-FORMS Annual Filing E- forms 9. Form for filing balance sheet and other documents with the Registrar Form 23AC 10. Form for filing Profit and Loss account and other documents with the Registrar Form 23ACA 11. Form for filing annual return by a company having a share capital with the Registrar Form 20B 12. Particulars of annual return for the company not having share capital Form 21A CS KAUSHIK M JHAVERI
63
RECENT UPDATES Pay Later facility has been provided to the User on the payment gateway of the MCA portal. (mca.gov.in) A Payment Option “Pay Later” facility has been provided to the stakeholder, which will allow the user to upload the form in one step and do the payment at a later point of time (within 7 days of uploading the form) through Credit Card/Net Banking. Initially Pay Later facility was not available on MCA portal. The User who used to upload Forms on the portal only need to make payment immediately on uploading CS KAUSHIK M JHAVERI
64
THANKS FOR PARTICIPATION
Kaushik M. Jhaveri Kaushik M. Jhaveri & Co., Practising Company Secretary 407,Kapadia Chambers, 599, JSS Road, Next to Maheshwari Bhavan, Marine Lines (East), Mumbai – Telephone: Cell No.: id: CS KAUSHIK M JHAVERI
Similar presentations
© 2017 SlidePlayer.com Inc.
|
http://slideplayer.com/slide/228647/
|
CC-MAIN-2017-17
|
refinedweb
| 5,714
| 52.29
|
When creating a new CSS library or framework, developers typically take one of two approaches with component naming: the Bootstrap approach or the jQueryUI approach.
Bootstrap tries to be as simple and basic as possible, calling a component exactly what it is. If something is a tooltip, why not use the class selector
.tooltip to define how it looks? This approach keeps things simple, clean, and easy to remember, but it has one big disadvantage. If you’re trying to incorporate Bootstrap into an existing project, the chances are pretty high it will conflict with your existing selectors.
jQueryUI, on the other hand, takes the opposite approach. They prefix every class name with the string
ui- greatly reducing the possibility of conflict, but at the cost of being more verbose.
Choosing between these two paths isn’t always easy. Namespacing might be better for compatibility, but what should your prefix be? A longer, more unique prefix will lead to fewer conflicts at the cost of a lot more typing. But if you pick a simple prefix, another library might already be using it. And many of the short and sweet prefixes are already taken (like
ui- by jQuery and
x- by ExtJS).
What if there were a third option? One with all the benefits of clean and simple names like Bootstrap, but without any of the possible conflicts?
With the help of a CSS preprocessor like Sass, this is possible.
Define Selectors with a Variable
Imagine I have a website that’s been around for a while and already defines styles for
.tooltip and
.alert. Then I decide I want to start using Bootstrap, but I don’t have the time to convert all of my legacy code to the Bootstrap format.
Given the current state of Bootstrap, I’m pretty much out of luck.
But what if there were a way to tell Bootstrap that I wanted to use its
.alert component, but call it something else, perhaps
.notice. With dynamic selectors, you can do exactly that.
Selectors don’t have to be static. If you build your components with a predictable naming convention, it becomes easy to abstract that name into a variable.
The convention I use is to give each component a name and add that name to the root element of the component. Each sub-element of the component that needs styling defines a class with the component name as a prefix.
Here’s a basic example of a messagebox component taken from an imaginary library called Flux:
<!-- the markup for the messagebox component --> <div class="messagebox"> <h1 class="messagebox-title">...</h1> <p class="messagebox-body">...</p> </div>
/* and the corresponding styles */ .messagebox { } .messagebox-title { } .messagebox-body { }
A predictable convention like this allows you to easily replace the static names in the selector with a Sass variable like so:
$flux-messagebox-name: "messagebox" !default; .#{$flux-messagebox-name} { } .#{$flux-messagebox-name}-title { } .#{$flux-messagebox-name}-body { }
This technique has all the pros of a clean naming system like Bootstrap with almost none of the potential conflicts. If a project wants to include the messagebox styles above, but its CSS already has
.messagebox defined, there’s no problem. All they’d have to do is assign the
$flux-messagebox-name variable to something else before including the messagebox’s Sass file, and the conflict is solved.
/* first override the messagebox's class name */ $flux-messagebox-name: "some-other-name"; /* then import flux normally */ @import "flux";
Note: I’m prefixing the class name variables with the
flux namespace for an extra level of protection since Sass variables live in the global scope. Doing this isn’t 100% necessary, but I recommend it.
JavaScript Plugins
Most component libraries come with a least some JavaScript that dynamically creates its own markup. If these components offer Sass variables for dynamic selectors, they’ll also need to offer JavaScript variables to change the class names there as well.
Since components typically expose a defaults object, the class name variable could be a property on that object, allowing users of the library to change it globally in one place.
For example, if messagebox is a jQuery plugin, you might use code like this to dynamically change the class name:
$.fn.messagebox.defaults.className = "some-other-name";
What about static markup?
At this point I’m sure some readers are wondering whether I’ve overlooked half the problem. Dynamically building selectors is one thing, but what if the old class name is in hundreds of places in the HTML, how do you deal with that?
The truth is I don’t think that situation would be very common. The typical use case for dynamic selectors is when you want to start using a third party library, haven’t written any code for it yet, and realize there would be conflicts. In this use case, you’re picking a class name that isn’t in the HTML precisely to avoid conflict.
The only time I could see dynamic selectors leading to a lot of find-and-replace in the HTML is if you change your mind and suddenly decide you want to name your classes something else, in which case it’s not really the library author’s fault. Also, if you’re repeating a lot of the same markup for each component and you think it’s likely you’ll change your mind later, this is a perfect place to abstract that markup into templates, partials, or helpers.
Summary
All component libraries that use preprocessors should offer the option of dynamic selectors. It allows for a short and simple name for the majority of users and only requires extra effort for the ones who need it. It doesn’t impose a verbose prefix on anyone and keeps the barrier to entry low. Those who want to make changes can dive into the Sass file, and those who just want to use it out of the box can simply grab the compiled CSS. Everybody wins.
I’d love to see libraries like Bootstrap adopt this approach. Bootstrap already uses a jQuery-like
noConflict() method in each of its JavaScript plugins. Dynamic selectors wouldn’t be much harder and would go a long way to increase its compatibility.
I believe that website authors should be able to write their markup however they want. They should be able to choose whatever names they want without the fear that someday those names will conflict with a third party library. It should be the responsibility of library and framework authors to make their code as compatible as possible.
|
http://philipwalton.com/articles/dynamic-selectors/
|
CC-MAIN-2015-32
|
refinedweb
| 1,098
| 62.07
|
After a brief and rocky relation, I have had jilted Borland 5.02 and found new love for CODE::BLOCK only to discover a while ago that Borland could compile a code snippet which CODE::BLOCK couldn't.
In the working program produced below, CODE::BLOCK gave out an error message and failed to compile the original codes, where I used Void main(void) in the main function; it was adamant that it would only accept int main(void).
Then I realized that I should not have abandoned Borland, recalling fond memories that when you highlighted a C++ keyword, and pressed F1, you could get help readily, c/w explanations and examples of usage. CODE::BLOCK8.02 could not do this. In this respect, it is less user-friendly than Borland.
So, Borland need not be discarded, since its help is handily available. Perhaps, it can coexist with CODE::BLOCK, playing a different role, perhaps for lookup on explanation and usage of keywords, etc.
However, I have also discovered out that Borland has bad habits, being sometimes unpredictable and infested with bugs, and failing to compile on bug-free codes with the message "External errors" and could even tolerate the "Wrong thing" in compiling C++ codes with Void main(void), without any complaint, which I found to be like mixing with the wrong company.
Now, coming back to the main purpose of this thread, as shown in the title.. In the C++ codes below, I have remarked out // inp="", otherwise it would cause compiling to fail. So, I have used inp=NULL, and was let off with a warning, and compiling could be completed, and the program could run.
But, that line inp=NULL had been ignored on execution of the program. :(
It looks like a simple assignment of a character variable to NULL, for those familiar with other high level computer languages but i have not figured out how to do it in C++ yet.
I believe that the time a self-taught person take to learn C++ programming or any other skills in isolation would range from 3 X more to infinity -- which means not in a lifetime -- more compared with a person lucky to be pointed the right direction by a good and knowledgeable mentor, ceteris paribus. I also believe in Karma and that what goes around, comes around.
There is an intention to develop functions to make C++ programs more user-friendly. Ultimately, it is hoped that extended ASCII codes produced by pressing those Up, Dn, Left, Right, PgUp and PgDn keys could be used for data entry where Input type could be predetermined, and user is pre-empted from making errors before confirming with the Enter key. And the cursor can move from field to field, and page to page using extended keys mentioned above.
So, please help.
// ASCII-getche ASCII from keypress #include <stdio.h> #include <conio.h> #include <iostream> #include <string> #include <stdlib.h> using namespace std; int main(void) { system ("color 0a"); int c=0; char inp; //inp="": do { system("CLS"); cout << "\n\n\n\n\n\tThis program produces ASCII code for any key pressed."; cout << "\n\n\n\n\n\tChar : " << inp << " ASCII: " << c <<"\n\n\n\tEsc to Exit,\tPresskey a key: "; c = getche(); //* assign ASCII code to c inp=c; // CHR$ from ASCII if extended, c=0 if (c==0) { c=getche(); inp=NULL; } } while (c != 27); /* ESC to escape*/ cout << "\n\n\n\tBye\n\n\n"; getch(); }
|
https://www.daniweb.com/programming/software-development/threads/222347/howto-null-character-borland-vs-code-block-and-int-main-void-vs-void-main-void
|
CC-MAIN-2022-33
|
refinedweb
| 581
| 67.69
|
Ubuntu.Components.Popups.Popover
A popover allows an application to present additional content without changing the view. A popover has a fixed width and automatic height, depending on is contents. It can be closed by clicking anywhere outside of the popover area. More...
Properties
- autoClose : bool
- caller : Item
- callerMargin : real
- container : list<Object>
- contentHeight : real
- contentWidth : real
- edgeMargins : real
- foregroundStyle : Component
- pointerTarget : Item
- style : Component
- styleName : string
- theme : ThemeSettings
Methods
Detailed Description
Example:
import QtQuick 2.4 import Ubuntu.Components 1.3 import Ubuntu.Components.ListItems 1.3 as ListItem import Ubuntu.Components.Popups 1.3 Rectangle { color: theme.palette.normal.background width: units.gu(80) height: units.gu(80) Component { id: popoverComponent Popover { id: popover Column { id: containerLayout anchors { left: parent.left top: parent.top right: parent.right } ListItem.Header { text: "Standard list items" } ListItem.Standard { text: "Do something" } ListItem.Standard { text: "Do something else" } ListItem.Header { text: "Buttons" } ListItem.SingleControl { highlightWhenPressed: false control: Button { text: "Do nothing" anchors { fill: parent margins: units.gu(1) } } } ListItem.SingleControl { highlightWhenPressed: false control: Button { text: "Close" anchors { fill: parent margins: units.gu(1) } onClicked: PopupUtils.close(popover) } } } } } Button { id: popoverButton anchors.centerIn: parent text: "open" onClicked: PopupUtils.open(popoverComponent, popoverButton) } }
Property Documentation
The property drives the automatic closing of the Popover when user taps on the dismissArea. The default behavior is to close the Popover, therefore set to true.
When set to false, closing the Popover is the responsibility of the caller. Also, the mouse and touch events are not blocked from the dismissArea.
The Item such as a Button that the user interacted with to open the Dialog. This property will be used for the automatic positioning of the Dialog next to the caller, if possible.
The property holds the margin from the popover's caller. The property is themed.
Content will be put inside the foreround of the Popover.
Use this property to override the default content height.
Use this property to override the default content width.
The property holds the margins from the popover's dismissArea. The property is themed.
Exposes the style property of the StyledItem contained in the Popover. Refer to StyledItem how to use it.
The property holds the item to which the pointer should be anchored to. This can be same as the caller or any child of the caller. By default the property is set to caller.
The style of the foreground of the Popover. This property takes precedence over styleName
This QML property was introduced in Ubuntu.Components 1.3.
See also StyledItem::style.
The style name of the foreground of the Popover.
This QML property was introduced in Ubuntu.Components 1.3.
See also StyledItem::styleName.
Configure the theme of the Popover foreground and all its subcomponents.
This QML property was introduced in Ubuntu.Components 1.3.
See also StyledItem::theme and Dialog::theme.
Method Documentation
Hide the popover. Only use this function if you handle memory management. Otherwise use PopupUtils.close() to do it automatically.
Make the popover visible. Reparent to the background area object first if needed. Only use this function if you handle memory management. Otherwise use PopupUtils.open() to do it automatically.
|
https://docs.ubuntu.com/phone/en/apps/api-qml-current/Ubuntu.Components.Popups.Popover
|
CC-MAIN-2018-51
|
refinedweb
| 524
| 54.79
|
Greetings,
Presuming that you filed a joint return ("when he did our taxes") then there is no way for you to amend the 2006 return to include the inadvertently omitted income without his signature on the joint return. So, unless it is your plan to slip the tax papers into other items he is signing in the hope he does not notice you will have to confess to the omission.
You will use Form 1040X to include the income and recompute the tax due. You have three years from the original date filed to submit the Form 1040X. Perhaps you should wait to amend the return until after you clean out your briefcase and any other places that could contain return information (half kidding there). Or, you may wish to compile all of the 2007 information and then present both the new complete and orderly information and the omitted prior year item.
Since you are including additonal income you will likely have a balance due (and some interest); but should be able to plead for mercy and request abatement of any penalty, if you have a good history of compliance.
I hope this helps. Best wishes on the confession and apology to your husband.
Hello Craig !
Happy New Year to you and yours, as well. Thank you for the opportunity to be of service.
|
http://www.justanswer.com/tax/10871-cleaning-desk-found-1300-00-dollars-extra.html
|
CC-MAIN-2014-41
|
refinedweb
| 224
| 67.69
|
Beaver is a logging application and lib for flex/flash applications. It is able to store logs to a LSO, send logs to a Beaver AIR app, generates a log report, can opt in or out of sending to flash console i.e. trace, uses a unique key for all handshakes and offers a channel to handle Error/Fatal events within the application. Regarding the log report generation, any application can perform that task by connecting to Beaver and reading the logs identified by a unique key.
In order to use the logger, a developer must create a unique key starting with an underscore i.e. _123456. After that, it necessary to send a reference to the app instance to assign a handler for dispatched ERROR/FATAL events. Finally create a class to send the logs.
Sample
public class BeaverLog { /** * Constructor expects a unique key for the application * and a flag to send all output to the flash console. * * @param key:String * @param app:Object * @param outputToConsole:Boolean (default = true) */ private static var trunk:BeaverTrunk = new BeaverTrunk("_123456", Example.root); public static function send(message:String, sender:Object, level:int = 4):void { trunk.saveNewLog(message, sender, level); } } BeaverLog.send("Gnaw a log or two", this); BeaverLog.send("The whole tree fell!", this, LogEventLevel.FATAL);
|
https://www.as3gamegears.com/debug/beaver/
|
CC-MAIN-2020-29
|
refinedweb
| 214
| 65.01
|
String is a collection of characters. There are two types of strings commonly used in C++ programming language:
- Strings that are objects of string class (The Standard C++ Library string class)
- C-strings (C-style Strings)
C-strings).
How to define a C-string?
char str[] = "C++";
In the above code,
str is a string and it holds 4 characters.
Although, "
C++" has 3 character, the null character
\0 is added to the end of the string automatically.
Alternative ways of defining a string
char str[4] = "C++"; char str[] = {'C','+','+','\0'}; char str[4] = {'C','+','+','\0'};
Like arrays, it is not necessary to use all the space allocated for the string. For example:
char str[100] = "C++";
Example 1: C++ String to read a word
C++ program to display a string entered by user.
#include <iostream> using namespace std; int main() { char str[100]; cout << "Enter a string: "; cin >> str; cout << "You entered: " << str << endl; cout << "\nEnter another string: "; cin >> str; cout << "You entered: "<<str<<endl; return 0; }
Output: C++ String to read a line of text
C++ program to read and display an entire line entered by user.
#include <iostream> using namespace std; int main() { char str[100]; cout << "Enter a string: "; cin.get(str, 100); cout << "You entered: " << str << endl; return 0; }
Output
Enter a string: Programming is fun. You entered: Programming is.
string Object
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can be extended as per your requirement.
Example 3: C++ string using string data type
#include <iostream> using namespace std; int main() { // Declaring a string object string str; cout << "Enter a string: "; getline(cin, str); cout << "You entered: " << str << endl; return 0; }
Output
Enter a string: Programming is fun. You entered: Programming is fun.
In this program, a string str is declared. Then the string is asked from the user.
Instead of using
cin>> or
cin.get() function, you can get the entered line of text using
getline().
getline() function takes the input stream as the first parameter which is
cin and
str as the location of the line to be stored.
Passing String to a Function
Strings are passed to a function in a similar way arrays are passed to a function.
#include <iostream> using namespace std; void display(char *); void display(string); int main() { string str1; char str[100]; cout << "Enter a string: "; getline(cin, str1); cout << "Enter another string: "; cin.get(str, 100, '\n'); display(str1); display(str); return 0; } void display(char s[]) { cout << "Entered char array is: " << s << endl; } void display(string s) { cout << "Entered string is: " << s << endl; }
Output
Enter a string: Programming is fun. Enter another string: Really? Entered string is: Programming is fun. Entered char array is: Really?
In the above program, two strings are asked to enter. These are stored in str and str1 respectively, where str is a
char array and str1 is a
string object.
Then, we have two functions
display() that outputs the string onto the string.
The only difference between the two functions is the parameter. The first
display() function takes char array as a parameter, while the second takes string as a parameter.
This process is known as function overloading. Learn more about Function Overloading.
|
https://cdn.programiz.com/cpp-programming/strings
|
CC-MAIN-2020-40
|
refinedweb
| 550
| 72.26
|
Up to [DragonFly] / src / etc / defaults
Request diff between arbitrary revisions
Keyword substitution: kv
Default branch: MAIN
Bring in some changes to bsd.sys.mk from FreeBSD. -Werror is turned on for i386/gcc41 builds (can be overridden with NO_WERROR. -Use CWARNFLAGS so they can be overridden easily. -Introduce CSTD which allows a Makefile to specify the precise dialect of C. Reviewed-by: swildner
Make bsdcpio the default cpio. Place WITH_GCPIO in make.conf if you want the GNU version as the default. Both are still built and installed..
Build the installer as part of normal build-/installworld if WANT_INSTALLER is set. Clean up nrelease/Makefile to define WANT_INSTALLER if the 'installer' target is specified.
Remove fortran from base.
- Add THREAD_LIB to make.conf - Export LIBTHREAD in bsd.libnames.mk based on THREAD_LIB - Bail out earlier, if NO_LIBC_R is defined and THREAD_LIB is "r_c" - Set DPADD to LIBTHREAD in lib/libpthread/Makefile # Default thread library is still lib/libthread_xu
Fix typo. Reported-by: "Trevor Kendall" <trevorjkendall@gmail.com>
Describe CCVER's default as gcc41.
Add a build option (NO_GCC34) to prevent building gcc version 3.4. This does not attempt to remove gcc-3.4, only to prevent it from building.
Remove NO_GCC41 make option.
Add a make.conf variable GROFF_PAPER_SIZE which allows to set the paper size that groff is built for, either "letter" (default) or "A4". Suggested-by: Steve O'Hara-Smith <steve@sohara.org>
Build gcc41 per default. This can be disabled with NO_GCC41 in make.conf. This does not make gcc41 the default compiler. To do so, you still have to set CCVER=gcc41 in make.conf or in your environment.
Remove GNU tar. Reviewed-by: corecode
Remove traces of gcc40
Document pentium-m support Reported-by: TGEN
Remove lukemftpd from our source tree as discussed on users@: This is still available from pkgsrc.
Move WANT_LUKEMFTPD up a few lines so it's not grouped with the cvsup options. Reported by: Trevor Kendall <trevorjk@gmail.com>
NO_PKGTOOLS doesn't exist anymore
Welcome the build infrastructure for gcc41
Make bsdtar our default tar. GNU tar is still installed as gtar, and can be "tar" by using WITH_GTAR in make.conf. Discussed on: users@gmail.com> Thanks to pavalos for noting that WANT_LUKEMFTPD is missing.
Bring etc/defaults/make.conf closer to reality: * Add WITH_BSDTAR * NOSHARE -> NO_SHARE * Fix ports related comment.
Remove BOOTWAIT and NO_SHAREDOCS options. BOOTWAIT was from the old boot code and NO_SHAREDOCS is obsolete since we don't build share/doc anymore.
* Generally change NOXXX to NO_XXX, similar to work done in FreeBSD. * Revamp the NO_XXX documentation in make.conf Submitted-by: "Carl A. Schmidt" <carl@carlschmidt.net>
Add gcc40 build hooks. Gcc40 isn't built per default, you will have to enable it by adding WANT_GCC40=yes to make.conf.
Add NO_PKGTOOLS to disable building of the pkg_* tools during world. This is useful for people using pkgsrc.
Get rid off Alpha mentions.
Remove documentation of NOPERL, it's the default now. Don't create an include hierachie for perl.
Add comment markers to avoid the same stupid mistake as I made.
Add a commented out STRIP variable to show people how to make sure installed files keep their debugging symbols.
Get rid of the NO_TCSH make.conf variable. We do not support removing /bin/csh from the base system as part of a buildworld sequence.
Add an explanation for the use of CCVER in /etc/make.conf, and recommend that it not yet be used in that file. Suggested-by: "Erik P. Skaalerud" <erik@pentadon.com>
Correct the commented-out example for MODULES_OVERRIDE. Submitted-by: Dheeraj Reddy <dheerajs@comcast.net>
Remove kerberosIV from the build. Both normal builds and kerberos5 builds have been tested to work.
Remove NOSECURE which no longer serves a purpose. Note: FreeBSD also removed NOSECURE. Submitted-by: Jeroen Ruigrok/asmodai <asmodai@tendra.org>
Remove UUCP support. Note: /usr/src/gnu/libexec/uucp and /usr/src/libexec/uucpd physically removed from repository.
Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most ids have been removed from !lint sections and moved into comment sections.
import from FreeBSD RELENG_4 1.97.2.80
|
http://www.dragonflybsd.org/cvsweb/src/etc/defaults/make.conf?f=h
|
CC-MAIN-2014-15
|
refinedweb
| 697
| 62.54
|
Write a Java program file called P1.java with a class name P1, an example of the code structured is shown below. All of the Java code you write should be contained in the main method. For this assignment, you must follow the directions below exactly:
// P1 Assignment // Author: Colonel Mustard // Date: 8/23/2017 // Class: CS163/CS154 // Email: eid@cs.colostate.edu public class P1 { public static void main(String[] args) { // Print statements go here } }
Your program should print seven lines, and should match the output shown below, except as described here. You must print exactly what is requested. Spelling errors, incorrect capitalization, extra or missing white space and any other difference will reduce your grade. The second line will have your name instead of mine. The third line may differ, so it will not be checked, but it must be present! The fourth, fifth and sixth lines must have exactly the strings shown. The seventh line must follow the specification given above. See the grading criteria below for additional information.
Java programming is great! Say, Benjamin Computer Science 2468 08/28/2017 CS163: CS1 Java, No Prior Programming I am in this class because I really like computer programming.
P1.java
|
http://www.cs.colostate.edu/~cs163/.Fall17/assignments/P1/doc/P1.php
|
CC-MAIN-2017-43
|
refinedweb
| 203
| 66.03
|
Sometimes things happen or do not happen differently than we expect it. That often requires a thorough investigation of the causality and flow of our code. The first move would normally be to throw a Debug.Log somewhere, where we expect our problem to happen. However, what if it is not enough?
Another parameter in Debug.Log
The problem: You got a number of objects with the same name that would be normally hard to distinguish.
The solution: The first thing to beef up the log statement is to add an extra parameter to our call. As per documentation:
public static void Log(object message, Object context);
If you pass a GameObject or Component as the optional context argument, Unity momentarily highlights that object in the Hierarchy window when you click the log message in the Console.
Now what does this mean? Let’s say our debug code looks like this:
public class FindMe : MonoBehaviour { void Start() { Debug.Log("ヘ(・ω| Where am I?", this); } }
Then by simply clicking on the log, the corresponding object will be highlighted. In this case a
Component was passed (this refers to the class we’re at, which eventually inherits after Component). Similarly, any
GameObject could be passed.
From the official description, it could seem that only objects that are in the Hierarchy window could be highlighted this way. Though the method header indicates that any
UnityEngine.Object could be used. This is exactly the case and we can use it to locate anything that has an instance ID. It includes but is not limited to classes like:
Material,
ScriptableObject, and
Mesh.
Bonus fact: We can use
EditorGUIUtility.PingObject to use the highlight functionality without writing logs. Link
Making the logs pop
The problem: You need to log a lot of things and while viewing the data and categorize it quickly at a glance. Using the search box and collapsing the logs do not work as well as the order of messages is important and a value that is searched for is not that obvious.
The solution: Spice up your logs visually. Log statements can take in Rich Text tags. Differentiating by color is way faster for eyes than reading each line. In the following example, if a slightly concerning value is shown, then the color of the value changes. This is easily noticed almost immediately.
Stopping the flow
The problem: The special case denoted by color is not understood enough once it passed. You need to inspect the scene and/or look at the exact execution in code.
The solution: Firstly, the more known approach. Setting up a breakpoint. Unity and Visual Studio work quite well together for this purpose. If on the Visual Studio side for basic debugging, link to the official docs. Getting it working in Unity is quite simple:
- Click to the left of the line of code you want the break to happen at.
- Attach to Unity.
- Press Play.
- The breakpoints is hit. From there Visual Studio allows to inspect Local values, investigate the Call Stack and use many other Visual Studio debugging tools.
When Visual Studio takes over, the Editor becomes unresponsive. This form of breakpoint is not suitable for inspecting the scene. If it is necessary to do so,
Debug.Break is your friend. It acts as if the pause button was pressed, except it is exactly at the desired line in code. Then the state of the scene can be fully explored. Alternatively use a debug using
Debug.LogError while enabling the option to pause on error.
Adjusting the console window
The problem: There are a myriad types of data that may need to be displayed. Not every type fits neatly in the limited space provided by the log entry.
The solution: Look into the options of the Console window and select as necessary. Additionally, timestamps can be enabled/disabled.
What did I just build?
The problem: Build completed with a result of ‘Succeeded’ is not enough information about what has just happened. Especially when looking to slim down the size of the app.
The solution: Console window options, then “Open Editor Log”. and select as necessary. A text file opens. Starting from section of Build Report there is a detailed breakdown of what assets went in and how much space do they take up, conveniently in descending order.
Logging based on preprocessor directives
The problem: There is a system, that is so vital to the whole app that every time it is being interacted with, you have a set of key debug statements that you want to know about. However it is too many to simply comment and uncomment every time.
The solution: Creating a static class that is active with a custom directive will call the corresponding log method with custom prefix. To quickly turn that off have another class with exactly the same name and methods that is active with negation of the directive. Then in
Edit > Project Settings > Player > Other Settings > Scripting Define Symbols add the symbol that is used to filter this particular logger. The following example assumes naming conventions for a networking module selective logging:
using UnityEngine; #if NET_LOGGER && (UNITY_EDITOR || DEVELOPMENT_BUILD) public static class DebugNet { public static void Log(string message) { Debug.Log($"[NET] {message}"); } public static void LogWarning(string message) { Debug.LogWarning($"[NET] {message}"); } public static void LogError(string message) { Debug.LogError($"[NET] {message}"); } } #else public static class DebugNet { public static void Log(string message) { } public static void LogWarning(string message) { } public static void LogError(string message) { } } #endif
To ensure that the logs never end up in the final build, display will also be dependent on the build being a development variant or in the editor. To learn more about directives that Unity provides, have a look in the documentation.
A potential drawback of this solution is that it does leave debug statements in the main code flow (even if you can hide them in a way that minimizes impact on performance). On the other hand, it is like leaving a comment in code of what is expected to have happened at that particular point in time.
Numbers not enough?
The problem: There is a lot of data. This data does not make much sense when viewed as numbers. Maybe it denotes some direction, or area, or it is a number/string, but it’s very important to know at a glance its current value and what object it’s attached to.
The solution: Depending on the needs, there are many approaches to debug by drawing things on the screen.
Debug class
The quickest way to draw a line is via the Debug class. From documentation (line, ray):
public static void DrawLine(Vector3 start, Vector3 end, Color color = Color.white, float duration = 0.0f, bool depthTest = true);
public static void DrawRay(Vector3 start, Vector3 dir, Color color = Color.white, float duration = 0.0f, bool depthTest = true);
Those two methods are especially useful in debugging things like raycast. The simple example would be to see how your object sees the world in front of them. This could highlight many possible issues that arise from improper layer setups or wrongly defined raycast source and direction.
[SerializeField] float hitDist = 1000; void Update() { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, hitDist)) { Debug.DrawLine(ray.origin, hit.point, Color.green); //Do your thing on hit } else { Debug.DrawLine(ray.origin, ray.GetPoint(hitDist), Color.red); } }
This snippet shows how to visualize your raycast. Do not that if the point is not hit,
DrawLine is used also. This is so that we don’t draw a line of infinite length, but the actual distance that is being tested via raycast. The film shows behavior with the aforementioned code:
Gizmos and Handles
If you need more custom shapes to be displayed than simple lines then the Gizmos context is your friend. It can help you draw all sorts of basic shapes, as well as custom meshes. In the following example bounds are being visualized in a similar way a box collider might do it.
public class BoundingBox : MonoBehaviour { [SerializeField] Bounds bounds; [SerializeField] bool filled; void OnDrawGizmosSelected() { Gizmos.matrix = transform.localToWorldMatrix; if (filled) { Gizmos.DrawCube(bounds.center, bounds.size); } Gizmos.DrawWireCube(bounds.center, bounds.size); } }
To ensure the coordinates of the bounds drawn are responsive to the transform component, a matrix that will transform each drawn point from local space to world space is set.
There is also a Handles class is generally used to make Editor tools, as it has got mostly methods that return a value if the user modifies something. However, for debugging it has one major advantage that Gizmos doesn’t have. It has a handy way to add labels to your objects (documentation).
public static void Label(Vector3 position, string text, GUIStyle style);
void OnDrawGizmos() { Handles.Label(transform.position, $"{gameObject.name} {transform.position.ToString()}", EditorStyles.miniButton); }
This snippet demonstrates how to draw a temporary label over the object. It is drawn at the position of the object and displays the object name and position. This can be used to display all kinds of data that you need to know the current state of some variable, and to which object they correspond to with a single glance. As the label is white and thin by default, a style was applied to rectify that. For quick setup that will be visible with any background EditorStyles class was used that houses a button type display.
Note that Gizmos methods can be called only in functions
OnDrawGizmos,
OnDrawGizmosSelected and those with proper attribute usage. If you try it in any other place, it will not work. This means that Gizmos are specific to Components. If you need to draw things from an Editor window, then Handles are the only option.
In conclusion…
As a final note sometimes to aid with the debug code some third party tools or scripts are needed. One should always be mindful of adding robust plugins, as it may have many functionalities that are simply not needed for the project, and might even hinder it. That being said, now you have hopefully learned some techniques that you might be considering to use when tackling a new bug or aiming to gain a greater understanding of your system. Keep in mind though that a solution should always be tailored to the problem and using a shiny new technique is usually not the way to go. Always take a step back to consider what is actually needed.
|
https://itsilesia.com/debug_unity/
|
CC-MAIN-2022-05
|
refinedweb
| 1,752
| 65.01
|
WEKF_Settings
Enables or disables settings for Keyboard Filter.
Syntax
class WEKF_Settings { [Key] string Name; [Read, Write] string Value; };
The following tables list any methods and properties that belong to this class.
Properties
Remarks
You must be signed in to an administrator account to make any changes to this class.
Each WEKF_Settings object represents a single Keyboard Filter setting. You can enumerate across all WEKF_Settings objects to see the value of all Keyboard Filter settings.
The following table lists all settings available for Keyboard Filter.
One instance of the WEKF_Settings class exists for each valid setting.
Changes to the DisableKeyboardFilterForAdministrator setting are applied when an administrator account signs in, and applies to all applications run during the user session. If a user without an administrator account runs an application as an administrator, Keyboard Filter is still enabled, regardless of the DisableKeyboardFilterForAdministrator setting.
Changes to the BreakoutKeyScanCode setting do not take effect until you restart the device.
If the BreakoutKeyScanCode is set to the scan code for either the left Windows logo key or the right Windows logo key, both Windows Logo keys will work as the breakout key.
The BreakoutKeyScanCode setting only applies to accounts where Keyboard Filter is active. If the scan code is set to a value that does not map to any key, such as 0 (zero), then you must use another method to access the Welcome screen if you need to service the device, such as remotely connecting, or restarting the device if automatic sign-in is not enabled.
Important On some devices, if the breakout key is pressed too rapidly, the key presses may not register. We recommend that you include a slight pause between each breakout key press.
Warning
When setting the BreakoutKeyScanCode, be sure to use the scan code of the key, and not the virtual key value.
Example
The following Windows PowerShell script demonstrates how to use this class to modify the breakout mode key for Keyboard Filter. This example sets the BreakoutKeyScanCode setting to the scan code for the Home key on a standard keyboard.
#---Define variables--- $COMPUTER = "localhost" $NAMESPACE = "root\standardcimv2\embedded" # Define the decimal scan code of the Home key $HomeKeyScanCode = 71 # Get the BreakoutKeyScanCode setting from WEKF_Settings $BreakoutMode = get-wmiobject -class wekf_settings -namespace $NAMESPACE | where {$_.name -eq "BreakoutKeyScanCode"} # Set the breakout key to the Home key. $BreakoutMode.value = $HomeKeyScanCode # Push the change into the WMI configuration. You must restart your device before this change takes effect. $BreakoutMode.put()
Requirements
Related topics
Keyboard Filter WMI provider reference
|
https://docs.microsoft.com/en-us/windows-hardware/customize/enterprise/wekf-settings
|
CC-MAIN-2019-35
|
refinedweb
| 418
| 53.31
|
0
Hi there
Just started an IT course recently, and although flying with HTML and other disciplines, I'm having trouble with some C++ syntax.
I have a problem with a short piece of code I have to write, which has to read input from the keyboard for 5 fictional employees, each of which has an ID number, name and salary. I have to use an array of structures, but the gets() piece of the code does not seem to work.
Looking at the code below, is it just my syntax that is wrong? I'm using C++ in Visual Studio 2008.
Many thanks in anticipation of some much-needed help!
#include <iostream> #include <cstring> using namespace std; struct employees{ int id; /* employee ID */ char name[30]; /* employee name */ double salary; /* employee salary */ }employee[5]; int main(void) { int counter; double salarytotal=0; for(counter=0;counter<5;counter++) {cout<<"Enter Employee ID number "<<counter+1<<": "; cin>>employee[counter].id; cout<<"Enter Salary for this Employee: "; cin>>employee[counter].salary; cout<<"Enter Name for this Employee (Max 30 chars): "; gets(employee[counter].name); salarytotal=salarytotal+employee[counter].salary;} cout<<"Combined Salary for these five employees is: "<<static_cast<char>(156)<<salarytotal<<endl; return 0; }
|
https://www.daniweb.com/programming/software-development/threads/244829/new-to-c-problem-with-gets-within-an-array-structure
|
CC-MAIN-2017-26
|
refinedweb
| 203
| 54.32
|
Problems using QPixmap's loadFromData to load an image
Trying to use the loadFromData to load an image that's in a sub-folder where the code looks like this:
@
QPixmap qp;
QString qs = "folder/pic.png"; // I've also tried dual backslash instead of the forward slash
qp.loadFromData(qs.toAscii());
@
I have the folder both in the project's folder as well as in the debug folder where the debug .exe is (not sure where I'm supposed to have it) and this function always returns false.
Any help would be much appreciated, thanks.
- koahnig Moderators
You may use "QDir::absoluteFilePath": to check where the file should be.
Hello
Maybe I miss something, but loadFromData method is used, when you have your picture loaded into memory. Try to use "QPixmap::load": method
Tried using the load function and that doesn't seem to be solving my problem either:
@
QPixmap qp;
QString qs = "folder/pic.png"; // I've also tried dual backslash instead of the forward slash
qp.load(qs);
@
QPixamp has a constructor taking a QString with the pathname:
@
QPixampa qp("foler/pic.png");
@
For your path problem. Make a QFile of the path an check if that absolute path exists:
@
QFile qpFile("folder/pic.png");
QFileInfo qpFileInfo(qpFile);
qDebug() << qpFileInfo. absoluteFilePath();
@
Yes, the file path exists. Tried to run the same code with using the file name in the constructor and it still doesn't work. Is there some flag I should be setting in the .load() call?
Hello
It sounds silly, but try to use "./folder/pic.png" or "/folder/pic.png" instead of "folder/pic.png".
Did you try with an full, absolute path in the constructor? Just to make sure, it's not a "file not found" issue.
If that doesn't work either, check if the imageformats support PNG. Add in your main method:
@
#include <QImageReader>
qDebug() << QImageReader::supportedImageFormats();
@
This should list PNG, amongst others.
Figured out that my problem was the folder was in the wrong folder for the code to recognize it. In any case I'm now having the problem where the image wont draw via a qpainter.drawPixmap() function. Going to start a new thread
|
https://forum.qt.io/topic/14808/problems-using-qpixmap-s-loadfromdata-to-load-an-image
|
CC-MAIN-2017-43
|
refinedweb
| 366
| 67.15
|
There seems to be some changes implemented in JBoss EAP 6.4.10 that is causing deployment of our app to hang during startup.
--
"ServerService Thread Pool -- 50" #112 prio=5 os_prio=0 tid=0x000000001edd0800 nid=0x204c in Object.wait() [0x0000000025c5d000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at org.jboss.as.ee.component.BasicComponent.waitForComponentStart(BasicComponent.java:117)
*- locked <0x00000000c56881e0> (a org.jboss.as.ejb3.component.stateless.StatelessSessionComponent)*
---
I've been able to pinpoint to JPA changes made between 6.4.9 and 6.4.10 as I can drop in JPA jars directly into 6.4.10 and don't get this issue.
I believe associated to: WFLY-6441 Setup the Java EE namespace on persistence unit start by scottmarlow · Pull Request #8810 · wildfly/wildfly · …
Any thoughts?
Hello Daniel,
If you have a JBoss EAP support contract, please raise this as a support ticket in the support portal. That way, it's easier to provide any patch that might be needed for this.
If you don't have access to the support portal, then you can raise this as an issue in WildFly (the upstream project) if it's still reproducible in latest released WildFly versions.
|
https://developer.jboss.org/message/988499
|
CC-MAIN-2019-43
|
refinedweb
| 214
| 52.46
|
You can subscribe to this list here.
Showing
25
50
100
250
results of 44
I just downloaded the 0.50 tar.gz and found the fonts folder appears to
be awol.
other than that it is working great :)
john
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
jdhunter@... ha scritto:
>?
Ok, I have removed the python2.3-numeric-ext dependency. The new version is on
the server
- --
/Vittorio Palmisano/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird -
iD8DBQFAPga4pT6bvDtyXOIRApu0AKDMEXGwqhsjQHr66KsAQYGAkCqq1ACgvZob
1GiHun0m4qd+c4yZKoGScu4=
=amuJ
-----END PGP SIGNATURE-----
Todd Miller has added a TkAgg backend to CVS. As the name implies,
this is a Tkinter GUI backend which uses agg to render. One very nice
feature of this backend is that it works interactively from any python
shell, though you'll still need to set matplotlib.interactive(True).
> python -i yourscript.py -dTkAgg
There may be a few minor issues to clear up, but it will be included
in the next release, so now would be a good time to test it out
(Thanks Todd!)
Also, following Paul Barrett's pointer to the BaKoMa fonts, I
implemented a TeX math parser which works with the new ft2font module
to render math text. Any text element (xlabel, ylabel, title, text,
etc) can use TeX markup, as in
xlabel(r'$\Delta_i$')
^
use raw strings
The $ symbols must be the first and last symbols in the string. Eg,
you cannot do
r'My label $x_i$'.
But you can change fonts, as in
r'\rm{My label} x_y'
to achieve the same effect.
A large set of the TeX symbols are provided (see below). Subscripting
and superscripting are supported, as well as the over/under style of
subscripting with \sum, \int, etc.
The module uses pyparsing to parse the TeX expression, an so can
handle fairly complex TeX expressions
Eg, the following renders correctly
tex = r'$\cal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\rm{sin}(2 \pi f x_i)$'
See
for a screenshot.
The fonts \cal, \rm, \it, and \tt are defined.
The computer modern fonts this package uses are part of the BaKoMa
fonts, which are (in my understanding) free for noncommercial use.
For commercial use, please consult the licenses in fonts/ttf and the
author Basil K. Malyshev - see also
KNOWN ISSUES:
- some hackish ways I deal with a strange offset in cmex10
- bbox is a bit large in vertical direction and small in horizontal direction
- nested subscripts, eg, x_i_i not working
- nesting fonts changes in sub/superscript groups not parsing
- no rotations yet
- no kerning
I would like to add more layout commands, like \frac.
Backends: This currently works with Agg, GTKAgg and TkAgg. If David
incorporates ft2font into paint, it will be easy to add to Paint. I
think I can also add it to GTK rather straightforwardly, since it's
just a matter of rendering from the ft2font pixel buffers; ditto for
wx. PS will require more substantial work, doing the metrics and
layouts with the AFM versions of the computer modern fonts. Backends
which don't support mathtext will just render the TeX string as a
literal.
CVS is updated - or if you prefer, I uploaded a snapshot to
Let me know how it goes! I expect there will be plenty of issues
cropping up.
JDH
Allowed TeX symbols:
\Delta \Downarrow \Gamma \Im \LEFTangle \LEFTbrace \LEFTbracket
\LEFTparen \Lambda \Leftarrow \Leftbrace \Leftbracket \Leftparen
\Leftrightarrow \Omega \P \Phi \Pi \Psi \RIGHTangle \RIGHTbrace
\RIGHTbracket \RIGHTparen \Re \Rightarrow \Rightbrace \Rightbracket
\Rightparen \S \SQRT \Sigma \Sqrt \Theta \Uparrow \Updownarrow
\Upsilon \Vert \Xi \aleph \alpha \approx \ast \asymp \backslash \beta
\bigcap \bigcirc \bigcup \bigodot \bigoplus \bigotimes
\bigtriangledown \bigtriangleup \biguplus \bigvee \bigwedge \bot
\bullet \cap \cdot \chi \circ \clubsuit \coprod \cup \dag \dashv \ddag
\delta \diamond \diamondsuit \div \downarrow \ell \emptyset \epsilon
\equiv \eta \exists \flat \forall \frown \gamma \geq \gg \heartsuit
\imath \in \infty \int \iota \jmath \kappa \lambda \langle \lbrace
\lceil \leftangle \leftarrow \leftbrace \leftbracket \leftharpoondown
\leftharpoonup \leftparen \leftrightarrow \leq \lfloor \ll \mid \mp
\mu \nabla \natural \nearrow \neg \ni \nu \nwarrow \odot \oint \omega
\ominus \oplus \oslash \otimes \phi \pi \pm \prec \preceq \prime \prod
\propto \psi \rangle \rbrace \rceil \rfloor \rho \rightangle
\rightarrow \rightbrace \rightbracket \rightharpoondown
\rightharpoonup \rightparen \searrow \sharp \sigma \sim \simeq \slash
\smile \spadesuit \sqcap \sqcup \sqrt \sqsubseteq \sqsupseteq \subset
\subseteq \succ \succeq \sum \supset \supseteq \swarrow \tau \theta
\times \top \triangleleft \triangleright \uparrow \updownarrow \uplus
\upsilon \varepsilon \varphi \varphi \varrho \varsigma \vartheta
\vdash \vee \wedge \wp \wr \xi \zeta
Vittorio Palmisano <redclay@...> writes:
> Hello,
> I have updated my debian packages for Matplotlib, and I put the installation
> instructions on my page:
Hello Vittorio,
Thanks much for doing this. I am just now taking it for a test drive
on a debian machine I have access to.?
Thanks again,
JDH
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hello,
I have updated my debian packages for Matplotlib, and I put the installation
instructions on my page:
These are the packages I've build:
python-gdmodule 0.52
python-matplotlib 0.50-1
python-matplotlib python-matplotlib-doc 0.50-1
python-pypaint 0.3
python-ttfquery 1.0.0a1
python-matplotlib-doc is a documentation package made with pydoc.
- --
/Vittorio Palmisano/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird -
iD8DBQFAOPj2pT6bvDtyXOIRAjTqAJ99uxVxbH//QG32f/xC+UCURBYyYACgilk+
bLZtzF0xGJIP0KmHiJiU1Nk=
=CqiV
-----END PGP SIGNATURE-----
John Hunter wrote:
>?
See
AMS Fonts (Truetype)
TTF versions of the American Mathematical Society Computer Modern fonts,
aka the BaKoMa fonts by Boris Malyshev. The truetype versions of the AMS
fonts are included in PCTeX.
-- Paul
--
Paul Barrett, PhD Space Telescope Science Institute
Phone: 410-338-4475 ESS/Science Software Branch
>>>>>
>>>>> "John" == John Hunter <jdhunter@...> writes:
John> * clipping appears broken: arctest.py, legend_demo.py, and
John> so on. This used to work, right?
John> * dotted lines are solid: see any plot with grid(True),
John> eg, log_test.py. Ditto for dashed lines: eg, plot(t3,
John> cos(2*pi*t3), 'r--') appears solid.
Both of these problems are arising from the select / unselect thing in
the GC. Since these changes were in response to the double gc problem
which no longer exists, I'm simply going to 'pass' in select and
unselect for the next release (which fixes both problems) above.
backend wx now passes all the tests, except the known issues.
I also added some more of the dpi scaling functionality to wx
(linewidth and markersize via the new renderer method
points_to_pixels). The last remaining area is dash size which is more
difficult since wx uses a constant for dash drawing rather than an ink
on/off approach. Does wx also support on/off? If I recall correctly,
you experimented with this but had a hard time getting it working right.
In any case the high res (eg dpi=300) wx output looks great.
There also seems to be an issue with getting the text bounding box
right with fontangles and fontweights that are not standard. To
experiment with this, uncomment 'if 0' on or around line 416 is
axis.py and run text_handles.py or text_themes.py. This will draw the
bbox around you text instance.
JDH
pypaint 0.3
-----------------
This module provides a light Python wrapper for libart written in C. It
allows you to create static images quickly. pypaint runs on both Linux and
Windows.
It only provides basic functionality at the moment - line drawing,
rectangles, polygons, arcs, fill, and simple font support (using freetype
1). The images are output in PNG format.
There will be support for a pypaint backend in the next release of
matplotlib.
pypaint is available at. In
future, there will be a homepage up at
David Moore
Software Consultant
St. James Software
Phone: +27 21 424 3492
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system ().
Version: 6.0.580 / Virus Database: 367 - Release Date: 2004/02/06
>>>>> "David" == David Moore <davidm@...> writes:
David> Sorry, last email wasn't to the list. From posts you've
David> made, it looks like you've made some changes to pypaint.
David> Do you want those committed before a pypaint release?
David> Apart from that, I'm just tying up some loose ends, and
David> then I'll be able to make the release - hopefully today,
David> but maybe only Monday if you want your changes added.
I don't have anything to add. I tried to get clipping working but
didn't succeed. I think there are two problems
1) libart wants to paths to be counter clockwise for clipping to work
(at least that's what I was told on the libart list), and I don't
think all the path constructors insure this, eg draw_arc.
2) even when the paths are constructed properly, I think there is a
problem in libart that causes clipping artifacts.
So I think you'll be fine going with what you've got for now. It
would be great to get clipping worked out in the long run, but I don't
see any immediate solutions.
On the font front: as I mentioned earlier, I ported font.c to agg and
it's working. For high resolution images it works great. For small
images (eg, dpi=60) the fonts look pretty bad. I think this is the
same for paint and agg, at least in the comparisons I've looked at.
This isn't surprising since the font code is the same. The two areas
where small rasters come up are for web pages (which is where I assume
your interests are) and embedding in GUI applications (which is
important to me).
Is this why you want to upgrade to freetype2? From my reading of some
of the docs there, this is one thing that freetype2 does better.
JDH
On Saturday 14 February 2004 8:03 am, you wrote:
> Thanks for the pointers.
>
> On Friday 13 February 2004 9:20 pm, you wrote:
> > I made some progress!
>
> [snup]
>
> > The bug was a line I introduced when I added some more print
> > debugs
>
> I had fixed this one...
>
> > The front end change that is causing your problems is that I now pass
> > a gcedge and a gcface. I used to pass a gcface and a face color.
> > Maybe I'll revert to that.
> >
> > When I instantiate a gcedge and a gcface on the front end, you make 2
> > calls to new_gc
> >
> > def new_gc(self):
> > """
> > Return an instance of a GraphicsContextWx, and sets the current
> > gc copy """
> > DEBUG_MSG('new_gc()', 2, self)
> > self.gc = GraphicsContextWx(self.bitmap, self)
> > assert self.gc.Ok(), "wxMemoryDC not OK to use"
> > return self.gc
> >
> > I think initing 2 GCs with the same bitmap is causing the problem. If
> > you see an easy backend solution, that would be ideal. If not, I
> > could re-refactor the frontend to be like it was: pass a gcedge and a
> > facecolor.
>
> This is, indeed, illegal in wx. It sometimes works under Windows, but
> consistently fails (dramatically) under Linux (at least for wxGtk).
To be more exact about what happens, here is the synopsis:
In patches.py, Patch._draw() instantiates two gc instances
def _draw(self, renderer, *args, **kwargs):
#here=============>
gc = renderer.new_gc()
gc.set_foreground(self._edgecolor)
gc.set_linewidth(self._linewidth)
gc.set_alpha(self._alpha)
if self._clipOn:
gc.set_clip_rectangle(self.bbox.get_bounds())
if not self.fill: gcFace = None
else:
#and here===========>
gcFace = renderer.new_gc()
gcFace.set_foreground(self._facecolor)
gcFace.set_alpha(self._alpha)
self._derived_draw(renderer, gc, gcFace)
Each call to backend_wx.py RendererWx.new_gc() does the following:
self.gc = GraphicsContextWx(self.bitmap, self)
assert self.gc.Ok(), "wxMemoryDC not OK to use"
return self.gc
But instantiating a GraphicsContextWx does:
def __init__(self, bitmap, renderer):
GraphicsContextBase.__init__(self)
wxMemoryDC.__init__(self)
DEBUG_MSG("__init__()", 1, self)
# Make sure (belt and braces!) that existing wxDC is not selected to
# to a bitmap.
if GraphicsContextWx._lastWxDC != None:
#the gcEdge gets selected into a NULL bitmap here
GraphicsContextWx._lastWxDC.SelectObject(wxNullBitmap)
self.SelectObject(bitmap)
self.SetPen(wxPen('BLACK', 1, wxSOLID))
self._style = wxSOLID
self.renderer = renderer
GraphicsContextWx._lastWxDC = self
You will note that in order to enforce the wx rule that no more than one
wxMemoryDC can be selected into a bitmap, I ensure that the last wxMemoryDC
instance activated is selected to a wxNullBitmap.
In the case of the above code, this means that the gc representing the
rectangle has already been selected to a NULL bitmap. When you try to draw to
this, an exception is generated within the C++ code which is not propagated
back up to the Python layer. Unfortunately, the assert() calls don't help
much here as each gc instance is OK when it is constructed.
I'm afraid I'd missed the significance of the change from a facecolor to a
gcFace for fill colours.
> I'll see if I can come up with any ideas, but passing a gcedge and
> facecolor is likely to be simpler to get to work reliably.
I have thought about this, and to only other option I can think of is for me
to select between 'currently active' gc instances as required. Obviously,
this would probably slow backend_wx down, but I'm not yet sure what the
performance hit will be. Let me try it...
[an hour or so later...]
Attached is a backend_wx which seems to work with most of the examples I've
tried (Linux only - expect Windows to work as it's generally better behaved
than wxGtk, but would be nice if someone would try it.
Some issues (for now):
- Clipping seems to be broken (c.f. arctest.py)
- Object picker demo doesn't work (haven't implemented this functionality)
- Some types of dotted lines are not working properly (c.f. subplot_demo.py)
- embedding_in_wx doesn't work - due to some of the recent API changes. I'll
fix this one pretty soon - it shouldn't be much work.
- It's about 20% slower than the previous implementation in which only one GC
was active at a time.
Not sure if the dotted lines and clipping are down to information being lost
when I switch between gcs - I'll have to look into this, but the attached
will be a good start for getting things to work on wx again.
John, I'll leave it as your call whether you want to switch the API back to
using a facecolor instead of a gcFace. It would be better from the wx
perspective, but there may be good reasons for doing otherwise on other
backends.
There are a couple of optimisations I can probably make to speed things a
little if we stick with the current API -it should be possible to do
something slightly more intelligent than simply selecting a bitmap at the
start of each call, and deselecting it afterwards - although, as noted above,
wxMemoryDC seems to be extremely fragile under wxGtk - not sure why.
I have checked the attached into CVS for now, but we may have the usual
'mirror update' issue.
Regards
Jeremy
>>>>> "Vittorio" == Vittorio Palmisano <redclay@...> writes:
Vittorio> I have rebuild the package with support for gtkgd. I
Vittorio> have tried to build also the agg backend, but I can't
Vittorio> find the source package for this library! I've found two
Vittorio> version: one from and another from
Vittorio> scipy cvs, but seems that there are some missing headers
Vittorio> when I compile the backend. I have also packaged the
Vittorio> gdmodule from
Vittorio>
Vittorio> and the ttfquery module from
Vittorio>, all the debs
Vittorio> are on
Wow, amazing work.
You may want to look at the header of matplotlib.backends.backend_agg
- this includes some install instructions, where to get agg, etc...
However, that may not be necessary.
I have built a new sdist that has all the prereqs for agg built in
(fonttools, ttfquery, and agg2). You just have to set BUILD_AGG in
setup.py and it should build, as long as your compiler is fairly
recent. I'll leave it to you whether you want to use debian to get
fontools and ttfquery, or use the ones included with matplotlib. I
stripped all the fluff out of those 3 packages and with everything
included the sdist is still under a megabyte.
I used this to build an all-in-one win32 installer, which will be nice
because now win32 users with Numeric can make PS and PNG plots out of
the box (zlib, libpng, freetype are statically built in).
I'm going to upload the snapshot if you want to experiment with it. I
should warn you though: I forgot yesterday that there is still a
critical bug in wx that must be repaired. Thus there will be one more
revision following this one. (Sorry)
JDH
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
John Hunter ha scritto:
>
>.
>
I have rebuild the package with support for gtkgd.
I have tried to build also the agg backend, but I can't find the source package
for this library! I've found two version: one from and
another from scipy cvs, but seems that there are some missing headers when I
compile the backend.
I have also packaged the gdmodule from and the ttfquery module
from, all the debs are on
I can write some documentation about debian packages required, once I've tested
them, but only for the next weekend, bye
- --
/Vittorio Palmisano/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird -
iD8DBQFALOhdpT6bvDtyXOIRAiQGAKDDQCrh0sELN09vI2dKYVfTKZ9H4ACgr8o2
ezklwMSi/Ke3zY5kK8DWwsI=
=SX+C
-----END PGP SIGNATURE-----
Almost
>
> On the topic of releases: David, my target date is early next week.
> Do you think you can get pypaint up by then?
>
> Thanks again,
> JDH
>
Hi John,
Sorry, last email wasn't to the list. From posts you've made, it looks like
you've made some changes to pypaint. Do you want those committed before a
pypaint release? Apart from that, I'm just tying up some loose ends, and
then I'll be able to make the release - hopefully today, but maybe only
Monday if you want your changes added.
thanks,
David Moore
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system ().
Version: 6.0.580 / Virus Database: 367 - Release Date: 2004/02/06
>>>>> "Vittorio" == Vittorio Palmisano <redclay@...> writes:
Vittorio> Ok, I have fixed this problems, now "lintian -i
Vittorio> python-matplotlib_0.50-1_i386.changes" doesn't say
Vittorio> nothing. I have updated the files on my repository, bye
Hi Vittorio, thanks a bunch for doing this. A lot of people have
asked for this, and there's been incremental progress here and there,
but I'm glad to see you got everything done..
On the topic of releases: David, my target date is early next week.
Do you think you can get pypaint up by then?
Thanks again,
JDH
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Jochen Voss ha scritto:
> Hi Vittorio,
>
>
>
Ok, I have fixed this problems, now "lintian -i
python-matplotlib_0.50-1_i386.changes" doesn't say nothing.
I have updated the files on my repository, bye
- --
/Vittorio Palmisano/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird -
iD8DBQFALBMapT6bvDtyXOIRAotMAKCKjRsSkEqW1+ZghHsbPTPSkxiK5gCfcse1
nTVo7VRSpn42CrynvFDGNKY=
=yfL1
-----END PGP SIGNATURE-----
Hi Vittorio,
On Thu, Feb 12, 2004 at 11:14:19PM +0100, Vittorio Palmisano wrote:
> I've made a Debian package for matplotlib and I've put it at:
>
--=20
Hello,
I've made a Debian package for matplotlib and I've put it at:
I've read some specification for dependencies from,
this is my first package and so there are some (many?) things to fix.
I think that the package may also include the api documentation generated with pydoc.
--
/Vittorio Palmisano/
On Tue, 2004-02-10 at 16:30, John Hunter wrote:
> I just made a minor change in the backend API. The faceColor argument
> (formerly a color arg) for draw_rectangle, draw_arc, etc... is now a
> graphics context instance. I updated all the backends in CVS.
>
Hi John,
I'm working with Perry Greenfield's group on a Tkinter/Paint backend for
matplotlib. I noticed today that the paint facecolor had changed to
black. Looking into it, there were a few more edits to
backend_paint.py needed as a result of the interface change above. I
also noticed that the paint version of draw_polygons needed a little
code to get it working. Attached is a patch for both.
Regards,
Todd
--
Todd Miller <jmiller@...>
The agg backend
Features that are implemented
* capstyles and join styles
* dashes
* linewidth
* lines, rectangles, ellipses, polygons
* clipping to a rectangle
* output to RGBA and PNG
* alpha blending
* DPI scaling - (dashes, linewidths, fontsizes, etc)
* freetype1
TODO:
* use ttf manager to get font - right now I just use Vera
INSTALLING
Grab the latest matplotlib from
REQUIREMENTs
python2.2+
Numeric 22+
agg2 (see below)
freetype 1
libpng
libz ?
Install AGG2 (cut and paste below into xterm should work)
wget
tar xvfz agg2.tar.gz
cd agg2
make
(Optional) if you want to make the examples:
cd examples/X11
make
Installing backend_agg
Edit setup.py: change aggsrc to point to the agg2 src tree and
replace if 0: with if 1: in the backend_agg section
Then just do the usual thing: python setup.py build
Please let me know if you encounter build problems, and tell me
platform, gcc version, etc... Currently the paths in setupext.py
assume as linux like filesystem (eg X11 include dir, location of
libttf, etcc) so you may need to tweak these.
Using agg backend
python somefile.py -dAgg
or
import matplotlib
matplotlib.use('Agg')
Let me know how it works out! Note also that backend agg is the first
backend to support alpha blending; see scatter_demo2.py.
JDH
|
http://sourceforge.net/p/matplotlib/mailman/matplotlib-devel/?viewmonth=200402
|
CC-MAIN-2016-07
|
refinedweb
| 3,602
| 63.7
|
Hi,
AFAIU ContentSession.getCurrentRoot() will return the most
up to date version of the root, which provides access to a
snapshot of the tree. In oak-jcr this method is used when
a SessionDelegate is created and the root is initialized with
getCurrentRoot(). Later on this root is used for operations
on the tree.
now, there are also a lot of other places where getCurrentRoot()
is called. some of these look a bit suspicious to me. the
namespace registry and node type manager operate mostly
on fresh snapshots of the tree for each method call. doesn't
that always result in a call all the way down to the microkernel?
I know that both namespace and node type management are
considered repository wide and not bound to the current session,
but it seems excessive to always get a new snapshot for a
namespace uri to prefix mapping that rarely changes.
another usage I noticed is in Query.getTree(String). Shouldn't
the query rather operate on the same stable tree as seen by
the JCR session?
Regards
Marcel
|
http://mail-archives.apache.org/mod_mbox/jackrabbit-oak-dev/201209.mbox/%3C9C0FC4C8E9C29945B01766FC7F9D389816FE0B2244@eurmbx01.eur.adobe.com%3E
|
CC-MAIN-2014-23
|
refinedweb
| 178
| 72.56
|
- NAME
- SYNOPSIS
- DESCRIPTION
- AUTHOR
- SEE ALSO
NAME
Test::Debugger - Create Test Scripts which Generate Log Files
SYNOPSIS
use Test::Debugger; plan(tests => 1, log_file => 'test.log'); ok($actual, $expected, $message, $error); # OR Object-Oriented use Test::Debugger; my $t = Test::Debugger->new( tests => 1, log_file => 'test.log', ); # set the order of the parameters passed to 'ok' $t->param_order('ok' => [qw(self expected actual message error)]); $t->ok($expected, $actual, $description, $error_message); $t->todo($expected, $actual, $description, $error_message); $t->skip($because, $expected, $actual, $description, $error); $t->ok_ne($expected, $actual, $description, $error_message); $t->ok_gt($expected, $actual, $description, $error_message); $t->ok_ge($expected, $actual, $description, $error_message); $t->ok_lt($expected, $actual, $description, $error_message); $t->ok_le($expected, $actual, $description, $error_message); $t->ok_re($expected, $actual, $description, $error_message);
DESCRIPTION
Have you ever tried to debug a test script that is failing tests? Without too many modifications, your test script can generate a log file with information about each failed test.
You can take your existing test script, and with (hopefully) very little effort, convert it to use Test::Debugger. Then re-run your modified test and view the log file it creates.
Object-Oriented Interface
Test::Debugger can be run using exported subroutines, or using an object-oriented interface.
The object-oriented interface allows for easier access to some types of functionality, such as comparision operators other than 'eq'.
You start by creating a test object.
my $t = Test::Debugger->new(%params);
The
new method calls
plan automatically, so you can pass your
plan parameters directly to
new.
The three most basic methods are
ok,
todo and
skip. You can rearrange the order of the parameters to these methods by running
param_order. You must run
param_order for the testing subroutines to work as methods.
$t->param_order('ok' => ['self', 'actual', 'expected']);
The key here is the word self. The default param order does not include self as a valid parameter. The example above sets the valid parameters to pass to
ok, including the test object, the value we are testing, and the value we expect it to match against.
A parameter order need only be assigned for
ok. The
todo and
skip methods will mimic the order assigned for
ok, if they are undefined.
Now we can set up our tests:
$t->ok($actual, $expected);
An explanation of each method can be found further down in this document.
Subroutine Interface
The interface for Test::Debugger is based loosely on the interface for Test.pm. You have four subroutines exported into your namespace:
plan,
ok,
skip, and
todo.
You should
plan, but it is not as strictly enforced as in Test.pm.
The default order of arguments to
ok and
todo is:
ok($actual, $expected, $message, $error, $operator);
You must supply at least an
$actual value, and you should supply the first three parameters. You can change the order of the parameters with
param_order.
Log File
I generally name my test log file 'test.log', and add an entry to my Makefile.PL to remove it on 'make clean'.
WriteMakefile( ... 'clean' => { 'FILES' => 'test.log', }, );
If a test fails, is skipped, or is marked todo (and fails), an entry is made to the log file. Each entry looks similar to this:
t/todo.t 1 TODO. should fail as TODO ### Expected ### 1 ### Actual Results ### 0
The first part is the name of the test file. The number is the subtest within the test file. The word
TODO means that this test was not expected to succeed, because code it relies on is not finished. This word could also have been
FAILED or
SKIPPED.
On the second line, we see the
$message provided to the test. We would see the
$error on the third line, if that had been provided.
Then the expected value and the actual value are displayed. An extra newline is appended to the actual value, in the log file, so that there is a blank line between entries.
Extra Debugging
If the test log file is not sufficient to debug your code, or your test, you may enable the
note subroutine of Devel::Messenger and write to another file, perhaps called something like 'debug.txt'.
use Devel::Messenger qw(note); local *Test::Debugger::note = note { output => 'debug.txt' };
Test::Debugger will
note the test it is working on. You can then place notes in your module, and they will be grouped by test number.
Methods/Subroutines
Most methods may be called as a subroutine, rather than as a method.
- new
Creates a new Test::Debugger instance and returns a handle to that instance. Accepts a HASH of parameters, which is passed to the
planmethod.
Not available as a subroutine.
- next_test_number
Takes a number to store internally as the next test number.
$t->next_test_number(1); $next_test = $t->next_test_number();
Returns the number of the next test to be run.
- param_order
Allows you to specify in which order you shall submit parameters.
$t->param_order($method => \@order);
The key words allowed in the
@orderarray are:
self Test::Debugger object expected the value you expect to get actual the value you are testing message description of the test error an error message to log operator Perl comparison operator
You may include as many or few of these items as parameters, as long as
actualis always present.
- plan
Sets up some internal variables, such as where to log errors.
$t->plan( 'skip' => $because, 'skip_message' => $explanation, 'tests' => $total_number_of_tests, 'todo' => [@tests_to_skip], 'log_file' => $filename, 'start' => $number, 'param_order' => { 'ok' => ['actual', 'expected', 'message', 'error'], }, );
If you do not include a
testsparameter, you must print the line:
"1..$number\n"
Otherwise Test::Harness will not know how many tests there are.
If the
$becauseof the
skipparameter is true, the entire test file will be skipped.
- ok
Takes parameters which may include a Test::Debugger object handle, an actual value, expected value, description of the test, error message, and the Perl comparision operator to use.
See
param_orderfor information on specifying the order of parameters.
Compares the actual and expected values (or determines the truth if only the actual value is specified in
param_order). Prints "ok $number\n" on success, or "not ok $number $message\n" on failure.
$t->param_order('ok' => ['self', 'expected', 'actual', 'message']); $t->ok('Test::Debugger',ref($t),'testing value of ref');
An expected value of
qr/regex/will try to match
$actual =~ qr/regex/.
$t->ok(qr/help/, 'help me', 'testing regex');
Returns true if the test does not fail.
- ok_<operator>
Takes the same arguments as
ok. Prints the same output as
ok. Allows for the use of operators other than 'eq' to compare expected and actual values. Available operators are:
ne not equal gt greater than ge greater than or equal to lt less than le less than or equal to re regualar expression
Each operator is converted to the numeric equivalent if both arguments contain nothing other than numbers.
Not available as subroutines.
- skip
Skips a single test if a condition is met.
$t->skip($because, $expected, $actual, $description);
Prints "ok $number skip: $description\n", if
$becauseis true. Returns true if the test succeeds, or if it is skipped.
- todo
Skips a single test, or marks it TODO, because you are still working on the underlying code.
$t->todo($expected, $actual, $description);
Output depends on the version of Test::Harness you are using. Always returns true.
AUTHOR
Nathan Gray - kolibrie@southernvirginia.edu
You may distribute under the terms of either the GNU General Public License, or the Perl Artistic License.
SEE ALSO
perl(1), Test::Harness(3), Devel::Messenger(3).
|
http://web-stage.metacpan.org/pod/release/KOLIBRIE/Test-Debugger-0.14/Debugger.pm
|
CC-MAIN-2020-29
|
refinedweb
| 1,245
| 56.05
|
On August 26, 2003, Namco released Soul Calibur II for home gaming
consoles in the United States and Canada. Versions for PlayStation 2,
Xbox, and GameCube were released
on the same day for the same price of US$49.99 (MSRP excluding tax).
All three versions are excellent; I own the PS2 version and have played the
two others on friends' consoles.
This game is one of the best fighting games you can get for a home
console. It follows the original Soul Calibur, which was released for
the ill-fated Sega Dreamcast, in providing excellent replay value and
good qualities all around.
First off...
People expect a laundry list of unlockable characters in a console fighting game. Soul Calibur II
provides a few: Lizardman, Assassin, Berzerker, Sophitia, and
Seung Mina can all be unlocked after enough play. However, what sets
the different versions of Soul Calibur II apart are the console-specific
characters.
Every console gets Necrid, a Todd McFarlane character who
can use several other characters' weapons to do special moves. One additional
character is provided in each version, and cannot be accessed on any other
console:
While Necrid frequently appears in Weapon Master and arcade mode,
the console-specific character is mainly for the benefit of human players.
Seasoned players now need to learn how to guard against three new characters,
which may be tough for those who only have one game console at home.
The console-specific characters are not present in the Japanese
version of Soul Calibur II, oddly enough. They are only present in the
North American version, and should be in the European release as well.
The game looks and sounds the same on any console, but the different
control pads control the game in a slightly different manner.
Personally, I recommend the use of
an arcade stick no matter what console you use. Electronics Boutique
sells the Gamester Reflex arcade stick for PlayStation 2 and Xbox for
about US$25. Hori makes a stick specifically designed for Soul Calibur II
(complete with character art as decoration) for the PlayStation 2 and
GameCube, but it's a Japanese item and costs $60-70 from your average
import shop. The X-Arcade joystick, at about $100 for one player or
$150 for two, provides a real arcade feel and can connect to any system
with extra adapters (one included; extras cost $20-30 each).
If you're not willing to take the plunge for an arcade stick, the PS2
Dual Shock 2 controller feels most like the old Dreamcast setup. The Xbox's
buttons are also set up in a diamond shape and mapped as on the
Dreamcast and PS2. The GameCube controller's buttons are shaped differently,
and from my experience require the most learning curve and/or
reconfiguration before they become comfortable. Mapping a shoulder button
to 'guard' helps with throws and some special moves.
The game is a quantum leap above the original, with graphics on par with
any current-generation fighter (Virtua Fighter 4, Tekken 4, and
Dead or Alive 3, to name a few). I haven't noticed a difference among
the three systems using standard RCA outputs, but reviews suggest that
the PS2's graphics look slightly jaggy when using component video for
high definition output. The fighters are impeccably detailed and shaded,
complete with obligatory T&A for the ladies, and the environments have
fully 3-D backgrounds. Unlike DoA, there's no way to knock people into other
sections of a stage. Some environments have ring outs on all sides; others
are fully enclosed; and others still are partially enclosed.
Playing the Weapon Master mode lets you unlock extra artwork, both
hand-drawn and computer animated.
Like the original, Soul Calibur II features a rousing orchestral score.
In Japan, an OST sells for ¥3500 (about US$30) and includes a
companion book. Soul Calibur II supports 5.1 channel surround sound on
all platforms, although I haven't been able to test it. It sounds awesome
on a good two-speaker setup.
The voice acting, expectedly, is atrocious. You have the option of
hearing the tiresome pre-fight taunts in English or Japanese, but it
would have been nice to just skip them altogether. Listen to the announcer's
overblown intros ("A tale of souls and swords, eternally retold...") for
comic relief only.
Weapon Master mode replaces the Conquest mode that gave the arcade game
such a lasting appeal. In Weapon Master, as in the original's "Mission Mode,"
you must defeat enemies using a certain technique. For example, some missions
require you to use guard impacts or unblockable moves; other moves have
zero effect. Some missions are incredibly frustrating, and must be reloaded
from scratch when failed. The lack of a "Retry" button is frustrating,
although "Give Up" is conveniently provided in case you can't wait 20
seconds to lose the mission.
As you go through the levels of Weapon Master mode, including dungeon
levels and extra levels the second time through, you earn gold and
experience. Experience points let you increase in level, although this
doesn't improve your character any; and Gold lets you buy extra weapons and
features. The strength of Weapon Master mode is in the ability to use up to
ten weapons for each character. Each has its pros and cons.
For example, Kilik's
Kunlun Bamboo slowly heals Kilik but does less damage than Kilik's other
weapons. Choosing the right character and the right weapon makes a big
difference in many missions.
Weapon Master mode compels you to play with the lure of unlocking hidden
features, but at the same time teaches you the proper techniques of fighting.
Among the features unlocked are "Extra" modes like "Extra Arcade" that let
players use acquired weapons in otherwise normal one-player and two-player
games.
Buy this game.
Learn Soul Calibur II. Learn to guard impact. Learn how stances and
well-thought-out soul charges are Namco's answer to
Super Turbo Level 3 Ultra X Tag Combos popularized by
Capcom and SNK alike. Play the game, fail a Weapon Master mission
13 times in a row, then come back so you can unlock Sophitia's third
costume.
Soul Calibur II is one of the few games that costs fifty dollars and is
worth every penny.
Need help? accounthelp@everything2.com
|
https://everything2.com/user/generic-man/writeups/Soul+Calibur+II
|
CC-MAIN-2018-13
|
refinedweb
| 1,062
| 61.77
|
Every); ...
Benefits of WSIF.
The other volatile aspect of these services is location. A service that may have been available locally may suddenly be moved to servers on the other side of the globe. As a practice, experienced designers have learned to externalize the location of such services; however, enforcing such rigors in a large and complex enterprise solution developed and maintained by a global fleet of designers and developers proves difficult.
Typically, SOAP is touted as panacea for such pain points. SOAP has been a unifying protocol, but its implementation, from a practical perspective, has limitations. First, not all services may be enabled as SOAP-based services. There could be significant cost implications in enabling all the services developed over the years as SOAP-based services. Second, using SOAP has performance implications. Benchmarking comparisons indicate that SOAP calls using Apache Axis have several hundred times more latency than Java RMI (remote method invocation) calls (see "Latency Performance of SOAP Implementations" (IEEE Cluster Computing and the Grid, 2002)). Considering the performance impact, it would be unreasonable to expect Java clients to use SOAP for accessing EJB components to gain platform and location independence.
WSIF, modeled after WSDL (Web Services Description Language), is more suitable for alleviating such problems. For a given service, WSIF uses a WSDL-based XML file so that custom wrappers for new or existing Java and EJB objects are not needed. WSDL provides definitions of services: it defines the interface consisting of functions, parameters, return values, and exceptions and the binding consisting of the service's implementation specification and location. WSDL was designed with extensibility in mind. In a typical SOAP-based Web service, the binding is almost always
soap:binding. WSDL provides plug-ins to other bindings such as Java and EJB. WSIF exploits this specific WSDL extensibility. I describe more on this extensibility in later sections.
Using WSIF
There are two invocation models for using the WSIF API: stub invocation or dynamic invocation. The stub model relies on stubs at the client side; service functions are invoked on these stubs. This approach offers a more natural way of programming and has the benefits of compiler-checked code. The dynamic model programmatically constructs service calls. This model suits those applications that want a more abstract view of a service.
To better understand these invocation models, let's look at an example that provides a stock price. The service
StockQuote has a single call,
getQuote(), that expects a string. Let's first look at a stub"); // Create the service stub, StockQuote.class is a class generated by WSDL2Java for // StockQuote service WSIF configuration file. 8. StockQuote stub = (StockQuote) service.getStub(StockQuote.class); // Call the function to get the stock price. 9. string symbol = "IBM"; 10. float result = stub.getQuote(symbol); 11. system.out.println("Price for " + symbol + " is " + result); ...
On Line 1, an instance of a WSIF factory is created, which initializes the WSIF framework if it has not already initialized.
On Lines 2 through 7, the WSIF factory retrieves instances of specific services. The WSIF factory is supplied the WSIF-WSDL file location, service namespace, service name, port-type namespace, and port-type name. The service namespace and service name can be left as null if the WSDL file contains only one service definition and location. The WSIF parses the WSIF-WSDL file to create instances of services requested.
On Line 8, a stub instance is retrieved. Calls are made against this stub. Stub classes can be created using the WSDL2Java tool, an industry-standard tool for generating Java proxies and skeletons for services with WSDL descriptions. WSIF uses client-side proxies generated using the following command:
%java org.apache.axis.wsdl.WSDL2Java (WSIF-WSDL-file-URL).
On Line 10, an actual call is made against the stub. Here, the WSIF framework internally maps to the appropriate port-type implementation specified in the WSIF-WSDL file and places a call to the endpoint. The value returns to your client code.
Now let's look at a dynamic"); // Get the port. 8. WSIFPort port = service.getPort(); // Create the operation. 9. WSIFOperation operation = port.createOperation("getQuote"); // Create the input, output, and fault messages for the operation. 10. WSIFMessage input = operation.createInputMessage(); 11. WSIFMessage output = operation.createOutputMessage(); 12. WSIFMessage fault = operation. createFaultMessage(); // Populate the input message. 13. String symbol = "UIS" 14. input.setObjectPart("symbol", symbol); // Do the invocation. 15. operation.executeRequestResponseOperation(input, output, fault); // Extract the result from output message. 16. float result = output.getFloatPart("result") ...
In the dynamic invocation, Lines 1 through 7 match the code in the stub invocation. On Line 8, a port is created for the service; on Line 9, a specific operation of interest is created. On Lines 10, 11, and 12, input, output, and fault messages are created. For the
getQuote() operation, we have string input and string output. The input values are set in Line 14, and finally, on Line 15, the operation is invoked. On Line 16, the stock price value is retrieved.
Using WSIF step by step
- Download the WSIF framework from Apache.
- Run
wsif-2.0\classpath.batto set appropriate classpath. This script also sets the classpath for samples included in the download. You may need to modify this file depending on your development environment.
- Create a WSIF-WSDL file for your service provider. For SOAP-based applications, you could use its WSDL as a starting point. For Java and EJB applications, you could use Java2WSDL. And, for adventurous types, you could create WSDL by hand.
- Run
WSDL2Javato create Java stubs for the WSDL.
- Modify WSDL to include WSIF extensions for Java, EJB, etc., depending on type of service provider.
- Place WSIF-WSDL file and stubs in your application's directory path.
- Start using WSIF in your application.
WSIF and service-oriented architecture
SOA-based services must adhere to three basic tenets:
- Interface contract is platform-independent
- Service can be dynamically located and invoked
- Service is self contained
WSIF takes your code a few steps closer to service-oriented architecture:
- WSIF's WSDL-based interface description of services provides platform-independent interface definitions in
portType.
- The WSIF framework automatically locates component locations specified in the WSDL-based XML configuration file. The choice of implementation can be deferred until runtime.
- Being a client-side framework, WSIF cannot make a service self contained; however, WSIF works best with self-contained services and does not require state management between calls.
WSIF Java extension and WSDL
Let's walk through a structure of WSDL to see how WSIF extends WSDL. WSDL is an XML file with four main sections:
- Definitions
- Types
- Bindings
- Services
WSIF extends WSDL's bindings and services sections to specify WSIF providers. Bindings allow plug-ins of various providers. Thus, WSIF has providers for Java, EJB, SOAP, J2EE Connector Architecture, etc. These providers enable the invocation of corresponding services.
We will take a publicly available WSDL file at to understand various sections of WSDL and how WSIF extends such a file. For a more detailed explanation of WSDL, please see Resources. The WSDL delayed-quote service file is available here:.
Definitions
Let's look at the first two lines of the delayed-quote service WSDL file downloaded from the site above. This is the definitions section of the WSDL file:
<definitions name="net.xmethods.services.stockquote.StockQuote" targetNamespace=". stockquote.StockQuote/">
The definitions section is WSDL's root element and is a container for all other WSDL elements. It holds all necessary information about the service and its attributes. The
definitions element's
targetNamespace attribute is required and points to a URI that demarcates this WSDL file's namespace. The WSIF service definition requires the addition of a few namespaces as indicated below.
targetNamespaces differentiate definitions from element declarations in different vocabularies. This means various elements defined in this WSDL file belong to the namespace.
|
https://www.javaworld.com/article/2072290/soa/bridging-islands-of-enterprise-software.html
|
CC-MAIN-2018-09
|
refinedweb
| 1,304
| 50.23
|
Simple examples about Closure in JavaScript and Ruby
.
1 key elements
There’re two key elements to be noted in those examples: function and binding. Don’t worry about what is binding now, treat it just as any variable name that references “something”.
2 Code Examples in different languages
Let’s jump in some concrete examples to demonstrate the existence of closure.
- First I’ll describe what’s the final result I want;
- Second I’ll write tests to express the expected results, then write code to try passing the test;
- during the process we’ll have short discussion and try to find out closure.
2.1 what I want: make a counter
I want to make a
counter which is a function that will use
0 as starting point then increases by
1 each time the function is called.
- set start point as
0
- create the function
counter
- call
counter→ returns
1
- call
counteragain → returns
2
- call
counteragain → returns
3
- …
2.2 Code example with Node.js + Jest:
File structure:
closure_javascript
├── counter.js
├── package.json
└── counter.test.js
package.json:
{
"scripts": {
"test": "jest"
}
}
Incorporate Jest into the project. Then run
npm install .
Note: If you use other package management tool, check Jest doc to find out how to install it. And the the name of the test file should be
counter.test.js in this case.
counter.test.js
const counter = require('./counter');test("each function call increases by 1", () => {
expect(counter()).toBe(1);
expect(counter()).toBe(2);
expect(counter()).toBe(3);
expect(counter()).toBe(4);
})
In our single test, we are expecting the returned value increases by
1 after each function call on
counter . So we expect to get
1 after first call and get
4 after the fourth call.
counter.js
function makeCounter() {
let startingPoint = 0;
return () => { return startingPoint += 1};
};let counter = makeCounter(); // the counter is actually created heremodule.exports = counter;
In
counter.js , the
counter function is not made by standard function declaration way i.e
function counter() {...}; Instead it has to be made by a wrapper function
makeCounter that returns a function
counter.
And the local variable declared in the wrapper function is somehow “carried” by the returned function. The local variable
startingPoint is bound with the returned function so that the value of the
startingPoint can keep changing after the
makeCounter wrapper has returned long before.
In other words, as long as we have access to the
counter function made by
makeCounter , we can access the
startingPoint variable declared in
makeCounter , but in a predefined way, because we won’t be able to alter the logic of function
counter after it has been made.
This binding relationship between a function and data bound with the function during its creation(the exact creation point is when we invoke the wrapper function) is one of the key elements we mentioned —
binding .
Run the test by
npm run test in terminal, test result:
PASS ./counter.test.js
✓ each function call increases by 1 (3 ms)Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.235 s
Ran all test suites.
By now we should pass the simple test.
2.3 Code example with Ruby + Minitest:
File structure:
closure_ruby
├── counter.rb
└── test_counter.rb
counter.rb
def make_counter
starting_point = 0
Proc.new { starting_point += 1 }
end
Regardless of the different syntaxes, what we do here is exactly the same as what we did when using JavaScript. The
make_counter method(I think it’s ok to call it function) is a wrapper method, it returns a
Proc object.
Note: A
Proc object is just another form of function, the ‘function body’ is written in the code block
{starting_point += 1} . And the way to invoke a Proc object is by calling
call method on it —
proc.call .
And also we declare a local variable
starting_point inside the wrapper method, the returned
proc (conceptual function) has access to that local variable. But this time we create the
counter in test file, see below.
test_counter.rb
require "./counter.rb"
require "minitest/autorun"class TestCounter < Minitest::Test
def setup
@counter = make_counter # the counter is made here
end def test_counter
assert_equal 1, @counter.call
assert_equal 2, @counter.call
assert_equal 3, @counter.call
assert_equal 4, @counter.call
end
Here
@counter is an instance variable that can be accessed by all the test methods and
@counter is a proc object(conceptually a function) that can be invoked by
@counter.call. Again in the test method we are expecting that the same thing to happen — every invoking causes
starting_point to increase by
1 so we also get
4 after the fourth invocation.
In Ruby example, the “function” element is the proc object and the “binding” element is the local variable declared in the wrapper function. Also as long as we have access to the proc, we have access to the
starting_point variable — in a predefined way.
Run the test with
ruby test_counter.rb in terminal
Run options: --seed 63631# Running:.Finished in 0.000886s, 1128.6682 runs/s, 4514.6727 assertions/s.
1 runs, 4 assertions, 0 failures, 0 errors, 0 skips
In spite of the difference in syntax and terminology, we can see the manifestation of the concept of closure. A closure is just some binding/environment/data/record, whatever you call it, carried by a function, and that function is created by another wrapper function, all the variables we want to access later by the returned function can be declared in the definition body of the wrapper function.
3 Definitions
wikipedia: In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions.
mdn:.
O’Reilly: In Ruby, procs and lambdas are closures. The term “closure” comes from the early days of computer science; it refers to an object that is both an invocable function and a variable binding for that function. When you create a proc or a lambda, the resulting Proc object holds not just the executable block but also bindings for all the variables used by the block.
4 Summary
You can think of a function as a man, and the man’s carrying a suitcase(closure), all the things(data) in the suitcase is packaged by his mom(wrapper function), and the man is ‘created’ by his mom.
Hope these simple examples in different languages can help you better understand closure from different points of view. And it takes some time and re-acquaintances to really remember how all of this closure thing work so don’t worry if you don’t get it at the first few trials.
|
https://xullnn.medium.com/simple-examples-about-closure-in-javascript-and-ruby-7d8032e49a48?responsesOpen=true&source=---------0----------------------------
|
CC-MAIN-2021-25
|
refinedweb
| 1,108
| 62.58
|
There’s a nice bit over at linux-sxs.org detailing how to install mplayer for mozilla. Should be useful for all Linux users, particularly those that use new distributions that use Mozilla as the default browser.
Installing MPlayer for Mozilla
2003-02-02 Mozilla, Gecko 23 Comments
right when I switch to konqueror 3.1 as my main browser. Is there anything like this for konqueror?
Yes there is
Greets
for those who can’t get this to work (like me), go to. it’s another plugin. all you need to do is do a “make”, then the resulting mplayerplug-in.so file must be copied in the mozilla plugin directory (mine’s at /usr/lib/mozilla/plugin/). that’s it. it works better i think. or just on my pc. i’d love to show a screenshot, but quicktime movies don’t seem to like screenshots.
mplayer-plugin works much better for me (altough I would like to have some controls and the ability to preload a streaming movie before playing it so that I can view larger movies instead of small ones only (connection is too slow)).
>> i’d love to show a screenshot, but quicktime movies don’t seem to like screenshots.
Use another video driver (no xv) or start up multiple instances of MPlayer before taking a screenshot..
Wierd things… mplayerplugin and mplayer is installed. I tried the apple switch ads, but all I get is a box with
‘mplayer pluin – Loading movie…’
That’s it. Nothing more… Anybody else had such a problem?
Nether WebfreeTv.com or mplayerplug-in work for me. All I get is ‘mplayer pluin – Loading movie…’ or ‘’. I’m running Mozilla 1.2b and Mplayer mplayer-0.90pre10-fr1 with all the binary DLLs inatalled.
and don’t hold me to this, but it’s probably due to the way Sorenson and/or QT handle the “hidden” information. Inside your typical Apple trailer site, the link is actually a “referring” .mov that actually calls another .mov. Kinda similar to the way DVD’s work (IIRC). AFAICT, it’s a cheesy way of requiring compliant (read: Apple or Windows) clients. I don’t think mplayer has a way of gracefully handling that particular data in the codec stream. (Mind you, I know very little about codecs… this was all explained to me in a recent LUG meeting.)
The way to get around it isn’t a breeze, but it’s not entirely difficult, either. Read the html source for the trailer page, and look for the href to the relevant .mov. Then use wget to grab that first file. It will likely NOT have the movie, but WILL send the missing filename to stderr (provided you’re running mplayer from the command line). Then just download each subsequent .mov until you get to the real one.
Complex? Yup. Easy? Yup? Waste of time? Yup. I just downloaded 3 .mov’s to get to the real Matrix Reloaded trailer. But it was worth it. 😉
-fp.
Correction: You’ll want to look for the “embed” tag for the relevant link to the .mov (for Apple trailers), not an href.
-fp.
I’m getting the exact problems others talk about, and i’ve tried both of the ways of doing it. I’m not about to start hunting for urls to watch trailers. Could someone put up non-bastardized version of a video so that i could test this out?
Thanks
1) Yes, I’m having the same problems as everyone else.
2) Your prerogrative. I don’t blame you, but it doesn’t bother me to jump through the hoops.
3) I tried writing a testpage using embed, linking to my local file. No good.
4) I even tried loading the .mov by itself with mozilla/galeon. No good either. Oh well.
-fp
The DareDevil and Hulk movies worked for me but other did not. Blasted Apple !! You can take from the OSS community and not give back in terms of useful apps like quicktime for Linux or something that people might actually want to use. Sure I like Mplayer and think that with some work that Mplayer and it’s plugin will eventually work good enough for people to use but damit why can’t Apple just give back something useful !!
I can play _all_ movies (from anywhere, including the trailers @ apple.com).
You just need the Qt6 DLL’s and not those for Qt5.
Which plugin did you use?
And is distributing the qt6 dlls for free illegal? and if not… anyone got the up somewheres?
Here’s a script that will download the real movie from an Apple trailer page. Its a simple translator of mangled urls to the real akamai one using a few known schemes. You can run it with ‘mov.py‘. I’m guessing that that tabs won’t be preserved when I post this, but oh well.
Python people will figure it out…
#!/usr/bin/python
import os,sys,re,string
try:
url = sys.argv[1]
except:
print “Usage: %s URL” % sys.argv[0]
sys.exit (1)
# Get the web page with embedded movie
p = os.popen (“wget -O – %s” % url)
lines = p.readlines ()
p.close ()
mov = None
for line in lines:
m = re.match (‘^.*(?P<mov>http.*_480.mov)’, line)
if m:
mov = m.group (‘mov’)
mov = string.replace (mov, ‘_480’, ‘_m480’)
break
m = re.match (‘^.*(?P<mov>http.*-sref.mov)’, line)
if m:
mov = m.group (‘mov’)
mov = string.replace (mov, ‘-sref’, ‘_m480’)
break
m = re.match (‘^.*(?P<mov>http.*_480r.mov)’, line)
if m:
mov = m.group (‘mov’)
mov = string.replace (mov, ‘480r’, ‘m480’)
break
m = re.match (‘^.*(?P<mov>http.*_320.mov)’, line)
if m:
mov = m.group (‘mov’)
mov = string.replace (mov, ‘320’, ‘m320’)
break
if mov:
os.system (“wget %s” % mov)
else:
print “No movies found.”
sys.exit (1)
>> Which plugin did you use?
mplayer-plugin
>> And is distributing the qt6 dlls for free illegal? and if not… anyone got the up somewheres?
Dunno, but you can download them here:
(watch the Quicktime6 DLL’s part)
well, i’m too lazy to get screen captures… anyway…
if you’ve got an rpm capable distro, use the rpms for mplayer and the codecs. that’s what i did. using redhat 8.0 with mplayer 0.90rc3 rpms + codecs in rpms.
“make”d the source of mplayerplug-in. placed .so file in plugin dir. it does show the same thing “mplayer pluin – Loading movie…”, it takes awhile to finish loading a significant part of the movie before it plays, so maybe it just hasn’t downloaded enough of the movie. since there’s no gui controls (yet) for the plugin, hard to see how much has been downloaded.
about the legality… i’m thinking it should be legal since we’re not using it as a “quicktime pro” version where we can encode videos. we’re just playing, and apple already distributes quicktime for free. besides, wouldn’t apple like to see more people viewing quicktime movies instead of wmv or real or something?
Installed mplayer from , without doing jack, mplayer embeds itself in mozilla/galeon. Don’t know if its the mplayer RPM or RH’s plugger, but plugger is atleast configured to use mplayer. Very Nice(TM)
./configure –enable-gui … why not enable the gui by default and have a “–disable-gui”?
I’m begind a proxy… “Connect error” – I searched the howto for “proxy” and found …
“MPlayer also honors the http_proxy environment variable, and uses proxy if available. Proxy usage can also be forced”
->google, in a mailinglist I found there has to be a preceeding “http://“…
export http_püroxy=”“.
Why can’t this be set in the preference-dialogs anyway?
Where do I have to copy these damn codec files?
I have been using Linux for five years day by day at home and at work.
I (still) like it a lot – but things like this are really annoying and deterrent.
I don’t have Mozilla install, so does it works with phoenix? I keep get error in the Phoenix with this plugin. Maybe, it’s because of FreeBSD or else. I compiled both of them and still no go.
Thanks for the heads up on the QT files. I had the earlier ones that they posted when they first got qt to work in mplayer. I guess they must of update those libs or something. I followed your advise and downloaded the new qt6 libs and everything now works as some as silk.
P.S. I used this plugin as the other one barfed on me. This one works a lot better IMHO.
and you can find all the codecs you’ll ever need here
and of course you get mplayer from here
If you use Debian(I use Sid/Unstable) and instaled mplayer through apt-get, you can get the codecs for qt6 by doing “apt-get install qt6codecs”
This is unfortunately another effort that just falls short of really working for everyone. Ive tried this one, the mplayer one, and also plugger 4.0. None of them work worth a damn for me. After reading most of these posts its clear then the majority is also experiencing the same issues I am. Ive looked and looked and cant really find any documentation or support on these plugins……which is unfortunate because its probably not too difficult a problem.
Until we have a really good effort to bring a real working mplayer plugin to the masses with support for more than one distro, I’ll have to stick with my Crossover Plugin. FYI for anyone interested, this really does work. It costs 20 to 30 bucks, but so what when everything else we do is free. With Crossover Plugin from Codeweavers, I can now have the actual Quicktime6, and wmp 6.4 plugin support under any version of mozilla and any distro of linux……it just works.
Kmplayer really works awesome for me. Most embedded movies (be it windowsmedia, or quicktime), ‘just work’.. I love it
|
https://www.osnews.com/story/2707/installing-mplayer-for-mozilla/
|
CC-MAIN-2019-13
|
refinedweb
| 1,679
| 76.42
|
Buster Silver (#cc5380c3) at 20 Jul 08:28
#186 -- Revert Proxy changes to fix regression bug on Docker.
Buster Silver (#275c74c0) at 19 Jul 20:17
Change autogenerated Proxy namespace to avoid conflicts.
Buster Silver (#70fa5d8a) at 19 Jul 07:55
Fix CI builds and code updates; will work on Proxy includes later
Buster Silver (#6b7b1bba) at 19 Jul 06:52
#186 -- Add "sent to autodj" flag to media to avoid double-cues.
Buster Silver (#6757d21e) at 19 Jul 00:33
Update Composer dependencies.
Buster "Silver Eagle" Neece (#69aa8593) at 19 Jul 00:09
Redis cache overhaul and optimization, settings restructure.
Buster "Silver Eagle" Neece (#3772e54d) at 17 Jul 23:19
Revert reordering of error handling due to unit test issue.
Buster "Silver Eagle" Neece (#42abf491) at 17 Jul 22:21
Clean up error handling, add API middleware to help fix session propagation.
Buster "Silver Eagle" Neece (#a9415fb9) at 16 Jul 18:41
Fix session generation issue on internal API calls, and migrate the environment flag to be a defined boolean instead of string comparison for less error-prone-ness.
Buster "Silver Eagle" Neece (#a46ad3c4) at 15 Jul 07:11
Locale generate.
Buster "Silver Eagle" Neece (#b96530af) at 15 Jul 07:10
Closes #189 -- Prevent redirect loop if user currently administers no stations.
Buster "Silver Eagle" Neece (#b27f3ec2) at 15 Jul 05:44
Clarify readme, open up Redis port on dev boxes and update Stash config.
Buster "Silver Eagle" Neece (#c954bd2b) at 13 Jul 22:54
Fix config migrator for instances old enough to have used the "root" user.
Buster "Silver Eagle" Neece (#f2e01043) at 13 Jul 21:44
Service and Configuration overhaul:
- Move all app-specific configuration to one ansible-editable INI file
- Migrate installations using previous config to new style using CLI command
- Install Redis for all AzuraCast installations (matching Docker)
- Move caching and session management into Redis (avoiding inode issues)
Buster "Silver Eagle" Neece (#08932908) at 11 Jul 21:01
#182 -- Don't remove components from IceCast KH either.
Buster "Silver Eagle" Neece (#242a0aef) at 11 Jul 03:59
Fix connected time display on live listener report.
Buster "Silver Eagle" Neece (#4628ea31) at 11 Jul 03:58
Add special check to prevent the same song from playing back-to-back.
Buster "Silver Eagle" Neece (#645b3399) at 11 Jul 03:33
Revert removal of supporting libraries as some LS plugins still use them in runtime.
Buster "Silver Eagle" Neece (#30418cec) at 08 Jul 20:34
Remove squash until Docker Compose adds support for it: docker/compose#4235
Buster "Silver Eagle" Neece (#c8822a21) at 08 Jul 15:38
Update the Docker package name on the other install method.
Buster "Silver Eagle" Neece (#3ac7cdc3) at 08 Jul 15:36
Switch Docker upgrade methods.
Buster "Silver Eagle" Neece (#183a9dfb) at 08 Jul 15:25
Remove unnecessary packages after compilation, squash the resulting images during Travis build for significantly smaller sizes.
Buster Silver (#fb4792cc) at 30 Jun 22:34
Fix dependencies causing "stack overflow" on OPAM install.
Buster Silver (#4df7cf71) at 30 Jun 19:32
#174 -- Fix API return type for "stream offline" return.
Buster Silver (#ad05cf5c) at 30 Jun 14:44
#174 -- Update listener map script to reflect API changes.
Buster Silver (#c09c6581) at 30 Jun 14:11
Fixes #176 -- Install composer before doing main Docker install tasks.
Buster Silver (#83b8d287) at 30 Jun 04:34
More work to fix uptime timing issues with Docker containers.
Buster Silver (#a7ccbf3a) at 30 Jun 03:35
More fixes to make unit tests match new API style.
Buster Silver (#b4832292) at 30 Jun 02:26
Minor update to match type-specificity in API.
Buster Silver (#12417d7c) at 30 Jun 02:16
Minor tweaks to unit testing.
Buster Silver (#c09499ff) at 30 Jun 01:24
Readme language update and expansion.
Buster Silver (#b9b6899a) at 30 Jun 01:18
Updated locale import.
Buster Silver (#67167b20) at 27 Jun 05:42
Travis fixes to ensure the proper Docker version is running.
Buster Silver (#78f1e9e8) at 27 Jun 05:23
Update permissions on coverage output temp dir.
Buster Silver (#c9544052) at 27 Jun 04:14
Update package name on Docker.
Buster Silver (#a70b7733) at 27 Jun 03:45
Use new method for mysql uptime check.
Buster Silver (#d245d6dc) at 27 Jun 03:29
Include the Docker/Docker Compose installer in the docker install script.
Buster Silver (#122b254b) at 25 Jun 20:08
Actually provide the git clone instruction in the Docker section. [skip ci]
Buster Silver (#853f55d0) at 25 Jun 17:01
Update readme to emphasize Docker's broad compatibility. [skip ci]
Buster Silver (#1b46ce7e) at 25 Jun 17:00
Cleaning up the PHP installation step of trad install. [skip ci]
Buster Silver (#19553016) at 23 Jun 04:54
Implement asset cache busting and password strength checking with zxcvbn.
|
https://gitlab.com/SlvrEagle23.atom
|
CC-MAIN-2017-30
|
refinedweb
| 791
| 60.24
|
Computer Science Archive: Questions from October 13, 2008
- Anonymous askedThis is actually question 5.3 from the 6th edition ofStallings but they seem to be pretty close to t... Show moreThis is actually question 5.3 from the 6th edition ofStallings but they seem to be pretty close to the same so I washoping it was maybe 5.2 in the 5th edition. This is thequestion, and at the bottom is what I think it produces:
Consider a concurrent program with two processes, pand q, defined as follows. A, B, C, D, and E are arbitraryatomic (indivisible) statements. Assume that the main program(not shown) does a parbegin of the twoprocesses.
void p() void q( )
{ {
A; D;
B; E;
C; }
}Show all the possible interleavings of the executionof the preceding two processes (show this by -giving execution“traces” in terms of the atomicstatements).-----------------------------------------------------------------------------------------------------------------------------A; B; C; D; E; or D; E; A; B; C;• Show lessI'm confused if this really could produce any combination ofthe statements like A;D;B;E;C/D;A;E;B;C; or if it has to go all theway through one process then do the next. Any help would beappreciated.2 answers
- Anonymous askedusing inheritance create a base class called fraction and aninherited class called mix fractions tha... Show moreusing inheritance create a base class called fraction and aninherited class called mix fractions that will be used in your mainprogram.
* create a menu that asks the user for the type of operation(+,*)that is to be performed, followed by the whole number, numeratorand denominator..
* after the user enters the values and the operation the answer isto be expressed in the following format wholenumber/denominator.
* the user should also be given the option to convert frommixed fraction to improper fraction. eg 7 1/4 to 29/ 4.
• Show less1 answer
- Anonymous askedFor the do-while loop program segment below write equivalentprograms that use the while loop and the... Show moreFor the do-while loop program segment below write equivalentprograms that use the while loop and the for loop. All programsmust generate the same output.
x = 9;
do
cout << x--;
while(x>2);
• Show less1 answer
- Anonymous askedI am trying to write a program that prompts theuser to enter a center point of a circle, and... Show more/*• Show less
I am trying to write a program that prompts theuser to enter a center point of a circle, and a point on thecircle, and then outputs the radius, diameter, circumference, andarea of the circle. I am having trouble with my program below, socan anyone help me?
*/
#include <iostream>
#include <cmath>
using namespace std;
int centerX;
int centerY;
int outsideX;
int outsideY;
int centerPoints();
int outsidePoints();
double pi = 3.1416;
double radius =(outsideX - centerX) * (outsideX - centerX) +(outsideY - centerY) * (outsideY - centerY);
double radius2 = pow(radius, 1 / 2);
double diameter = radius2 * 2;
double circumference = 2 * pi * radius2;
double area = pi * radius2 * radius2;
int main()
{
cout << "Center Point: " <<centerPoints() << endl;
cout << "Radius: " << radius2<< endl;
cout << "Diameter: " << diameter<< endl;
cout << "Circumference: " <<circumference << endl;
cout << "Area: " << area <<endl;
system("pause");
return 0;
}
int centerPoints()
{
int centerX = 0;
int centerY = 0;
bool invalid = false;
do
{
cout <<"Enter center (x,y) coordinate: ";
cin >>centerX >> centerY;
if ( ! cin < 0|| ! cin > 0 || ! cin == 0 )
{
cin.clear();
cin.ignore(100, '\n');
}
invalid = (! cin< 0 || ! cin > 0 || ! cin == 0);
if ( invalid)
{
cout << "Coordinates must be integers" << endl;
}
} while ( invalid );
return (centerX, centerY);
}
int outsidePoints()
{
int outsideX = 0;
int outsideY = 0;
bool invalid = false;
do
{
cout <<"Enter outside (x,y) coordinate: ";
cin >>outsideX >> outsideY;
if ( ! cin < 0|| ! cin > 0 || ! cin == 0 )
{
cin.clear();
cin.ignore(100, '\n');
}
invalid = ( ! cin< 0 || ! cin > 0 || ! cin == 0 );
if ( invalid )
{
cout << "Coordinates must be integers" << endl;
}
} while ( invalid );
return (outsideX, outsideY);
}1 answer
- Anonymous askedexpress is standard canon... Show moreI really need help with this problem as soon as possible thanks inadvance.
express is standard canonical SOP form:
F(w,x,y,z) = w'xy' + x'z' + (w'+z')(y'+x)
b. Express is standard canonical POS form:
F(w,x,y,z) = (w'+x)(x+y) + w'z'(x'+y) + w'x+ yz
• Show less0 answers
- Anonymous askedthe first... Show moreWrite a program that simulates the rolling of two dice.The program should use rand to roll the first die andshould use rand again to roll the second die. Thesum of the two values should then be calculated.[note: since eachdie can show an integer value from 1 to 6, then the sum of the twovalues vary from 2 to 12, with 7 being the most frequent sum and 2and 12 the least frequent sums.] show the 36 possible combinationsof the two dice. your program should roll the two dice 36,000times. Use a single-subscripted array to tall the numbers of timeseach possible sum appears. PRint the results in tabular from. onesixth of all rolls should be 7.should look like this1 2 3 4 5 61 2 3 4 5 6 72 3 4 5 6 7 83 4 5 6 7 8 94 5 6 7 8 9 105 6 7 8 9 10 116 7 8 9 10 11 12• Show less1 answer
- Anonymous asked ... More »0 answers
- Anonymous askedFor the correct operation of one of luminous beacon ofcirculation of three lamps (A: green, B: orang... Show more
For the correct operation of one of luminous beacon ofcirculation of three lamps (A: green, B: orange, C: red), it isallowed to be turned on only one from the three lamps, whilethe remainder combinations lead to erroneous operation of beaconand a signal of alarm must be produced to the company that hasundertaken his maintainance. Design the table of truth ofreasonable interelation that produces the signal of alarm. Using Karnaugh map you have to minimise this interelation in formof sum of products and afterwardsmaterialise the minimised interelation using three level gates : an initial level of inversions for the export ofsupplementery forms of variables that is required, a second gatelevel AND and a third level OR.• Show less1 answer
- Anonymous askedIn a country the government is constituted by threecommittees (A, B, C). Committee A includes 35 mem... Show moreIn a country the government is constituted by threecommittees (A, B, C). Committee A includes 35 members, committee Bincludes 20 members and committee C includes 45 members. Allmembers of same committee agree always if they approve or no aproposal. In order to approve a proposal from the governmentis required the consent of at least the 55% of total number ofmembers of government.
Using the above logic, design the table of truth oflogical function F, which receives logical value 1 only when isapproved a proposal from the government of country. With Karnaughmap minimise this interelation in form of sum of sum ofproducts and afterwards you materialise the minimised interelationwith two levels gates AND-NOR , after initially you use inversions in order to produce the additional forms ofvariables of entry that are required.• Show less1 answer
- Anonymous asked?... Show morepart2:• Show less0 answers
- Anonymous askedIf anyone can help with any of the... Show moreI know if the this is the right forum to placethese questions in.
If anyone can help with any of the following questions, if it isonly one question, greatly appreciated. Thank you.
Project 1. Create a database of clients who rent buildingequipment from you consisting of either tractors, bull dozers andcranes. A crane rents for $2000 , a tractor rents for $4,500 and abulldozer rents for $1,700. Each client can rent more than oneitem. (The key to the table should the client name)
Create a form that allows you to enter clients and to then producea total of you revenue.
Project 2. Create a project that demonstrates a method thatdisplays the equation of a line passing through two points. Letthis method depend on a method called slope.
Hint return “y =”+slope.ToString()+”x+(”+b.ToString+”)”;
Project 3.
The following formula computes mortgage payments for a loan.
R is the monthly payment.
i is the interest rate.
n is number of payments.
L is the amount borrowed.
A=R * ((1-(1+i)-n)/i)
As a mortgage company keep track of the client loans and theirmonthly payments using a method that you will create to compute thevalue of R.
Project 4. Create a program that draws an automobile use graphicscommands.
Have methods called on like drawWheel,drawFender etc.
Project 5. Create a program the uses methods that demonstrate thelaws of cosines.
Project 6. Make a game of your own construction that uses theRandom class. Try to use graphics.
Project 7. Can you create a database program that store images ofgold coins? • Show less0 answers
- eman55 asked1 answer
- Anonymous askedwhat is mod... Show more
This is little stupid to ask
what is quality management,
what types of quality management• Show less
what is modern quality management?1 answer
- StrickerXY askedI am really close to solving this...I am trying to calculatethe monthlyPayment. I cant get the Math.... Show moreI am really close to solving this...I am trying to calculatethe monthlyPayment. I cant get the Math.pow(); to workcorrectly..my code =
public class interest
{
public static void main(String[]args)
{
final int YEAR = 12;
double interestRate =.06;
double loanAmount;
double monthlyPayment;
double totalPayment;
double n;
int numberOfYears;
double numerator;
double denomenator;
double discriminant;
Scanner scan =newScanner (System.in);
System.out.println("What is theloan amount: ");
loanAmount =scan.nextDouble();
System.out.println("What is theterm of the loan: ");
numberOfYears =scan.nextInt();
n = numberOfYears*YEAR;
numerator = ((interestRate /YEAR)*loanAmount); //this is the numerator and workswell
denomenator = 1-(1 + interestRate /YEAR); //denomenator works except needs to be to the power of(-n)
discriminant =Math.pow(denomenator, -n); //I know it is not reallya discriminant. returns some crazy number
monthlyPayment = (numerator /denomenator);
System.out.println(denomenator);
System.out.println(numerator);
System.out.println(discriminant);
System.out.println(monthlyPayment);
}
}5 answers
- Anonymous askedCrea... Show moreI need some help converting the following C++ program to C.Here is what it is supposed to do:
- Create a structure that has one variable called value and one pointer to the list (makingit a linked list). Prompt for 5 values from the keyboard as inputand store them in the linked list. Print out the current contentsof the list. Allow the user to add one more value to the linked list, and print the contents ofthe list again.
#include<iostream>
using namespace std;
struct ListNode{
int value;
ListNode *link;
};
int main(){
ListNode *head;
ListNode *temp;
ListNode *myIterator;
myIterator = head;
temp = head;
cout<< "Enter value 1: ";
cin >> head->value; //store value infirst node under variable 'value'
for(inti=0; i<4; i++){
temp->link = newListNode;
temp =temp->link;
cout << "Entervalue " << i+2 << ": ";
cin >>temp->value;
}//end for
temp->link = NULL; //bandaid
cout<< "Here is the list of values." << endl;
while(myIterator->link != NULL){
cout << endl<< myIterator->value;
myIterator =myIterator->link;
}//end while
cout << endl <<myIterator->value;
myIterator = head;
temp->link = new ListNode;
temp = temp->link;
cout << endl << "Value to add tolist: ";
cin >> temp->value;
cout << endl;
temp->link = NULL; //bandaid
cout<< "Here is the list of values again." << endl;
while(myIterator->link != NULL){
cout << endl<< myIterator->value;
myIterator =myIterator->link;
}//end while
cout << endl <<myIterator->value;
return 0;
}//end main1 answer
- Anonymous askedOk Im gonna lay about 8 questions down. If somone could justwork one. and show me how to do it. that... Show moreOk Im gonna lay about 8 questions down. If somone could justwork one. and show me how to do it. that would be great. and ifthere are any special cases on the rest of them let me know(My Real Problem comes because I dont know if when youmultiply a 3 and a 3.0.. what happens. to the decimal.. Placein these problems.. keep it throw it.. im confused)The original problem was just tell whether each is valid butknow she wants us to Solve and tell if the interger has changed..im confused(So acouple wont be able to be worked because there not validI have been told 31 and 34 are not Valid by a friend. If this isnot right please correct him.)The Following Declarations have been made.int intEight= 8, intFive1 = 5, intFive2 = 5, jobld;double two = 2.0, three = 3.0, four = 4.0,xValue;char code = 'A',letter;28.xValue = three+two/four;29.xValue=intEight/intFive1+5.1;30. jobld = intEight/intFive1 +5.1;31.xValue = three * three + four * four;32 jobld = intFive1++;33 jobld = ++intFive2;34 intEight * = 8;• Show less1 answer
- Anonymous asked1 answer
- Anonymous askedI am looking at designing a synchronous 4-bit counter using a 2:1Mux. Can anybody please guide me... Show moreHi,
I am looking at designing a synchronous 4-bit counter using a 2:1Mux. Can anybody please guide me.
Thanks
• Show less3 answers
- Anonymous askedIn a factory there are four buckets that contain heatedliquids. Two sensors of level of liquid (A an... Show moreIn a factory there are four buckets that contain heatedliquids. Two sensors of level of liquid (A and B) are used in thetwo from the four buckets in order to show if the level ofliquid has gone up above a predetermined limit of safety. Twosensors of temperature (C and D) are used in the remainder twobuckets in order to show if the temperature of liquid has fallenunder a predetermined limit. The clue of sensors of level receivesreasonable price 0 when the level is satisfactory and reasonableprice 1 when the level is higher than the predetermined limit. Theclue of sensors of temperature receives reasonable price 0 when thetemperature is satisfactory and reasonable price 1 when thetemperature falls under the predetermined limit.A buzzer (k) shouldbe activated when the level in at least one of the buckets withsensor of level has exceeded the predetermined limit, whilesimultaneously the temperature in at least one of the buckets withsensor of temperature is lower than the predetermined limit.
Using the above logic, design the table of truth oflogical function that activates the buzzer. With Karnaugh mapsimplify this interelation in form of Sum of Products andafterwards materialise using only three (3) gates NOR. It is notallowed the use of inversions or other logical gates and as inputsof logical circuit is only given the variables that correspond inthe clues of sensors and not their additional forms.• Show less0 answers
- Anonymous asked1 answer
- Anonymous askedgive the tree representation of the followiing array. mark thevalues that violate the max heap condi... Show moregive the tree representation of the followiing array. mark thevalues that violate the max heap condition.
A= <6,2,1,4,8,14,9,4,5,3,15>
• Show less1 answer
- Anonymous asked1 answer
- Anonymous askedthat uses a40-element array of digits to store integer... Show more
(HugeIntegerClass) Create a class HugeInteger that uses a40-element array of digits to store integers as large as 40 digitseach. Provide member functions input, output,add and substract. For comparingHugeInteger objects, provide functions isEqualTo,isNotEqualTo, isGreaterThan, isLessThan,isGreaterThanOrEqualTo andisLessThanOrEqualToeach of these is a "predicate" functionthat simply returns TRue if the relationship holds betweenthe two HugeIntegers and returns false if therelationship does not hold. Also, provide a predicate functionisZero. If you feel ambitious, provide member functionsmultiply, divide and modulus.• Show less1 answer
- Anonymous asked1 answer
- Anonymous asked1 answer
- Anonymous askedI need a pseudo code for an algorithm for preforming all the operations in an array list ADT im... More »1 answer
- Anonymous askedthreads that can run con... Show more
* A technique in which a process, executing anapplication, is divided into
threads that can run concurrently iscalled:
a. Multithreading
b. Multiprocessing
c. Symmetric multiprocessing (SMP)
d. None of the above
* One of the disadvantages of User-Level Threads(ULTs) compared to
Kernel-Level Threads (KLTs) is:
a. Scheduling is application specific
b. When a ULT executes a system call, all threads in the processare
blocked
c. Thread switching does not require kernel mode privileges
d. All of the above
* A benefit of the microkernel organizationis:
a. Extensibility
b. Portability
c. Flexibility
d. All of the above
* In a uniprocessor system, mutual exclusion canbe guaranteed by:
a. Overlapping processes
b. Interleaving processes
c. Disabling interrupts
d. All of the above
* A chief characteristic of a monitoris:
a. A maximum of two processes may be executing in a monitor at atime
b. Local data variables of the monitor are accessible by anyprocedure
requesting use of the monitor
c. A process enters the monitor by invoking one of itsprocedures
d. All of the above
• Show less1 answer
- Anonymous askedYourimplementa... Show moreFor thisassignment you’ll be using recursion to solve a numericalintegration problem.
Yourimplementation must berecursive.Considerthe problem of finding the area under the curve for some functionF(x). The function is presumed to be defined everywhere over theinterval of integration and can be evaluated anywhere within thatinterval. For this assignment we will make the further assumptionthat F(x) is continuous. One such function is sketched here. Wewish to integrate this function (find the area under the curve)from x =a tox =b. Presumably, we do nothave a closed-form antiderivative; there are many importantfunctions in science and engineering for which no antiderivative isknown, or can be shown to have no antiderivativefunction.• Show less
We wish to find the area under the curvefrom x =a tox =b. One method isthe trapezoidalrule;take
the trapezoid formed by the x axis, thelines x =a andx =b, and a line segmentconnecting F(a) and
F(b). This trapezoid is shown above as theheavy blue line, and has the area
A = (b – a) (F(a) + F(b)) / 2
Note that while this is an estimate of the area under the curve,it’s not necessarily a good estimate. One
way to see how good an estimate it is would beto break the interval into two halves and find the areaof
each half separately. If our estimate is good,then the sum of the two smaller trapezoids (reddashed
lines above) should be close to the area of ourfirst estimate.
M = (a + b) / 2
A1 = (M – a) (F(m) + F(a)) / 2
A2 = (b – M) (F(m) + F(b)) / 2
A1 + A2 = A'
if( A – A') is “close enough” to 0, we’redone.
But what if the estimates aren’tsufficiently close, as in the example above? In this case, we needa more accurate estimate of the area under each half of the curve:the interval from a to m, and the interval from m to b.But...We already have a function to findthe area under the curve over an interval. So wecan(recursively) call that function on each half separately,to get the area under each half, then return the sum of thoseareas.So now we simply must decide how close is close“enough.” There is no general algorithm for answeringthis question, as it depends on the function, the interval ofintegration, and the situation. For some applications, an estimateof the area within ± 1.0 is enough; other situations maydemand much higher precision. Rather than trying to guess,we’ll allow the user to specify a tolerance, an estimate of how much precision is needed.If our “big trapezoid – 2 small trapezoids”estimate is less (smaller absolute value) than the tolerance, thenwe’re “close enough.” Of course, the user wantsthat tolerance to apply across the entire interval; that is, if theestimate should be within, say, 0.01 across the entire range, thenwe can’t afford to have that much error in just the lefthalf, or leftmost quarter. So, when breaking our interval down intosubintervals, we’ll ‘allocate’ half the toleranceto each side; in other words, if our total tolerance is 0.01, thenour tolerance on the left is 0.005, and the tolerance on the rightis the same. If both halves are within their respective tolerances,then the total error should not exceed 0.005 + 0.005 = 0.01. Writea program that carries out numerical integration of a functionF(x). Include a separate function F(x) in your code; do nothard-code the function into the integration function. Your programshould then include a recursive function that takes left and right endpoints ofthe interval of integration, a tolerance, and function evaluationsat both the endpoints (to save having to carry out functionevaluations at points that have already been evaluated). Thefunction should carry out the integration using the algorithmdiscussed above. For this assignment, use something simple forF(x), something you can integrate analytically to ensure yourfunction is getting a correct answer within the specifiedtolerance.0 answers
- Anonymous asked1) Fill in the blank for each question * The _____________ is the portionof the operating system tha1 answer
- Anonymous askedWrite a program that lets users enter the total rainfall for eachof the 12 months i... Show moreRainfall Statics
Write a program that lets users enter the total rainfall for eachof the 12 months into an
array of doubles. The program should calculate and display thetotal rainfall for the
year, the average monthly rainfall, and the months with the highestand lowest amounts.
Input Validation; Do not accept negative numbers for monthlyrainfall figures.
You can edit my program or you can make it from scrach. thxneed by october 14th 8am.
you'll be a life saver. I tried and cant seem to getit.
so far, this is how my program looks:
#include <iostream>
using namespace std;
int main()
{
double year [12];
int count = 1;
int numbers [count];
double sum;
int highest;
cout <<"Enter the total monthly rainfallof each month:\n";
cout <<"Be sure not to enter negativenumbers.\n\n";
cout <<"January: \n";
cin >> year[0];
while (year[0] < 0)
{
cout <<"January: \n";
cin >> year[0];
}
cout <<"February: \n";
cin >> year[1];
while (year[1] <0)
{
cin >> year[1];
}
cout <<"March: \n";
cin >> year[2];
while (year[2] < 0)
{
cin >> year[2];
}
cout <<"April: \n";
cin >> year[3];
while (year[3] < 0)
{
cin >> year[3];
}
cout <<"May: \n";
cin >> year[4];
while (year[4] < 0)
{
cin >> year[4];
}
cout <<"June: \n";
cin >> year[5];
while (year[5] < 0)
{
cin >> year[5];
}
cout <<"July: \n";
cin >> year[6];
while (year[6] < 0)
{
cin >> year[6];
}
cout <<"August: \n";
cin >> year[7];
while (year[7] < 0)
{
cin >> year[7];
}
cout <<"September: \n";
cin >> year[8];
while (year[8] < 0)
{
cin >> year[8];
}
cout <<"October: \n";
cin >> year[9];
while (year[9] < 0)
{
cin >> year[9];
}
cout <<"November: \n";
cin >> year[10];
while (year[10] < 0)
{
cin >> year[10];
}
cout <<"December: \n";
cin >> year[11];
while (year[11] < 0)
{
cin >> year[11];
}
sum = (year[0] + year[1] + year[2] + year[3] + year[4] + year[5] +year[6] + year[6] + year[7] + year[8] + year[9] + year[10] +year[11]);
double average;
average = sum / 12;
cout <<"The total rainfall for the year is " << sum<< ".\n";
cout <<"The average monthly rainfall is " << average<< " .\n";
highest = year[12];
for (count = 1; count < 12; count++)
{
if (numbers[count] > highest)
{
highest = numbers[count];
}
}
cout <<"The highest monthy rainfall is " <<highest<<" .";
system("pause");
return 0;
}
• Show less3 answers
- WittyDinner2594 askedcreate an original well commented C program consisting of two ormore functions that you write, which... Show morecreate an original well commented C program consisting of two ormore functions that you write, which will graph a 1001 points of an-th order polynomial whose order, coefficients, and domain aredetermined by the user.
Deatils:
0 answers
- Your comments at the begining of your program should includeyou name and OUID as well as other useful comments. Also cite anyresources you used (people, websites, etc)
- Your program should query the user for the order of thefunction (you can place an upper limit of 10th order.
- Your program should query the user for the coefficients for thefunction (remember there are n+1 coefficients for a nth orderpolynomial). Hint, store the coefficients in a the first n+1elements of an array of size 11. The query fore the coefficientsshould look like: printf("What is the coefficient for theterm x^%d",i); where i has the value 0 to n, depending onwhich coefficient is being collected.
- Your program should ask the user for the minimum value of X tobe graphed.
- Your program should ask the user for the maximum value of X tobe graphed.
- Your program should then fill an array of X values where thefirst point is the minimum values and each subsequent point is1/1000 th of the way closer to the maximum value (this means the1001 point should be the maximum X value).
- Your program should then calculate corresponding Y values foreach X value where Y=CnX^n+C(n-1)X^(n-1)+...+C1X+C0X (Hint: createa separate function that takes an X value, an array of coefficientsand the order of the function and returns the Y value. Then callthat function in a loop as you go through each X value.)
- Your program should then do a printf which prints out a message"Here is a graph of the function the polynomial function _______"where is ______ is filled in with the function (e.g.,Y=3x^2+2x-15.5)
- Your program should then graph the data by callingg_graphData(x,y,1001); Hint: be sure to download the file grapher.cfrom the conrtent section of D2L. You will also need to place thatfile in the same directory as your program and have the line%include "grapher.c" at the begining of yourfile.
- Anna0404 askedOk...so I am not a computer sciencemajor. I am a physics major but as a requirement you need to take... Show moreOk...so I am not a computer sciencemajor. I am a physics major but as a requirement you need to take 1computer science class so I will appreciate it very much ifi can get any help .
Write a well modularized pseudocode algorithm that converts aninput string to "hacker speak", and vice-versa. Hacker speak iswhere simple subtitutions are made to individual letters asfollows: • Show less1 answer
- Anonymous askeda... Show moreThe following piece of code is executed using the pipelineshown in Figure 6.30:lw $5, 40($2)add $6, $3, $2or $7, $2, $1and $8, $4, $3sub $9, $2, $1At cycle 5, right before the instructions are executed, theprocessor state is as follows:a)The PC has the value 100ten, the address of thesub_instruction.b)Every register has the initial value 10ten plusthe register number(e.g., register $8 has the initial value18ten).c)Every memory word accessed as data has the initial value1000ten plus the byte address of the word (e.g.,Memory[8] has the initial value 1008ten).Determine the value of every field in the four pipelineregisters in cycle 5.• Show less2 answers
- Anonymous askedWrite a program t o output the amount of money that would be present in a bank account some year in ... More »0 answers
- Anonymous askedWrite a program to allow the user to input 6 integers. Use a loop to accomplish the input.&nbs... More »1 answer
- Anonymous askedWritea Java application program that will help an elementary school st... Show morex.Writea Java application program that will help an elementary school studentlearn multiplication. Use a Random object to produce two positive onedigit integers. The program should then prompt the user with aquestion, such as
How much is 6 times 7?
Thestudent then inputs the answer. Next, the program checks the student’sanswer. If it is correct, display one of the following the messages andask another multiplication question.
Responses to a correct answer:
- Very good! 2. Excellent! 3. Nice work! 4. Keep up the good work!
If the answer is wrong, display one of the following message the messages and let the student try the same question repeatedly until the student finally gets it right.
Responses to an incorrect answer:
- No. Please try again. 2. Wrong. Try once more. 3. Don't give up! 4. No. Keep trying.
You could use random-number generation to choose a number from 1 to 4 that will be used to select an appropriate response to each answer and use a switch statement to issue the responses.
My code:
import java.util.Random;• Show less
import java.util.Scanner;
public class LeeTA3CISP40108F
{
// create Random number generator for use in method Equation
private Random randomNumbers = new Random();
// enumeration with constants that represent the program status
private enum Status {RIGHT, WRONG, QUIT}
// constants that represent next actions
private final static int RIGHT = 1;
private final static int WRONG = 0;
private final static int QUIT = -1;
// formulates one equation
public void multiply ()
{
Status programStatus; // can contain RIGHT, WRONG, or QUIT
//int CONTINUE = 1;
int status = formEquation( ); // first equation that formulates
//determine program status
switch ( status )
{
case RIGHT: // when the user enters the correct answer
programStatus = Status.RIGHT;
break;
case WRONG: // when the user enters in the wrong answer
programStatus = Status.WRONG;
break;
default: // when the user wants to quit the program
programStatus = Status.QUIT;
break;
}
// when the wants to exit the game
if ( programStatus == Status.QUIT )
{
System.out.println( "Goodbye!" );
//system ("pause");
}
// when the user enters in a correct answer
if ( programStatus == Status.RIGHT )
{
// chooses a random number 1-4 that corresponds to a positive commment
int right = 1 + randomNumbers.nextInt ( 4 );
&nõ&bx.øi5 // switch statement to randomly choose a positive comment
switch ( right )
{
case 1:
System.out.println( "Very Good!" );
break;
case 2:
System.out.println( "Excellent!" );
break;
case 3:
System.out.println( "Nice Work!" );
break;
case 4:
System.out.println( "Keep up the Good Work!" );
break;
}
// continues the program, asks the user another equation
formEquation();
}
// when the user enters in a wrong answer
if ( programStatus == Status.WRONG )
{
// int CONTINUE = 0;
// choose a random number 1-4 that corresponds to a negative comment
int wrong = 1+ randomNumbers.nextInt ( 4 );
// switch statement to randomly choose a negative comment
switch ( wrong )
{
case 1:
System.out.println( "No. Please try again." );
break;
case 2:
System.out.println( "Wrong. Try once more." );
break;
case 3:
System.out.println( "Don't give up!" );
break;
case 4:
System.out.println( "No. Keep trying." );
break;
}
// continues the program, asks the user another equation
formEquation();
}
} // end method multiply
// forms the equation
public int formEquation( )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
// int continue = 1;
// if ( continue == 1 )
// {
int answer;
// pick random equation values
int first = 1 + randomNumbers.nextInt ( 10 );
int second = 1 + randomNumbers.nextInt ( 10 );
// the product of random numbers
int product = first*second;
// displays the equation
System.out.printf ( "How much is %d times %d?", first, second);
// }
System.out.printf ( "Enter you answer (-1 to exit)");
// reads the user's answer
answú nx.øi5nt();
&n1 answer
- Anonymous asked1 answer
- Tameem2 askedmy teacher is really tough. He makes us read the chapter and do aprogram before he goes over it and... Show moremy teacher is really tough. He makes us read the chapter and do aprogram before he goes over it and explains it to the class. i knowa little about arrays but i have no clue about parellel arrays.Please help. Will rate you as a life saver!!!
i will post up updates on my my progress so far when i have accessto my computer again. ofinteger that holds the number of jars sold during the month foreach sale type.
The salsa name should be stored using an initialization list at thetime the name array is created. the program should promt the userto enter the number of jars sold for each type. once this salesdata has been entered the program should produce a report thatdisplaysof
integer that holds the number of jars sold during the month foreach sale type.
The salsa name should be stored using an initialization list at thetime the name array is created. the program should promt the
user to enter the number of jars sold for each type. once thissales data has been entered the program should produce a reportthat
displays);
*/
So far, this is my program. i still need to call the 3functions:
#include <iostream>
using namespace std;
int getTotal(int numJarsSold[5])
{
int total = (numJarsSold[0] + numJarsSold[1] +numJarsSold[2] + numJarsSold[3] + numJarsSold[4]);
cout <<total <<"\n\n";
return 0;
}
int main()
{
char salsaNames[6] = {'Mild', 'Medium', 'Sweet','Hot','Zesty', '\0'};
int numJarsSold[5];
cout <<"Salsa \n\n\n";
cout << "How many jars of ""Mild Salsa""was sold? ";
cin >> numJarsSold[0];
cout <<"\n\n";
cout << "How many jars of ""Medium Salsa""was sold? ";
cin >> numJarsSold[1];
cout <<"\n\n";
cout << "How many jarsof ""Sweet Salsa"" was sold? ";
cin >> numJarsSold[2];
cout <<"\n\n";
cout << "How many jarsof ""Hot Salsa"" was sold? ";
cin >> numJarsSold[3];
cout <<"\n\n";
cout << "How many jarsof ""Zesty Salsa"" was sold? ";
cin >> numJarsSold[4];
cout <<"\n\n";
getTotal();
system("pause");
return 0;
}
• Show less2 answers
- Todd88 asked"All movies produced by John Sayles are wonderful. John Saylesproduced a movie about coal miners. Th... Show more"All movies produced by John Sayles are wonderful. John Saylesproduced a movie about coal miners. Therefore, there is a wonderfulmovie about coal miners."
I need a rule of inference in each step.
• Show less1 answer
- Todd88 asked1 answer
- TempleOwl32 askedHow is the solution BxA+100 wh... Show more1 answer
- Anonymous askedi ju... Show morei have to write a essay in software project management abouthistory of modern qualitymanagement
i just need to know that which type of topic can i include in thistype of essay
• Show less0 answers
- Anonymous askedlet say the program is the following
ORG %9000 (not important..
CLR D0
CLR D1
MOVE.W
MOVE.W
ADD
ADD... Show morelet say the program is the following
ORG %9000 (not important..
CLR D0
CLR D1
MOVE.W
MOVE.W
ADD
ADD ...til here)
TRAP #15
DC.W $63
i'd like to know what will happen when TRAP #15 executes and DC.W$63 executes.
what these op-codes do??
• Show less1 answer
- Anonymous askedThe newton raphson method can be used to find the roots of anyequation y(x)=0. In this method, the (... Show moreThe newton raphson method can be used to find the roots of anyequation y(x)=0. In this method, the (i+1)st approximation,xi+1 to a root of y(x)=0 is given in terms of theith approximation, xi by the formula
xi+1=xi-y(xi)/y`(xi)
For example if y(x)=3x2 +2x-2 then y`=6x+2 and the rootsare found by making a reasonable guess for a first approximationx1 and interating using the equation
xi+1=xi-(3xi2 +2xi-2)/(6xi+2)
1. Using the newton raphson methodfind the two roots of the equation 3x2 +2x-2=0; usingc++
• Show less1 answer
- Anonymous askedIn the last part of the problem, the average access delay accounts for the web cache by modifying th... More »1 answer
- shaydudu88 askedUsing the theorems and postulates, simplify the follwingexpression to a product of two sum terms. on... Show moreUsing the theorems and postulates, simplify the follwingexpression to a product of two sum terms. one with two literals andone with a single literal:F=(a+b+c)(a+b'+c)(a'+b'+c)(b'+c')Simplify to a sum of three product terms, two with twoliterals and one with four literals:F=w'x'y'z'+w'xy'z+w'x'z'+wx'yz+w'y'z+w'xz'+w'y'z'Please explain what I must do. I need to learn this and Iwould appreciate it if someone would explain the processstep-by-step SLOWLY. Thanks• Show less1 answer
- Anonymous askedConsider the rdt3.0 protocol. Draw a diagram showing that if thenetwork connection between the sende... Show moreConsider the rdt3.0 protocol. Draw a diagram showing that if thenetwork connection between the sender and receiver can reordermessages (that is, that two messages propagating in the mediumbetween the sender and receiver can be reordered), then thealternating-bit protocol will not work correctly (make sure youclearly identify the sense in which it will not work correctly).Your diagram should have the sender on the left and the receiver onthe right, with the time axis running down the page, showing data(D) and acknowledgment (A) message exchange. Make sure you indicatethe sequence number associated with any data or acknowledgmentsegment.
• Show less1 answer
- Anonymous askedAllentown Zoo k... Show moreThis problem is concerning Control Breaks-temporary detour inthe logic of a program.Allentown Zoo keeps track of the expense of feeding theanimals it houses. Each record holds one animal's ID number, name,species (elephant, rhinoceros, tiger, lion, and so on), zooresidence (pachyderm house, large-cat house, and so on), and weeklyfood budget. The records are sorted by species within residence.Design logic that produces a report that lists each animal's ID,name, and budgeted food amount. At the end of each species group,print a total budget for the species. At the end of each house,(for example, the species lion, tiger, and leopard are all in thelarge-cat house), print the house total. At the end of the report,print the grand total.• Show less0 answers
- Anonymous asked4 msec and thecurrent... Show more
Consider a TCPconnection at a sender node in which the current estimated RTTis
4 msec and thecurrent DevRTT is 1 msec. At this time (t =0), asegment is transmitted by the
sender and itsacknowledgment successfully received at timet = S msec, without requiringany
retransmissions.It turns out, however, that this does not change the time-outinterval. Assuming
= 1/8 and= 1/4, what is S?
Instructor:• Show less1 answer
- Anonymous askedbit to denote a... Show more
In typicalimplementations of the stop-and-wait link layer protocol, one usesa single
bit to denote asequence number associated with each of the data and acknowledgmentpackets.
Consider a modifiedprotocol in which we replace this bit in data packets with a‘0’ in packets
being transmittedfor the first time, and a ‘1’ in packets which arebeing retransmitted. In this
modified protocol,we drop the bit altogether from acknowledgment packets. Assume thatthe
sender’stime-out period is large enough that a retransmission of a datapacket will never occur
unless the datapacket or the acknowledgment is actually lost. On a link on whichdata packets or
acknowledgments may be lost,explain clearly with an example why this modified protocolmay
lead to an incorrectoperation• Show less0 answers
- Anonymous askednumber rangeof [0,1023].... Show more
Consider theGo-Back-N protocol with a sender window size of 3 and asequence
number rangeof [0,1023].Suppose that at time t, the next in-order packet that the receiveris
expecting has asequence number of S. Assume that the medium does not re-ordermessages.
(a) What are thepossible sets of sequence numbers inside the sender’s windowat time t? Use
thetextbook’s convention of a window, i.e., the number ofsequence numbers in the window is
always equal to thewindow size. Justify your answer.
(b) What are allpossible values of the ACK field in the message currentlypropagating to the
sender at timet?Justify your answer• Show less1 answer
|
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2008-october-13
|
CC-MAIN-2015-06
|
refinedweb
| 6,426
| 55.54
|
Adding extra information to the property overlay
Sometimes it can be quite hard for editors to know which property they should edit or even which property they are currently editing. Especially when they’ve just created a page and are presented with a column of empty blue squares that represent editable properties. For example:
The question of whether it’s possible to modify the overlays to display extra information has come up several times and I have given a few quick answers on the forums. But I figured a blog post might be more appreciated.
Display Name
The display name for each property is surprisingly already added to the DOM for all properties except content areas. Unfortunately due to some late design decisions it was hidden so that it wouldn't cause any visual problems. Such as hiding important information on the underlying website. This means that it is actually really simple to get the names of properties to be displayed, for example, on hover of an overlay. It's just a matter of loading some styles in edit mode:
/* Display the information node when hovering the overlay. */
.Sleek .epi-overlay-item.dijitHover .epi-overlay-item-info {
color: #333;
background-color: #B4C600;
border: 3px solid #B4C600;
border-radius: 2px 2px 0 0;
display: block;
font-size: 1.2em;
top: -30px;
right: -3px;
}
/* Hide the information node when editing. */
.Sleek .epi-overlay-item.dijitFocused .epi-overlay-item-info {
display: none;
}
The first selector here says that we want to show the display name when a user hovers the overlay. The main part of this is the display tag which actually makes the display name appear. The others are there to make it look good. I would suggest tweaking these based on how you want it to appear.
The second selector is to make the display name disappear when the user is editing. So in this case when the overlay has focus. This is important for properties that are edited inline, since the display name could distract or potentially hide important information, but you can decide if it is necessary.
Thus we end up with the following:
In order to load this custom CSS file in edit mode you need to add a module.config to your solution with the following:
<?xml version="1.0" encoding="utf-8"?>
<module>
<clientResources>
<add name="epi-cms.widgets.base" path="path-to-stylesheet.css" resourceType="Style" />
</clientResources>
</module>
Good. But please fix this in the product! And also give us some options to specify some information in content areas so the editors knows what to drop in them.
This is such a simple yet effective UX improvement. Totally agree with Johan this should come out of the box.
Awsome, hopefully i will get the module.config to work as well now when i know the namespace :)
Works great!
Are these descriptions localized? (And if not, how can they be localized?)
@Anders: If by "descriptions" you mean the labels displayed next to each property (like "Name"), those are just the property names from your content type.
You can still use the old language files XML system to localize property names - see the /Resources/LanguageFiles/PropertyNames.xml in your EPiServer 7 site for an example.
I needed to make a small change in the css to make this work. Not sure if this changed in patch 4?
Instead of:
.Sleek .epi-overlay-item.dijitHover .epi-overlay-item-info
I needed:
.Sleek .epi-overlay-item-over .epi-overlay-item-info
/ Thomas
|
https://world.episerver.com/blogs/Ben-McKernan/Dates/2013/9/Adding-extra-information-to-the-property-overlay/
|
CC-MAIN-2021-17
|
refinedweb
| 583
| 56.45
|
Random Module is used to generate random things by applying random function code lines. Learn more about the Random module in python here.
Random module: Creating a random user password
In order to create a random user password we can use the symbols provided in the string module. Specifically punctuation for punctuation symbols, ascii_letters for letters and digits for digits:
from string import punctuation, ascii_letters, digits
We can then combine all these symbols in a name named symbols:
symbols = ascii_letters + digits + punctuation
Remove either of these to create a pool of symbols with fewer elements.
After this, we can use random.SystemRandom to generate a password. For a 10 length password:
secure_random = random.SystemRandom()
password = "".join(secure_random.choice(symbols) for i in range(10))
print(password) # '^@g;J?]M6e'
Note that other routines made immediately available by the random module — such as random.choice, random.randint, etc. — are unsuitable for cryptographic purposes.
Behind the curtains, these routines use the Mersenne Twister PRNG, which does not satisfy the requirements of a CSPRNG. Thus, in particular, you should not use any of them to generate passwords you plan to use. Always use an instance of SystemRandom as shown above.
Python 3.x Version ≥ 3.6
Starting from Python 3.6, the secrets module is available, which exposes cryptographically safe functionality.
Quoting the official documentation, to generate “a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits,” you could:
import string
alphabet = string.ascii_letters + string.digits
while True:
password = ''.join(choice(alphabet) for i in range(10))
if (any(c.islower() for c in password)
and any(c.isupper() for c in password)
and sum(c.isdigit() for c in password) >= 3):
break
Random module: Create cryptographically secure random numbers
By default the Python random module use the Mersenne Twister PRNG to generate random numbers, which, although suitable in domains like simulations, fails to meet security requirements in more demanding environments.
In order to create a cryptographically secure pseudorandom number, one can use SystemRandom which, by using os.urandom, is able to act as a Cryptographically secure pseudorandom number generator, CPRNG.
The easiest way to use it simply involves initializing the SystemRandom class. The methods provided are similar to the ones exported by the random module.
from random import SystemRandom
secure_rand_gen = SystemRandom()
In order to create a random sequence of 10 ints in range [0, 20], one can simply call randrange():
print([secure_rand_gen.randrange(10) for i in range(10)])
[9, 6, 9, 2, 2, 3, 8, 0, 9, 9]
To create a random integer in a given range, one can use randint:
print(secure_rand_gen.randint(0, 20))
5
and, accordingly for all other methods. The interface is exactly the same, the only change is the underlying number generator.
You can also use os.urandom directly to obtain cryptographically secure random bytes.
Random module: Random and sequences: shu e, choice and sample
import random
shuffle()
You can use random.shuffle() to mix up/randomize the items in a mutable and indexable sequence. For example a list:
laughs = ["Hi", "Ho", "He"]
random.shuffle(laughs) # Shuffles in-place! Don't do: laughs = random.shuffle(laughs)
print(laughs)
Out: ["He", "Hi", "Ho"] # Output may vary! choice()
Takes a random element from an arbitrary sequence:
print(random.choice(laughs))
Out: He # Output may vary!
sample()
Like choice it takes random elements from an arbitrary sequence but you can specify how many:
|–sequence–|–number–|
print(random.sample( laughs , 1 )) # Take one element
Out: [‘Ho’] # Output may vary!
it will not take the same element twice:
print(random.sample(laughs, 3)) # Take 3 random element from the sequence.
Out: [‘Ho’, ‘He’, ‘Hi’] # Output may vary!
print(random.sample(laughs, 4)) # Take 4 random element from the 3-item sequence.
ValueError: Sample larger than population
Random module: Creating random integers and floats: randint, randrange, random, and uniform
import random
randint()
Returns a random integer between x and y (inclusive):
random.randint(x, y)
For example getting a random number between 1 and 8:
random.randint(1, 8) # Out: 8
randrange()
random.randrange has the same syntax as range and unlike random.randint, the last value is not inclusive:
random.randrange(100) # Random integer between 0 and 99
random.randrange(20, 50) # Random integer between 20 and 49
random.rangrange(10, 20, 3) # Random integer between 10 and 19 with step 3 (10, 13, 16 and 19)
random
Returns a random floating point number between 0 and 1:
random.random() # Out: 0.66486093215306317
uniform
Returns a random floating point number between x and y (inclusive):
random.uniform(1, 8) # Out: 3.726062641730108
Reproducible random numbers: Seed and State
Setting a specific Seed will create a fixed random-number series:
random.seed(5) # Create a fixed state
print(random.randrange(0, 10)) # Get a random integer between 0 and 9 # Out: 9
print(random.randrange(0, 10))
Out: 4
Resetting the seed will create the same “random” sequence again:
random.seed(5) # Reset the random module to the same fixed state. print(random.randrange(0, 10))
Out: 9
print(random.randrange(0, 10))
Out: 4
Since the seed is fixed these results are always 9 and 4. If having specific numbers is not required only that the values will be the same one can also just use getstate and setstate to recover to a previous state:
save_state = random.getstate() # Get the current state
print(random.randrange(0, 10))
Out: 5
print(random.randrange(0, 10))
Out: 8
random.setstate(save_state) # Reset to saved state
print(random.randrange(0, 10))
Out: 5
print(random.randrange(0, 10))
Out: 8
To pseudo-randomize the sequence again you seed with None:
random.seed(None)
Or call the seed method with no arguments:
random.seed()
Random module: Random Binary Decision
import random
probability = 0.3
if random.random() < probability:
print("Decision with probability 0.3")
else:
print("Decision with probability 0.7")
|
https://codingcompiler.com/random-module/
|
CC-MAIN-2022-27
|
refinedweb
| 987
| 51.34
|
[
]
Daniel Kulp resolved CXF-3837.
------------------------------
Resolution: Cannot Reproduce
Fix Version/s: (was: NeedMoreInfo)
Invalid
Assignee: Daniel Kulp
Request for more information about the configuration unanswered in over a month.
> Allow JAXB Context customization on client
> ------------------------------------------
>
> Key: CXF-3837
> URL:
> Project: CXF
> Issue Type: New Feature
> Reporter: Parag Mehta
> Assignee: Daniel Kulp
> Fix For: Invalid
>
>
> On server side, capabilities exist to customize JAXB bindings or specifying custom data
binding class (like org.apache.cxf.jaxb.JAXBDataBinding). There seems to be no way to do
so on the client side.
> Motivation:
> If JAXB customizations are used on server side for various reasons (inheritance, java
type adapters, dynamic transient annotations, namespace mapping), the server side object model
and the WSDL differ. In case where server owners are also client owners, it would help to
use same set of classes and JAXB customizations used on the server to also be used on the
client side. Hence we would need a way to apply the same JAXB customization on the client.
> Thanks.
--
This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators:
For more information on JIRA, see:
|
http://mail-archives.apache.org/mod_mbox/cxf-issues/201111.mbox/%3C1923098896.22816.1322593180560.JavaMail.tomcat@hel.zones.apache.org%3E
|
CC-MAIN-2017-09
|
refinedweb
| 192
| 50.57
|
Unity: Capturing audio from a microphone
Posted by Dimitri | Jul 29th, 2012 | Filed under Programming
.
So, here’s the script:
using UnityEngine; using System.Collections; [RequireComponent (typeof (AudioSource))] public class SingleMicrophoneCapture : MonoBehaviour { //A boolean that flags whether there's a connected microphone private bool micConnected = false; //The maximum and minimum available recording frequencies private int minFreq; private int maxFreq; //A handle to the attached AudioSource private AudioSource goAudioSource; //Use this for initialization void Start() { //Check if there is at least one microphone connected if(Microphone.devices.Length <= 0) { //Throw a warning message at the console if there isn't Debug.LogWarning("Microphone not connected!"); } else //At least one microphone is present { //Set 'micConnected' to true micConnected = true; //Get the default microphone recording capabilities Microphone.GetDeviceCaps(null, out minFreq, out maxFreq); //According to the documentation, if minFreq and maxFreq are zero, the microphone supports any frequency... if(minFreq == 0 && maxFreq == 0) { //...meaning 44100 Hz can be used as the recording sampling rate maxFreq = 44100; } //Get the attached AudioSource component goAudioSource = this.GetComponent<AudioSource>(); } } void OnGUI() { //If there is a microphone if(micConnected) { //If the audio from any microphone isn't being captured if(!Microphone.IsRecording(null)) { //Case the 'Record' button gets pressed if(GUI.Button(new Rect(Screen.width/2-100, Screen.height/2-25, 200, 50), "Record")) { //Start recording and store the audio captured from the microphone at the AudioClip in the AudioSource goAudioSource.clip = Microphone.Start(null, true, 20, maxFreq); } } else //Recording is in progress { //Case the 'Stop and Play' button gets pressed if(GUI.Button(new Rect(Screen.width/2-100, Screen.height/2-25, 200, 50), "Stop and Play!")) { Microphone.End(null); //Stop the audio recording goAudioSource.Play(); //Playback the recorded audio } GUI.Label(new Rect(Screen.width/2-100, Screen.height/2+25, 200, 50), "Recording in progress..."); } } else // No microphone { //Print a red "Microphone not connected!" message at the center of the screen GUI.contentColor = Color.red; GUI.Label(new Rect(Screen.width/2-100, Screen.height/2-25, 200, 50), "Microphone not connected!"); } } }
At the beginning of this script, four, member variables are being declared: a boolean, a pair of integers and an AudioSource. The boolean flag is set to tell whether there’s a microphone attached or not. The two integers will later in the code store the maximum and minimum available sampling frequencies for audio recording with the default microphone. Lastly, the AudioSource object is going to be the one responsible for playing back the recorded audio (lines 9 through 16).
The Start() method is basically composed of a single if statement, that tests whether the string static array named devices at the Microphone class has a length greater than zero (line 22). A length equal to zero means that there is no connected microphone. In this case, a warning message is printed at the console (line 25). Otherwise, if the length of the devices array is greater than one, the audio recording and playback variables are initialized.
This is done by first assigning true to micConnected (line 30). Then calling the static method GetDeviceCaps() from the Microphone class (line 33). This method gets the audio recording capabilities of the device’s microphone. It receives three parameters: a string with the microphone name and two integers for the maximum and minimum frequencies. In the above script, null has been passed as the first parameter and according to the documentation; “[…] Passing null or an empty string will pick the default device“. If there’s just a single microphone attached to the computer, this won’t be a problem. Nevertheless, to target a specific microphone, you just need to pass its name to this first parameter.
Still on the GetDeviceCaps() method, the second and third parameters are respectively, the maximum and minimum recording frequencies supported by the device. This method take these two parameters with an out modifier, meaning that any value alteration made to the minFreq and maxFreq inside the method will be maintained after the method has finished its execution. It’s roughly similar as passing a reference parameter to a function in C++. Again, quoting the documentation, if the maximum and minimum frequencies values are zero, the microphone supports any recording sampling frequency.
This test is done on the following if statement (lines 36 to 40), and being true, the maxFreq value is set to 44100. The last member variable to be initialized is the goAudioSource by obtaining a reference to the attached AudioSource on the same Game Object the script is linked to.
The OnGUI() method is responsible for rendering the controls to start recording, stop and playback the recorded audio. As the Start() method, this one is composed basically of a single if statement that checks the value of the micConnected boolean (line 53). If that’s false, no microphone is connected, so a red “Microphone not connected!” message is rendered at the middle of the screen (lines 74 through 79).
When a microphone is connected, the other block of code is executed, which checks if any microphone audio input isn’t being recorded (line 53). Case that’s true, the ‘Record‘ button is rendered to the user and by clicking on it, the audio from the microphone will get recorded (line 56).
As previously mentioned, the Microphone.Start() method will be the one responsible for capturing the audio from the microphone (line 59). The first parameter it takes is a string with the name of the microphone we wish to record from. Again, passing null will make Unity pick up the default microphone. The second parameter takes a boolean that indicates whether the recording should continue if the length defined on the third parameter is reached. Passing true as in the above script makes the audio recording wrap around the length of the audio clip and record from the beginning. And the third parameter, as explained, is the length of the AudioClip this method returns. To put in a simplified manner, in this script, if an audio recorded from a microphone has 23 seconds, the final 3 seconds will be recorded over the initial 3 seconds. So, the maximum recording time is 20 seconds in this script. The AudioClip returned by this method is assigned as the AudioClip of the goAudioSource.
And, if there’s at least one microphone and the audio from one of them is being recorded, the ‘Stop and Play‘ button is rendered (line 65). Pressing it will stop the audio recording and play it back (lines 67 and 68). Just like the other static methods from the microphone class, the End() method takes a string that tells Unity which microphone the recording should be stopped. It also accepts null as a parameter to select the default microphone.
And that’s it! Here are some screenshots of the application in action:
If there were no microphones connected, a red text label stating that no microphones were found would have been rendered, instead of the ‘Record’ button.
Press this button to stop the recording and start the audio playback.
Final Thoughts
As stated in the beginning of the post, this code has only been tested on the editor and as a Windows standalone application, on a computer. It should work without much changes on the web player, by setting the necessary permissions.
I’m not sure it will work when targeting mobile platforms, even if the correct permissions are set. It works on iOS devices, as pointed out by Scottie (thanks!). I’m not sure whether it works on Android. Also, this script requires an attached AudioSource to the same game object it has been linked to. But don’t worry, attaching this script will automatically add the necessary component, because of the RequireComponent directive.
Downloads
Please share your thoughts in the comments!
Exactly what I needed and works perfectly. Thanks a lot!”;. Thanks.”
Just thought I’d let you know that the microphone works perfectly on the iOS devices, no changes were needed whatsoever. This is a brilliant tutorial and I hope you do more Unity tutorials in the future. Well done!
Thank you Scottie!
I’ll update the post.
wow , thx
Is it work on android too?
Yes, it does. At least, it did in the previous Unity version.
hey,
Great work!
How can this be used to also save a wav file?
Best
i can´t do it work in android..anyone can help me?
thanks a lot
great tutorial.
Hi,
i want to save the audio clip in memory onces i record it how can i do that
|
http://www.41post.com/4884/programming/unity-capturing-audio-from-a-microphone
|
CC-MAIN-2019-47
|
refinedweb
| 1,426
| 64.3
|
.4: Logic, Blood, and Shopping
About This Page
Questions Answered: How do I write “If either that or that condition is met?” Or “If both conditions are met?” Can I write Scala classes independently already?
Topics: Logical operators are new. The programming assignments combine assorted earlier topics.
What Will I Do? Program, mostly. There’s a bit of reading at the beginning.
Rough Estimate of Workload:? Two hours? And quite a bit more if you do all the optional assignments, too.
Points Available: A120.
Related Projects: FlappyBug, Miscellaneous, AuctionHouse1 (new).
Intro: Let’s Make FlappyBug Harder
In Chapter 3.2, you wrote
isLost, a method that defines a
Game of FlappyBug to be
over if the obstacle touches the bug.
def isLost = this.obstacle.touches(this.bug)
As things stand, it’s too easy for the bug to advance simply by lurking at the top or
bottom. Let’s edit
touches so that the player loses if an obstacle hits or or the
bug is at the top or bottom of the playing area.
Here’s one way to do it:
def isLost = if (this.obstacle.touches(this.bug)) true else if (this.pos.y <= 0) true else this.pos.y >= GroundY
That works. But it’s a very complicated way of expressing something rather simple. We’d much rather write: “If that condition or that other condition is met.” Perhaps you’ve already yearned after such an expression in the earlier chapters.
In this chapter, you’ll learn to combine
Boolean values with logical operators such
as “and” and “or”. We’ll get back to FlappyBug after a general introduction to these
operators.
Logical Operators
The Scala language supplies us with several logical operators (logiikkaoperaattori).
In O1, you’ll mostly find use for
&&,
||, and
!. The last of those you already know
from earlier chapters.
Logical operators take in
Boolean values and also produce
Booleans:
val number = 50number >= 0 && number <= 5res0: Boolean = false if (number >= 0 && number <= 5) "a valid grade" else "an invalid grade"res1: String = "an invalid grade" number == 100 || number == 50res2: Boolean = true !(number >= 0)res3: Boolean = false
&&produces
trueif and only if both subexpressions are
true. Here, the first subexpression is
truebut the second isn’t, so the whole expression evaluates to
false.
||produces
trueif either of the two subexpressions is
true(or both are). Here, the first subexpression isn’t
truebut the second is, so the whole expression evaluates to
true.
!takes only a single operand while the others take two.
Non-strict evaluation of logical operators
The operators
&& and
|| are evaluated non-strictly (väljästi). What this means
for these operators is essentially that the left-hand operand is evaluated first and
if it alone determines the value of the logical operation, the right-hand operand
isn’t evaluated at all. (We will take a broader look at non-strict evaluation in
Chapter 7.1.)
This non-strictness has practical significance, as illustrated below.
First, let’s define a couple of variables. Here, we use literals, but you can easily imagine the numbers being read from the user’s keyboard, for instance.
val dividend = 50000dividend: Int = 50000 var divisor = 100divisor: Int = 100
Let’s divide one number with the other and see what we get. As we do so, let’s play
things safe and ensure that
divisor doesn’t equal zero. We can use either
&& or
|| to do that:
divisor != 0 && dividend / divisor < 10res4: Boolean = false divisor == 0 || dividend / divisor >= 10res5: Boolean = true
Assuming the divisor is not zero, we can swap the operands and still get the same result:
dividend / divisor >= 10 || divisor == 0res6: Boolean = true
But what if the divisor is zero?
divisor = 0divisor: Int = 0 dividend / divisor >= 10 || divisor == 0java.lang.ArithmeticException: / by zero ...
The computer performs the division as it evaluates the first operand. We get a runtime
error. We never even reached the expression
divisor == 0.
On the other hand, if we check the divisor in the first operand, things work out fine:
divisor == 0 || dividend / divisor >= 10res7: Boolean = true
Since divisor equalled zero, the expression
divisor == 0 evaluated to
true. It
becomes unnecessary to evaluate the rest of the logical expression given that
true ||
anythingAtAll is always
true. Because of the non-strictness of these operators, the
computer doesn’t even evaluate the second operand. Execution order matters!
Combining logical operators
You can use rounds brackets to group logical expressions just like arithmetic and other expressions.
if ((number > 0 && number % 2 == 0) || number < 20) { println("Either both positive and odd, or less than 20.") } if (number > 0 && (number % 2 == 0 || number < 20)) { println("Positive; moreover, either even or less than 20.") }
Practice on logical operators
Study the following piece of code. Carefully consider what happens as it runs. You might wish to make notes on a piece of paper.
val first = 20 val second = 10 var third = 50 if (first > second && first + second < third) { third = 30 println("One") } val result = first > second && first + second < third if (first < second || result) { println("Two") } if (first > second || second == third) { println("Three") } third = 10 if (!(result && third >= 50)) { println("Four") } else { println("Five") }
Further improvements to the vending machine
Logical operators are a convenient replacement for multiple
ifs.
Recall the
sellBottle method from Chapter 3.4. Here is the original
Int-returning
version: } }
Here are two attempts to reimplement the method with logical operators:
def sellBottle() = { if (this.isSoldOut || !this.enoughMoneyInserted) { -1 } else { this.earnedCash = this.earnedCash + this.bottlePrice // Etc. As above. } }
def sellBottle() = { if (this.enoughMoneyInserted && !this.isSoldOut) { this.earnedCash = this.earnedCash + this.bottlePrice // Etc. As above. } else { -1 } }
Assignment: FlappyBug (Part 14 of 16: Deadly Edges)
Task description
Make FlappyBug harder as suggested at the top of the chapter. Do it as follows.
- Add an effect-free, parameterless method
isInBoundsin class
Bug. It should return a
Booleanthat indicates whether the bug is within the legal playing area, that is, between the zero coordinate and the ground level (excluding those border values). Use a logical operator to implement the method.
- Modify
isLostin class
Gameso that it also considers a game to be lost if the bug is out of bounds. Use logical operators and the
isInBoundsmethod you just wrote.
Submission form
A+ presents the exercise submission form here.
Assignment: Blood Types
Task description
The project Miscellaneous contains the package
o1.blood, which in turn contains the class
BloodType. Implement that class so that it matches the documentation that comes with the
project.
Instructions and hints
This example shows how the class should work:
val myBlood = new BloodType("AB", true)myBlood: o1.blood.BloodType = AB+ val yourBlood = new BloodType("A", true)yourBlood: o1.blood.BloodType = A+ val theirBlood = new BloodType("O", false)theirBlood: o1.blood.BloodType = O- myBlood.canDonateTo(yourBlood)res8: Boolean = false yourBlood.canDonateTo(myBlood)res9: Boolean = true theirBlood.canDonateTo(yourBlood)res10: Boolean = true
You can also run the given
BloodTestapp to try out all the possible combinations of blood types.
Once again, you don’t have to attend to special cases or erroneous input unless specifically instructed to. For example, you can count on any user of class
BloodTypeto pass in only meaningful strings as constructor parameters.
Try to implement the methods as simply as you can and without duplicating the same piece of code.
- Use logical operators. Can you make do without
ifand
matchaltogether (at least outside
toString)?
- Call the other methods of the same class. Further tip: you can pass
thisas a parameter to a method.
Submission form
A+ presents the exercise submission form here.
Assignment:
FixedPriceSale
The Scaladocs in project AuctionHouse1 describe several classes for representing items that have been put up for sale in an imaginary online auction house. In this assignment, we’ll focus on a single way to sell an item: simply giving it a fixed price. Later assignments will features auctions and changing prices.
Task description
Fetch the project AuctionHouse1 and view its Scaladocs. Implement class
FixedPriceSale
of package
o1.auctionhouse so that its behavior matches the documentation.
Instructions and hints
Start by creating a new file for the class. Here’s a recap:
- Right-click the package in Package Explorer and select New.
- Ensure that the package name
o1.auctionhouseappears in the Name field where you enter the new class’s name.
- A new Scala file should appear within the package and have the appropriate
packagedefinition at the top.
You may wish to use an instance variable of type
Option, with an initial value of
None. If you do, remember that you need to annotate the variable with a data type (as in Chapter 4.2). Like this:
nameOfVariable: Option[Type].
The Scaladocs list the class’s members in alphabetical order, but that’s probably not the most convenient order for you to implement them (nor do the methods need to be in that order in your code). You are free to choose the order in which you implement the methods, but here’s one suggestion:
daysLeft,
toString,
buyer,
isExpired,
isOpen,
advanceOneDay,
buy.
Study the docs with care. Notice, for instance, that “open” and “expired” aren’t exact opposites even though an item cannot be both at the same time.
You can use the app object
FixedPriceSaleTestfor testing. Use it.
- Note that the app object initially generates error messages, which is simply because you haven’t yet implemented the methods that the app calls. The errors will go away once you do the assignment. (Remember: the cause of an error is not always where the message points to.)
- You can initially “comment out” part of the test app if you want to test a partial version of your class.
You can also run
TestApp, a program in
o1.auctionhouse.guithat lets you create and manipulate
FixedPriceSaleobjects in a graphical window that looks like this:
Submission form
A+ presents the exercise submission form here.
Optional Practice:
Moment and
Interval
The rest of the chapter consists of practice tasks that are voluntary but highly recommended. Take them as an opportunity to build up fluency. If the weekly deadline is ominously close, you might wish to go to Chapter 4.5 before returning here. The assignments below will probably take several hours to complete.
Introduction to
o1.time
This problem will let you apply the logical operators more extensively and freely than the preceding ones. It also provides practice on a number of other concepts.
Moments and intervals
Imagine we have an application (or several) that needs to represent time intervals:
an interval begins at a particular moment of time and continues until another moment.
We intend to model these concepts as the classes
Moment and
Interval. Each
Interval object is associated with two
Moment objects that represent the interval’s
first and last moment.
Project Miscellaneous contains a package
o1.time and therein a partial implementation
for class
Moment.
Interval is missing entirely.
The given code for
Moment is explained below.
import scala.math.abs class Moment(private val time: Int) { override def toString = this.time.toString def distance(another: Moment) = abs(another.time - this.time) def isLaterThan(another: Moment) = this.time > another.time def later(another: Moment) = if (this.isLaterThan(another)) this else another def earlier(another: Moment) = if (this.isLaterThan(another)) another else this }
Momentinstance, we specify the moment in time that it stands for. Our implementation doesn’t commit to any particular unit of time (days, years, nanoseconds, etc.); any integer will do.
Momentdelegates its whole
toStringmethod to the integer it stores. Notice that you can call a method on an
Int! An
Int’s
toStringmethod returns the characters that correspond to the number; e.g., for the integer 123 we get the string
"123". (We will discuss the methods on
Ints further in the next chapter, 4.5.)
distancemethod for determining how far apart two moments are.
isLaterThan,
later, and
earliercompare moments in different ways.
General hint: make use of abstractions
One of this problem’s main themes is to learn to make use of the other methods in the classes that you write. Sure, you’ve already done that in ealier assignments, too, but this one particularly highlights the matter.
If you write the required methods completely independently of each other, you’ll find yourself duplicating code. Don’t do that. Consider what other methods you’ve created that you could call. Try to keep your code DRY. Non-redundant code is easier to modify and less vulnerable to bugs.
In fancier words: Every method is an abstraction (Chapter 1.6). You should build new
abstractions atop existing ones. For example, the method
isLaterThan is as an
abstraction of its concrete implementation, which takes the values of two instance
variables and uses an operator to compare the two:
this.time > another.time. The other
methods that need to compare two
Moments can simply use this method and don’t need to
deal with the variables directly.
A task in four phases
Implement
Interval and
Moment so that they meet the specification. Below is a
recommended workflow that you can either follow or ignore.
Phase 1 of 4: Getting started with
Interval
- Read the introductions of both classes in the Scaladocs. Also read the docs for
Interval’s methods
lengthand
toString, which you’ll implement first.
- Create a new file for class
Interval.
- Define the constructor parameters. Since each parameter needs to be stored in an instance variable, define those, too, in the class header. Should these instance variables be private?
- Implement
length. Use a method from class
Moment.
- Now and later: resist the temptation to add public members in class
Momentbeyond those request in the docs. In particular, don’t make the instance variable
timepublic.
- Implement
toString. It’s a bit more complicated. Here are some hints:
- Use the methods you have at your disposal.
- You can use an
if–
elsestructure to cover the three different cases.
- Remember that a string can be “multiplied”. For instance,
"ho" * 3yields
"hohoho".
- See the starter code in
TimeTest. Add commands there as you see fit: create
Intervalobjects and call their methods.
When are two
Moments equal?
If you use
== or
!= to compare moments , what you get is an identity comparison
(“Do these two references point to the same
Moment object?”; see Chapter 3.2.)
What you don’t get is a comparison of the
Moment objects’ actual contents. These
operators won’t tell you whether two distinct
Moment objects represent the same
moment in time, that is, whether their
time variables have identical values.
In this assignment, identity comparison and those two operators are completely unnecessary. You don’t stand to gain anything from using them. Other methods will serve you better!
Phase 2 of 4:
isLaterThan and overloading
- Add
isLaterThanin class
Interval. Note that the method name has been overloaded (Chapter 3.6): there are two methods with the same name. One takes in a
Momentand the other an
Interval. Implement the former first. Make use of an existing method.
- Implement the second
isLaterThanmethod in
Interval. Make use of the method you implemented just before. As you do so, remember a detail from Chapter 3.6: if an overloaded method calls its namesake, Scala requires an explicit type annotation for the calling method’s return type. That means you’ll need to annotate the type on at least one of the
isLaterThanmethods.
- Add more test code to
TimeTestand run it. Confirm that both
isLaterThanmethods work as intended.
Momentshould also have an
isLaterThanmethod that takes in an
Intervalparameter. Add that method to the class.
Phase 3 of 4: logical operations
Continue implementing methods on
Interval and
Moment:
- Of the two
containsmethods of
Interval, implement the one that takes in a
Moment. Use logical operators in combination with methods that you have previously implemented.
- Implement the other
containsmethod. Again, use logical operators and the other methods. Also recall what was just said about overloaded methods.
- Implement
isInin class
Moment. It essentially does “the same thing in reverse” as another method you already wrote, which gives you a very simple implementation for it.
- Implement
overlapsin class
Interval. Once again, you can find uses for logical operators and existing methods. Make sure you cover all the possible cases.
- Add more method calls in
TimeTestand test your new methods.
Phase 4 of 4: combining instances to produce new ones
The methods
union and
intersection are still missing from class
Interval. Implement them and you’re done.
Submitting
A+ presents the exercise submission form here.
How private is
private?
Student question: How can that
Moment class work?
time is private!
Let’s take a moment to consider why the given code from the previous assignment doesn’t produce an error message.
class Moment(private val time: Int) { def isLaterThan(another: Moment) = this.time > another.time
timeis
private. It’s not available for external use. But what counts as external, exactly?
Momentobject can access its own
time.
Momentobject can also access the
timeof another
Momentobject: we simply prefix the variable name with an expression that refers to another object of the same class. Here, that expression is the variable name
another.
private indicates that a program component is for internal use within the
same class. The private component isn’t accessible by only a single object
but also by the class’s other instances.
In the words of the late Nobelist:
All human beings have three lives:public, private, and secret.
—Gabriel García Márquez
In Scala, “secret” is written
private[this]. Place that modifier in
front of a variable definition, and the variable will be accessible by
only an individual object. In O1, we won’t be using such “secret”
variables.
Optional Practice: Auctions
Assignment:
DutchAuction
Go back to AuctionHouse1. Implement class
DutchAuction as specified.
Instructions and hints:
- First and foremost: make sure you understand what “Dutch auctions” are! The details are in the Scaladocs. Unless you have a clear idea of what the class should do, implementing it will be tough going.
- As you read the docs, you’ll notice that some parts of
DutchAuctionare identical to
FixedPriceSale. You can copy parts of your earlier solution into your
DutchAuctionclass.
- You can again use
TestAppfrom
o1.auctionhouse.guito experiment with your class. You can of course also write your own text-based program for testing.
- If you have an
Intand need a
Double, you can either...
A+ presents the exercise submission form here.
Are you a bit upset that you had to write the same methods again in class
DutchAuction or at least copy them from one file to the other? Outstanding!
That means that you’re motivated to reach Chapters 7.2 and 7.3 where you’ll
Assignment:
EnglishAuction
Stay with AuctionHouse1 and implement
EnglishAuction.
Instructions and hints:
- Again, first make sure you understand exactly how “English auctions” are expected to work.
- A simple
Bidhas been provided, which you should find useful. There is also a bit of starter code for
EnglishAuction.
- Even though it’s possible to solve the assignment with a buffer that stores all bids placed on an item, you don’t actually need to do that. As it turns out, you don’t need to solve every last bid to fullfill the requirements...
- Instead, you can use two variables to store just the two highest bids, as shown in the starter code. Notice these two variables’ initial values: when there are no actual bids yet, the variables refer to “empty”
Bids equal to the starting price.
TestAppwill again be of service.
A+ presents the exercise submission form here.
Summary of Key Points
- Logical operators operate on Boolean values. You can use them to express meanings such as “X and Y” and “X or Y”.
- Links to the glossary: logical operator; to overload;.
touchesreturns
trueor
false. Consequently,
isLostalso return one of the two
Booleans.
|
https://plus.cs.aalto.fi/o1/2018/w04/ch04/
|
CC-MAIN-2020-24
|
refinedweb
| 3,281
| 59.4
|
Clojure tricks; in? Collection and Threadpools
Today I was working on a small project and I ran into a couple of brain teasers. Lets take a look at what they were and what I learned.
A needle in a haystack
The first one was a needle in a haystack problem. I needed to check if
a collection, a list in this case, contained a certain value. My first
idea, without any knowledge, was to try
contains?. Cider
indicated that it is an existing function, so I gave it a try. Sadly,
it failed miserably. Since Clojure 1.1 the
contains? function is
meant to find a key in a collection. I found this to be quite
odd, as the same semantics could easily be applied to a list.
Luckily the problem is easily solved by using a little
recursion. First, ensure we have a sequence to work with using
seq. Using the first element of the haystack we check to see if
it matches our needle, if not we
recur with the rest of the
haystack.
(defn in? "Find the needle in the haystack. The haystack can be anything accepted by `seq`" [needle haystack] (when (seq haystack) (or (= needle (first haystack)) (recur needle (next haystack)))))
Now, lets test this on some various situations. How about a list or a vector? Or perhaps we should find a character in a string?
(in? "needle" '("haystack" "with" "a" "needle")) ;; => true (in? "needle" ["haystack" "with" "a" "needle"]) ;; => true (in? "needle" '("only" "a" "haystack")) ;; => nil (in? "needle" "needle") ;; => nil (in? \e "needle") ;; => true
As you might know, the
nil value will be treated as
false by
truth operators like
if or
when. So you can use it for
conditional blocks.
How about
some?
While preparing this article I thought; could I have not used
some
to have the same effect? I guess I could have. Lets try the previous
examples again, but this time with the
some function.
(some #{"needle"} '("haystack" "with" "a" "needle")) ;; => "needle" (some #{"needle"} ["haystack" "with" "a" "needle"]) ;; => "needle" (some #{"needle"} '("only" "a" "haystack")) ;; => nil (some #{"needle"} "needle") ;; => nil (some #{\e} "needle") ;; => \e
if we take a look at the
documentation we see that
the use of the predicate in
some lends itself for far more powerful
evaluations.
(some #(= 5 %) [1 2 3 4 5]) ;;=> true (some #(= 5 %) [6 7 8 9 10]) ;;=> nil
So, the time spent on the
in? function seems kind of futile in
hindsight. At the time I did not think of it, which seems kind of
silly. I am still glad I took the time to write it up though as it
teaches me how it would work.
Threadpools
The second thing I learned today was the use of threadpools. This
sounds kind of silly of course; I have been using
Java for a very,
very, very long time. If I remember correctly I started as a
Java
geek around 1997, version 1.1, so I have had my time with
Threads,
ThreadPools and the
Executor service.
The neat thing about Clojure is that it abstracts those concepts away
from you using the
core.async package. This means that generally you
do not need to worry yourself with the details of the almighty
Thread.
Today I had the need to dig under the hood though. I wrote a batch processing functionality that worked so well that it swamped my machine, stalled the status reporting to the web interface and made life quite interesting for a little while until I realised that I had a threading issue.
The documentation on concurrency and parallelism is quite a good read and it explains in quite some detail how the default thread pooling works. In my case I needed to use a threadpool that would now swamp the other parts of my system. So I chose to create a small pool of 4 threads.
The first step is to add an
import statement to the namespace
declaration to introduce the Executors package.
(import java.util.concurrent.Executors)
With the executor package we can define a new threadpool of 4 threads, which is conservative as you would normally use number of CPU cores + 2, but it keeps my machine from being swamped while running, so that is good enough for me.
(def pool (Executors/newFixedThreadPool 4))
Lets create a small test function that will return the curren threads Id.
(defn get-thread-id [] (.getId (Thread/currentThread)))
Running it in the repl returns an Id of 50, while running it on the pool returns another number.
(get-thread-id) ;; => 50 (.execute pool #(prn (get-thread-id))) ;; prints => 54
You can also try to run many instances of the function on the threadpool to make sure it will only use 4 threads. I can assure you it works, but go ahead… try it.
(for [x (range 0 10)] (.execute pool #(println (get-thread-id))) )
So today was a very nice day of learning new things. It showed the great flexibility and ease of the Clojure language and its ability to interoperate with Java.
|
https://www.buildfunthings.com/clojure-tricks-in-collection-and-threadpools/
|
CC-MAIN-2018-47
|
refinedweb
| 839
| 81.43
|
Introduction
Struts is an open source framework sponsored by the Apache Software Foundation. You can use it to maintain and expand Web applications.
IBM ® WebSphere® Studio Application Developer
Version 5.0 (hereafter called WebSphere Studio) has built-in Struts support for Struts 1.02 and 1.1 (beta 2). The Struts Configuration editor in WebSphere Studio allows easy modifications of the
struts-config.xml
file. This article describes how to create a Struts example using the built-in support in WebSphere Studio.
Struts
The Struts framework is written entirely in Java using standard J2EE APIs. In addition, it uses several well-known J2EE design patterns, such as Model-view-controller and FrontController.
Model-view-controller (MVC).
The Struts framework is the View and Controller components of MVC. The following shows how Struts maps to the MVC framework. Struts has three major components:
Actionbeans
ActionServlet
ActionFormbeans and custom tags.
Figure 1. MVC and the Struts framework
Action beans and ActionServlet
Struts provides a single
ActionServlet
(
org.apache.struts.action.ActionServlet
) to handle all browser requests. This type of framework is called the FrontController pattern. Each browser request is handled by the Struts
Action
subclass (subclass of
org.apache.struts.action.Action
). Each browser request is mapped to an
Action
subclass in the
struts-config.xml
file. The
ActionServlet
loads the mapping during initialization. To configure the Web project to pass all browser requests to the
ActionServlet
, map all URIs that end with .do (for example, *.do) to the
ActionServlet
in the Web deployment descriptor. You can then provide the actual
Action
subclass mappings in the Struts configuration file for individual request URI, such as /submit.do.
ActionForm beans
Browser requests can come with parameters. When a user submits a HTML form, the Struts framework encloses the parameters in an
org.apache.struts.action.ActionForm
bean. You can also use the
ActionForm
bean to pre-populate a form with default values that are obtained from database or other backend systems. If the user enters incorrect values in the form, the
ActionForm
may perform validations. You can re-display the form with the previous input.
Custom tags
Struts provides a large set of JSP custom tags that support the
ActionForm
beans. The custom tags support:
- Pre-population of a HTML form with values taken from an
ActionFormsubclass.
- Internationalization, such as providing text that is determined by the user's locale.
- Logic, such as showing a different title for a page based on how it is used.
Struts is a versatile framework that you can easily use with WebSphere Studio. Let's start our first Struts example.
Writing a simple Struts application
Prerequisites
Start WebSphere Studio Version 5.0:
- Go to the Window Start menu.
- Select Programs => IBM WebSphere Studio => Application Developer 5.0.
Step 1: Starting a new Struts Web Project
Create a 1.3 EAR project without the EJB / Client or Web:
- Select New => Projects => Enterprise Application Project .
- Choose Create 1.3 J2EE Enterprise Application Project . Press Next .
- Uncheck all three subprojects: Application Client project, EJB project, and Web project.
- Enter
StrutsEARfor the project name.
- Click Finish .
Create a Web project and add Struts support:
- Select New => Projects => Web => Web Project .
- Enter
StrutsSampleWebfor the Web project.
- Select the Add Struts support checkbox. Click Next .
- Select Existing Enterprise Application Project.
- Browse for the newly created EAR project. Click Next twice.
- In the Struts Setting page, Select Override default settings and choose 1.1 (beta 2) in the drop down box as shown in Figure 2. As mentioned earlier, the Struts
ActionFormis automatically populated with the HTML form data when the form is submitted. In Struts 1.0.1, only simple Java types are supported. However, in Struts 1.1 (beta 2),
java.util.HashMapor other Collection types are supported. This is discussed later in the article .
- Click Finish .
Figure 2. Overriding default settings in a Web project creation Wizard
Examine the Struts file structure in Figure 3.
Figure 3. Web project with Struts support
You will modify the following files later:
ApplicationResources.propertiesis the resource bundle for the Struts application. Locale specific and error messages are placed in this properties file.
struts-config.xmlis the xml configuration file for Struts. WebSphere Studio provides a GUI editor for this file.
For now:
- Examine the
web.xmlfile.
- Expand the StrutsSampleWeb project and double click on Web Deployment Descriptor to open to the editor.
- Go to the Servlets page. Note the following:
Note that in the
Initialization
section,
validate
is set to true. The
ActionServlet
uses the XML parser to validate and process the configuration file. It has nothing to do with the form validation that you will see later in this
article
.
How does *.do get to the correct Action class?
As mentioned earlier, the
ActionServlet
and the
Action
class are the core of the Controller tier in the MVC model. The controller is responsible to process user requests, route requests to business logic, and select the view to respond to users (see
Struts User Guide, section 4.4
). When the form submits to
submit.do
, the Struts
ActionServlet
selects the correct
Action
class to use based on the
<action-mapping>
in the struts-config.xml file.
The Struts
Action
subclass is responsible to process the user data. In the example, create a Struts
Action
subclass called
SubmitAction
. It consists of actions, such as reading and processing form data. Each form is associated with an instance of the Struts
ActionForm
subclass. Create this form class that extends the
ActionForm
class. SubmitForm, which is a subclass of
ActionForm
, is created with getters and setters of the fields. Getters and setters are mandatory in
ActionForm
subclasses.
How does the SubmitForm come into play?
Every Struts
Action
class must associate with a Struts
ActionForm
class. You can define the SubmitForm class in the FormBean page of the struts-config.xml editor in WebSphere Studio. You can then associate it with the SubmitAction mapping in the struts-config.xml file. When a request is submitted, the
ActionServlet
automatically populates the SubmitForm with the data from the actual form on the Web browser. In the SubmitAction class, use
SubmitForm f = (SubmitForm) form
to access the form's data.
Step 2: Building a JSP form using Struts taglib
Struts provides a number of HTML tags for input fields and hyperlinks for the JSP form. Here is a list of the common ones:
- Checkboxes -
<html:checkbox
- Hidden fields -
<html:hidden
- Password input fields -
<html:password
- Radio buttons -
<html:radio
- Reset buttons -
<html:reset/>
- Options (drop down box)
- Submit buttons -
<html:submit/>
- Text input fields -
<html:text
- Textarea input fields -
<html:textarea
In most of the HTML tags, Javascript events are supported, such as onmouseclick, onmouseover, and so on. For more information, see HTML Bean API .
Let's create a JSP page for this example. In the Web Perspective, create a JSP page with Struts model:
- Expand the StrutsSampleWeb project until you see the /Web Content folder. Right click on /Web Content .
- Select New => JSP File .
- Enter
submitpage.jspin the Name .
- Choose Struts JSP as the Model from the dropdown box.
- Click Next and notice that only the taglib for HTML and Bean are added. If you want to use the taglib from the other tag libraries, such as the Logic taglib, select Add Tag Libraries and choose /WEB-INF/struts-logic.tld .
- Click Finish .
Figure 4. JSP creation wizard - Struts Tag Libraries
Modify the
submitpage.jsp
page with the following code in the source editor and save it:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <%@ taglib >Pizza Order Page</TITLE> </HEAD> <BODY> <P><h1>Pizza Order Page </h1></P> <html:form Name: <html:text<br> Address: <html:text<br> Size: <html:radioSmall <html:radioMedium <html:radioLarge Toppings: <br> Pepperoni<html:checkbox<br> Onion<html:checkbox<br> Mushroom<html:checkbox<br> Hot Pepper<html:checkbox<br> Bacon<html:checkbox<br> <html:select <html:optionDelivery</html:option> <html:optionPickup</html:option> </html:select> <html:submit/> <html:reset/> </html:form> </BODY> </html:html>
Ignore the warning message in the task list about submit.do not existing. Create a
/confirm.jsp
page for the Struts
Action
class for forwarding.
In the Web Perspective, create the confirm.jsp page:
- Right click on /Web Content .
- Select New => JSP File .
- Enter
confirm.jspin the Name field.
- Click Finish .
Modify the JSP file with the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <html:html> ></TITLE> </HEAD> <BODY> <P>Thank you <%=request.getAttribute("name")%></P> </BODY> </html:html>
In the submitpage.jsp, the
customer.name
property refers / to a field inside an object.
topping(Pepperoni)
property is a key/value pair of
java.util.HashMap
. Nested properties are supported by the Struts 1.1 (beta 2) HTML taglib.
Step 3: Creating an Struts ActionForm SubmitForm class
You must define a subclass that extends the Struts
ActionForm
class. It must have setters and getters for all the form fields. As mentioned earlier, the
ActionForm
class is pre-populated with form data when the form is submitted. The
ActionForm
class may optionally have a validation method and a reset method for validating the form input, and resetting the form, respectively. They are discussed later in the
article
.
If your application has a form that spans across multiple Web pages, use only one
ActionForm
. Define a single
ActionForm
bean that contains properties for all the fields, no matter which page the field is actually displayed on. Likewise, submit the various pages of the same form to the same
Action
class. Using this design, the Web site designer can rearrange fields without changes to the business logic.
Create a Java class that extends
org.apache.struts.action.ActionForm
in the /Java Source folder under the Web Project.
- In the Web Perspective, right click on the /Java Source folder under the StrutsSampleWeb project.
- Select New => Other => Web . Expand Web => Struts . Select ActionForm Class and click Next
Figure 5. Starting the Struts ActionForm Class Wizard
.
- Enter
com.ibm.sample.strutsas the Java Package name.
- Enter
SubmitFormas the class Name . Click Next .
- This page allows you to select the fields that you want for setters and getters. Expand the tree as shown in Figure 6. Select these items:
customer.name, size, topping(Pepperoni) and type
Figure 6. Selecting new accessors (getters and setters) for the HTML form
.
- Click Next .
- Change
customer.nameto customer (without the quotes) and change its type to Customer .
- Change
topping(Pepperoni)to toppings (note the plural) and its type to java.util.HashMap .
- Change
String[]to String type.
Figure 7. Modifying the accessors
- Add
namewith the String type.
- Add
addresswith the String type.
- Click Next . The
ActionServletuses the struts-config.xml file to determine which
Actionclass and its associated
ActionFormclass to forward the control. This page automatically defines the
submitForm ActionFormbean in the Struts configuration xml file.
Figure 8. Configuring the mapping for ActionForm in struts-config.xml
- Click Finish .
The
ActionForm
contains all the fields that are in the form, and each must have a getter and a setter. You need to manually change the implementation of the getters and setters of the
Customer
object and the
toppings
HashMap. Modify the code in bold in the SubmitForm you just created as follows:
package com.ibm.sample.struts; import java.util.HashMap; SubmitForm extends ActionForm { private Customer customer = new Customer(); private String size = null; private java.util.HashMap toppings = new java.util.HashMap(); private String type = null; private String name = null; private String address = null; public String getSize() { return size; } public HashMap getToppings() { return toppings; } public void setSize(String size) { this.size = size; } public void setToppings(HashMap toppings) { this.toppings = toppings; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public String getAddress() { return customer.getAddress(); } public String getName() { return customer.getName(); } public void setAddress(String address) { customer.setAddress(address); } public void setName(String name) { customer.setName(name); } public void setTopping(String key, Object value) { //*new* method toppings.put(key, value); } public Object getTopping(String key) { //*new* method return toppings.get(key); } public void reset(ActionMapping mapping, HttpServletRequest request) { this.customer = new Customer(); name = new String(); address = new String(); size = new String(); toppings.clear(); type = new String();
Because the SubmitForm uses the Customer bean, create a java class called
Customer
under the package
com.ibm.sample.struts
:
- In the Web Perspective, right click on /Java Source folder under the Web project.
- Select New => Class .
- Enter or browse
com.ibm.sample.strutsas the Package name.
- Enter
Customeras the class Name .
- Click Finish .
- Enter the following code for the class:
package com.ibm.sample.struts; public class Customer { private String name; private String address; public String getAddress() { return address; } public String getName() { return name; } public void setAddress(String address) { this.address = address; } public void setName(String name) { this.name = name; } }
To map an input text field from the form to the name field of the customer object, use
<html:text
in the HTML tag. To access the key/value pair of a HashMap or any Collections, use
property="toppings(key)"
in the HTML tag, where toppings are the HashMap name in the example.
Note:
Only Struts 1.1 (beta 2) supports the usage of HashMap or other Collections properties.
When the reset button is pressed, the reset() method is called.
Step 4: Creating an Action SubmitAction class
The Struts
Action
class is the application logic. It makes JDBC calls, invokes other business beans, invokes EJBs, and so on. It is recommended to separate the business logic from the other beans than to have it embedded in this
Action
class. This class calls beans that have the business logic. You should implement the execute() method. It returns an
ActionForward
object that identifies the next page, such as a JSP page.
public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
The execute() method has access to the form data that you can use. Because all requests are routed to one instance of your
Action
class, make sure your code can operate correctly in a multi-threaded environment. When returning an
ActionForward
that identifies a JSP page, define a logical name for the JSP page in the struts-config.xml editor. For example, define the name
success
for
/confirm.jsp
. In the execute() method, the line
return (mapping.findForward("success"));
forwards the control to the
/confirm.jsp
page.
Create an
Action
class named
SubmitAction
under the /Java Source folder:
- In the Web Perspective, right click on the /Java Source folder under the Web project.
- Select New => Other => Web => Struts => Action Class .
- Enter
com.ibm.sample.strutsas the Package name.
- Enter
SubmitActionas the class Name. Press Next .
- In the Forwards section, press Add to add a forwards with the Name
successwith
/confirm.jspas the Path.
- Choose submitForm as the Form Bean Name.
- Choose session as the Form Bean Scope.
- Click Finish .
Figure 9. Create Action Class Wizard
Enter the following code in the SubmitAction class:
package com.ibm.sample.struts;; /** * @version 1.0 * @author */ public class SubmitAction extends Action { /** * Constructor */ public SubmitAction() { super(); } public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionForward forward = new ActionForward(); // return value SubmitForm submitForm = (SubmitForm) form; try { // Getting the value from the form String name = submitForm.getCustomer().getName(); System.out.println ("The name is: " + name); request.setAttribute("name",name); } catch (Exception e) { // Report the error using the appropriate name and ID. errors.add("name", new ActionError("id")); } // If a message is required, save the specified key(s) // into the request for use by the <struts:errors> tag. if (!errors.empty()) { saveErrors(request, errors); } // Write logic determining how the user should be forwarded. forward = mapping.findForward("success"); // Finish with return (forward); } }
Step 5: Running the sample
At this point, you have completed the example and you can run it. To run the submitpage.jsp in a WebSphere Test Environment V5:
- Right click on submitpage.jsp => Run on Server .
- Make sure the WebSphere Test Environment v5 Server is selected. Press OK .
Step 6: Validation
You can validate in the Struts
ActionForm
. When a form is submitted, the validate() method in the
SubmitForm
is implemented. Add the following validate() method to the
SubmitForm
:
public ActionErrors validate( ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if ((customer.getName()==null)|| (customer.getName().equals(""))) { // if the name is empty --> errors errors.add("Name", new ActionError ("error.customer.name")); System.out.println("errors...."); } return errors; }
After saving the SubmitForm class, notice that the ActionError compilation errors are not resolved. Right click on ActionError => Source => Organize imports.
The error.customer.name property is obtained from the resource bundle. Open ApplicationResources.properties from the /Java Source folder into an editor. Add the following lines to the properties file:
# Optional header and footer for <errors/> tag. title=Pizza Store errors.header=<hr><h3>Errors</h3><ul> errors.footer=</ul><hr> error.customer.name=<li>Name is empty
When the errors are displayed in the JSP page, it is enclosed with
<hr><h3>Errors</h3><ul>
and
</ul>. You must define the header and footer for the error messages using errors.header and errors.footer. When errors are detected, they are returned to the form with input values preserved.
You need to add the
<html:errors/>
line in the JSP file so that the errors show up. In the submitpage.jsp file, enter the line
<html:errors/>
at the beginning of the file, right before the
<html:form>.
Modify the /input field in the struts-config.xml editor:
- Open the struts-config.xml file in the editor. This file is located in the /Web Content folder.
- The
Actionand the
ActionFormbean are configured by the Struts creation wizards, except for the input field in the Actions page. This field is necessary for the validation to work properly.
- In the Actions page of the struts-config.xml editor, select /submit and enter
/submitpage.jspin the Input field. Save the changes.
You can place error messages and other messages in the ApplicationResources.properties file. For example, you can use
<bean:message
to display the title in the JSP, where the content is obtained from the resource bundle.
The resource bundle also supports internationalization (i18n - there are 18 characters between i and n ). You can create ApplicationResources_xx.properties for other languages whose ISO language code is xx.
Running the sample again with validation
Since we made changes to the Web project, let's restart the server and try the sample again. To restart the server, go to the server view, right click and select Restart .
If you leave the name empty after you submit, it returns to the form page with the error message listed in the properties file.
Figure 10. Running the sample with validation
Graphical representation of Struts application
WebSphere Studio allows you to create Web diagram to represent a Struts application graphically.
- In the Web Perspective, right click on /Java Source folder under the Web project.
- Select File => New => Other => Web => Struts => Web Diagram .
- Enter
submitDiagramas the File name .
- Press Finish . A file named
submitDiagram.gpgis created under the /Java Source folder.
- Go to the Web Structure view. This view is on the same stack as the Outline view.
- Expand on <default module> => Actions => /submit .
- Drag the icon with /submit onto the diagram.
- Right click on the icon on the diagram => Draw => Draw All From .
- Double click on the icons to go to the editor. For example, double clicking on the /submit icon brings you to the struts-config.xml editor.
Figure 11. Struts Web diagram
Conclusion
Struts is a powerful framework that encourages flexibility and detached coupling between three application tiers. Using Struts in your application simplifies future maintenance and allows the Web site to expand easily. WebSphere Studio Version 5.0 provides an easy-to-use Struts plug-in to help you maintain and expand your Web sites.
|
http://www.ibm.com/developerworks/websphere/techjournal/0302_fung/fung.html
|
CC-MAIN-2016-40
|
refinedweb
| 3,327
| 60.21
|
FDO Enhanced Schema Name Support
Overview
This document discusses various options for improving the translation of Feature Schema names between FDO and GML.
The FDO API provides functions for translating FDO Feature Schemas to and from the OpenGeospatial GML format. These functions are provided to satisfy 4 main use cases:
- Export/Import: to provide a text based export format for FDO Feature Schemas. This export format actually covers other types of objects such as Spatial Contexts, Schema Overrides and Features. However, only Feature Schemas are pertinent to this document.
- Schema Exchange: Allow exchange of schemas between FDO and external GML-based applications.
- WFS Provider: used by the FDO WFS Provider to translated GML schemas, provided by the connected WFS, to FDO Schemas.
- Publish as WFS: Allow FDO accessible data to be published via a WFS. This is the opposite of the previous use case.
One of the big challenges, in translating schemas between FDO and GML, is the converting of schema names. In order to support the above use cases, these conversions must satisfy the following general requirements:
- round trip fidelity. If the schema is translated from GML to FDO to GML, the schema name in the resulting GML schema document must be the same as in the original. Similarly, the name must not change when translated from FDO to GML to FDO.
- name uniqueness must be preserved. Different GML schemas must get different FDO schema names when read into FDO. Conversely different FDO schemas must get different GML schema names when written to GML. If name uniqueness is not preserved, schemas will be unexpectedly merged on read or write.
The structure of schema names differs greatly in either format:
- in FDO, a schema name is a free-form name, containing any character except '.' and ':'. Names tend to be short; more detailed information is typically kept in the schema description.
- in GML, the schema name must be a valid URI. Most current FDO schema names are valid URI's. However, most GML schema names tend to conform to the http scheme (see glossary), as seen in the following example. FDO Schema names would tend to not fit the http scheme.
A typical example might be a Roads schema defined by the municipality "MyCity". The FDO schema might simply be "Roads". However, the GML schema name might look something like this:
where the schema name is qualified by the owning organization. This makes it difficult to perform the schema name conversion in a way that satisfies the abovementioned requirements.
The FDO API provides a number of methods to ensure round trip fidelity and preservation of schema name uniqueness. However, these methods are cumbersome for some of the abovementioned use cases. This document looks at alternatives for making schema name translation easier when performed through the FDO API.
Current API
Feature Schema translation is provided by 2 functions on FdoFeatureSchemaCollection:
- ReadXml() converts GML schemas to FDO
- WriteXml() converts FDO schemas to GML (WriteXml() is also present on FdoFeatureSchema to allow the writing of individual schemas).
Both of the above functions take optional FdoXmlFlags parameters, which control how the translation is performed.
The following sub-sections look at the various schema name translation options currently provided:
Default Translation
FDO to GML
When no FdoXmlFlags are specified, the FDO schema name is translated by prepending a default osgeo-defined schema prefix () to the schema name and escaping any characters not allowed in a URI. For example, the FDO Schema "Water Service" becomes:
GML to FDO
When no FdoXmlFlags are specified, GML schema names are translated by dropping any http:// prefix and escaping '.' and ':' to '-dot-' and '-colon-' respectively. This means that the example schema name from the Overview:
becomes:
www-dot-mycity-dot-on-dot-ca/departments/transportation/Roads
This preserves name uniqueness but leads to a rather messy looking FDO schema name that is not easily human-readable.
When the GML schema name begins with the default schema prefix (), this whole prefix is removed from the schema name. For example:
simply becomes:
Roads
This is done to preserve round-trip fidelity.
Use Case Implications
Export/Import
The Default method works well for the Export/Import use case. The schema name is preserved on round trip from FDO to GML to FDO. The prefix is added when the feature schemas are written to GML and removed when they are read back from GML. The fact that the GML schemas all look like they're owned by OSGeo is not an issue. Actors, for this use case, aren't concerned about the GML format itself; they just want to be able to export FDO schemas and re-import them later.
Schema Exchange
The Default method does not work well for the Schema Exchange use case, since it generates rather messy FDO schema names from the GML names. Also, when FDO schemas are written to GML, the schema name always gets the default prefix prepended. Most customers would likely want the GML schema name to be a URI that reflects their own organization, rather than OSGeo.
There is also a defect which occurs when a schema name, that doesn't start with the default prefix, is round tripped from GML to FDO to GML. The GML Schema name:
becomes:
www-dot-mycity-dot-on-dot-ca/departments/transportation/Roads
in FDO. However, when written back to GML, the default prefix is still prepended to the schema name, giving:
http: fdo.osgeo.org/schemas/feature/
Therefore, round trip fidelity is not preserved.
WFS Provider
The Default method is not applicable to the WFS Provider use case. The WFS Provider always passes FdoXmlFlags to the ReadXml function.
Publish as WFS
As with the Schema Exchange use case, the default method does not work well for the Publish as WFS use case since all schema names end up prefixed with.
Customized Schema Prefix
The FdoXmlFlags class provides a url attribute that allows the default osgeo schema prefix to be overridden. This url is then used to prepend schema names on writing to GML and for stripping off prefixes when reading from GML. For example, if the url is set to, then the FDO schema named "Roads" becomes:
when the schema is written to GML. If this schema is read back from GML. the url prefix is removed and the FDO schema name becomes "Roads".
This method works better, for the Publish as WFS use case, than the default method. The customer can control what the GML schema name looks like and can make it reflect the URI's used by their organization. However, there is a limitation in that the same schema prefix gets applied to each schema in the schema collection. For example, if the schema contains a "Roads" and "WaterService" schema, and the desired GML Schema names are:
then each schema must be written by a separate WriteXml() invocation, with a different url flag.
For the same reason, this method works better than the default method for the Schema Exchange use case. However, there is one caveat: round trip fidelity is only preserved if the same url is specified on both ReadXml() and WriteXml(). Also, the GML schema name must start with the url prefix for round trip fidelity to be preserved. This might be difficult for an application to manage, especially if a different prefix is required for each schema.
This method would not likely be used in the Export/Import use case, due to these extra complications in managing the prefixes for each schema.
This method is not applicable to the WFS Provider use case.
Short Prefix as Schema Name
Most GML schema documents associate a short prefix with each schema name. This short prefix is used to define references to the schema, in other parts of the document. This makes the GML document smaller and more readable. The short prefix is not guaranteed to be unique within a GML document. However, it is unique for the XML element where it is defined plus all sub-elements.
The FdoXmlFlags provides a SchemaNameAsPrefix setting. When set to true (the default is false), the short prefix becomes the FDO Schema name, when reading from GML to FDO. This setting is only applicable to the ReadXml() function. WriteXml() always uses the url setting to generate the GML schema names.
This method is used by the WFS Provider and works well for this use case. Although not globally unique, these prefixes are unique for a particular WFS. The prefixes are also very similar in format to a typical FDO Schema name in that they tend to be short and easily readable by humans.
This method is not applicable to the other use cases, since all of these require the use of the WriteXml() function. GML to FDO to GML round trip fidelity is not preserved. The full URI for the schema name is lost when translating to FDO, so it cannot be reliably re-constituted when translating back to GML.
Requirements and Gap Analysis
The current API handles the Export/Import and WFS Provider uses cases fairly well. However, the handling of the Schema Exchange and Publish as WFS use cases is cumbersome for the following reasons:
- customer must usually supply a schema prefix and must ensure that consistent prefixes are used when reading and writing the feature schemas.
- due to a bug, round trip fidelity of schema names is not preserved when the schema name does not start with the schema prefix.
- For a single ReadXml() or WriteXml() operation, there is no way to apply a different schema prefix to each schema.
- On ReadXml(), if the GML schema name is not prefixed by the schema prefix, a messy looking FDO schema name is generated.
The main requirement is to streamline the handling of these two use cases. MapGuide currently (or plans to ) supports publishing FDO data sources through a WFS, so supporting this Publish as WFS likely takes priority over Schema Exchange. (TBD: verify MapGuide's WFS publishing requirements).
Recommendation Summary
Section 'Solution Options' below explores a number of solution options. From these options, a number of recommendations can be made:
- It is recommended that the Schema Name Attributes option be implemented (see 5.2 Schema Name Attributes). Although not perfect, it is the best option mentioned in this document.
- it is not currently recommended that we allow '.' and ':' in schema names (see 5.1 Simple Default Translation). However, this option would make schema names more readable so it should be explored further to see if the potential drawbacks can be addressed.
Solution Options
The following lists some options for improving schema name conversion. These options are not necessarily mutually exclusive. However, it is unlikely that we'd implement them all since that would add a lot of complexity to the FDO API
Simple Default Translation
Under this option, the url setting for FdoXmlFlags would no longer have a default. When no FdoXmlFlags are specified, ReadXml() and WriteXml() would not usually modify the schema name, meaning that the GML and FDO names would usually be identical.
WriteXml() would only modify the name if it is not a valid URI. In this case, the name would be adjusted by escaping any non-conforming characters.
ReadXml() would only modify the name if it contains any escaped characters, which it would unescape. ReadXml() would no longer escape '.' and ':'. This has implications on the FdoFeatureSchema object in that these two characters would have to be allowed in schema names. This can be done by removing the no '.' or ':' restriction from schema element names. However, we'd need a way to indicate when these are literal characters when they appear as qualified names. One possibility is to mandate that each component of a qualified schema element name must be enclosed in double quotes when it contains a '.' or ':'.
When the url FdoXmlFlag is specified, the behaviour would be as now: WriteXml() would tack this url prefix onto the schema name and ReadXml() would remove it if present.
Pros
- Simpler approach. For the default case, we don't need to worry about tacking on and stripping off prefixes.
- FDO Schema Names derived from GML are more readable. The names can still be long but at least they won't contain the '-dot-' and '-colon-' sequences.
- Works well for the Export/Import and Schema Exchange use cases as long as both ReadXml() and WriteXml() are done in FDO 3.3.0. Not applicable to the WFS Provider use case.
Cons
- Backward Compatibility. For the Export/Import and Schema Exchange use cases, schema name round trip fidelity is not preserved if WriteXml() is done from pre-Slate and ReadXml() from FDO 3.3.0 or vice versa. The reason is that one operation will use a different name translation method from the other. This is more of a problem for Export/Import. The bug mentioned above already introduces round trip fidelity problems for the Schema Exchange use case. The backward compatibility issues could be mitigated if we could detect when one of the operations was done using pre-slate. In this case the operation done in slate would use the pre-slate name translation rules. However, this eliminates the simplicity pro since we still have to keep the old name translation algorithms around.
- Provider compatibility. Some providers might need changes, since current code based on assumption that schema element names do not contain '.' or ':'.
- Qualified Schema Element name compatibility. This option changes the rules for constructing qualified element names. In pre-slate, double quotes are always literals but in Slate they would be delimiters. It is unlikely that any pre-existing schema names start and end with a double quote but it is possible.
- GML Schema names no longer guaranteed to follow the http scheme. Almost every GML schema we've seen sofar follows this URI naming scheme, so customers might complain if we don't always follow it. Therefore, this option does not work well for the Publish as WFS use case. Clients doing this sort of publishing will likely start specifying FdoXmlFlags to WriteXml to ensure that the GML Schema name follows the http scheme.
Conclusions:
- If we were starting from scratch, this would be a good option. However, at this stage, it is not really viable, due to backward compatibility issues, since these issues wipe out the advantages in simplicity.
Schema Name Attributes
Under this option, attributes would be added to the GML and FDO schemas to specify the name of the schema in the other domain.
An xs:schema/fdo:name attribute would be added to the FDO XML format, to specify the equivalent FDO name for schema.
WriteXml() would write this attribute to the GML document.
when present, ReadXml() would take this attribute as the FDO schema name. Otherwise, the FDO Schema name would be generated from the GML name as is currently done.
A globalName attribute would be added to the FdoFeatureSchema class:
ReadXml() would set this attribute.
when present, WriteXml() would use this attribute as the GML schema name. Otherwise, the GML schema name would be generated from the FDO schema name, as is currently done. Hopefully, the GlobalName would be set to a valid URI. If not then WriteXml() would escape any non-conforming characters. Alternatively, we could restrict the GlobalName to be a valid URI.
From a semantic standpoint, the name attribute for FdoFeatureSchema would be unique within a particular domain (e.g.: an FDO Datastore, an FdoFeatureSchemaCollection in an application). The GlobalName attribute would be intended to be universally unique, or least unique among all organizations that use the feature schema.
Pros:
- Good for Schema Exchange use case. Customer no longer needs to ensure the same url FdoXmlFlag is used for both WriteXml() and ReadXml(). For the Schema Exchange, case it also opens up the possibility of using the Short Prefix as Schema Name method, since it eliminates the problem of reconstituting the GML schema name on WriteXml().
- Flexible. The GML and FDO schema name correspondences can be set on a per-schema basis.
- Still a relatively simple option. Much simpler than the Schema Overrides and Schema Namespaces options discussed below.
- Good for Publish as WFS use cases. Publisher can set the GML name for each FDO schema explicitly.
- GML schema name can be persisted in an FDO Datastore.
- Alternatively, GML schema name can be set on the Feature Schema just before it is converted to GML. This can easily be done via the FDO API.
Cons:
- There is no guarantee that these new settings will be persisted. This limits the cases where these settings can be effective. If an FDO schema goes through the following steps:
- Write to GML
- Read GML into 3rd party application
- Write from 3rd party application to GML
- Read from GML
the fdo:schema name will likely be lost when the schema goes through the 3rd party application.
FDO providers would not necessarily be immediately modified to support the GML namespace FdoFeatureSchema attribute. Therefore, the following steps:
- Read from GML
- Apply schema to FDO datastore
- Describe schema back from datastore
- Write schema to GML
will lose the GML Schema name if the datastore's provider does not handle it. However, this particular problem can be mitigated by ensuring that the SDF and RDBMS providers support this attribute.
This con would be applicable to the Schema Exchange and Publish as WFS use cases. Export/Import and WFS Provider would be unaffected.
- For cases where the FDO schema name cannot be persisted in the GML document, it would be possible for the application to add it to the document just before it is read into FDO. This is possible to do but not quite straightforward since there is no simple FDO API to do this. It would have to be done via the Xerces DOM classes or by an XSL transformation.
- There is overlap between the globalName attribute and the targetNamespace attribute on FdoSchemaMapping (See next section), since both would represent the GML schema name. We could have a precedence rule (e.g. FdoSchemaMapping.targetNamespace trumps FdoFeatureSchema.globalName). However, having multiple places where the same attribute can be set makes the FDO API more complicated.
Conclusions
- This is a viable option. Although it doesn't help with Schema name translation in all cases, it would still handle a lot of cases
- Despite the overlap with GML schema overrides, this would currently be the recommended option, since it is the best one mentioned in this document.
Schema Overrides
The FdoXmlSchemaMapping class already provides a way to match FDO and GML names for each feature schema. This is provided by this class' name (FDO name) and targetNamespace (GML name) settings. This class can already be passed to ReadXml() and WriteXml() via the FdoXmlFlags. We'd just need to start using its mappings in ReadXml() and WriteXml().
Pros:
- Flexible. The GML and FDO schema name correspondences can be set on a per-schema basis.
- More consistent with rest of FDO since GML names specified as GML-specific overrides.
- Opens up the ability to specify overrides for other FDO schema elements and customize how they are translated to GML. This would allow us to round trip other GML and XML Schema constructs, that don't easily fit into FDO, such as xs:choice elements.
Cons:
- More complicated API. Client must create set of override classes, instead of just setting the schema name attributes or FdoXmlFlags.
- Problematic for Schema Exchange use case. Instead of ensuring consistent url prefixes are used by both ReadXml() and !WriteXML(), the customer must ensure that consistent GML Schema Overrides are used. Instead of having to manage names, they have to manage object hierarchies or XML fragments.
- Problematic for Publish as WFS use case. The GML Schema Overrides must be persisted somehow so that consistent GML schema names are used, each time someone retrieves schemas from the WFS. Currently, they must be persisted in some file storage location.
One way to mitigate this con is the allow them to be stored in the provider datastore if the provider supports FdoIApplySchema. The RDBMS provider implementations of this command can take a set of schema overrides. However, they discard all overrides except those for that particular provider. A possible enhancement would be for the RDBMS providers to be able to persist schema overrides from other providers. This could be done by adding a CLOB column to f_schemainfo, where these overrides would be stored in XML format. There is a problem with doing this in that Schema Overrides cannot be serialized to XML without their corresponding provider being present, which is not guaranteed. Perhaps this enhancement should be limited to just handling GML Schema Overrides. These overrides can be serialized using only core FDO.
Conclusions:
- This is the most elegant solution but it lacks the simplicity of the Schema Name Attributes option:
o it requires the use of Schema Overrides, which are not popular with application developers.
o the persistence problems are worse. Instead of needing to persist a name, a whole set of classes or an XML fragment must be persisted.
Schema Namespace
Under this option, the concept of a Schema Namespace would be added to FDO, where Feature Schemas would be grouped into namespaces. The intent of the namespace name would be to contain the name of the organization that owns the schema. This could be a complex path as per the http URI scheme. The Feature Schema name itself would tend to be a simple short name as it is now.
On WriteXml:
The GML schema name would be fdo_ namespace + '/' + fdo_schema_name
On ReadXml:
the GML schema name would be split at last '/'. The left part would become the FDO namespace, and the right part the schema name. If the GML schema name does not contain'/' then it would become the FDO schema name and the namespace would be the default namespace (see below).
There are a couple of sub-options for representing the namespace in FDO. These are discussed in the following subsections, along with Pros, Cons and Conclusions.
Full Object
Under this sub-option, the namespace would be a fully fledged Fdo Schema Element. Feature Schemas would be grouped into namespaces. This could be done by adding the following classes:
class FdoSchemaNamespace: public FdoSchemaElement { FdoSchemaCollection* GetSchemas(); } class FdoSchemaNamespaceCollection : public FdoSchemaCollection<FdoSchemaNamespace> { }
Currently, FdoFeatureSchemaCollection is the highest level schema object. Under this option FdoSchemaNamespaceCollection would become the highest level object.
The SDF and RDBMS providers would be changed to handle namespaces. For the RDBMS providers, this would likely mean adding a new MetaSchema table. For backward compatibility, we'd need to introduce the concept of a default namespace. Feature Schemas in pre-existing datastores would automatically go under the default namespace.
For backward compatibility reasons, it would not likely be possible for FdoIDescribeSchema and FdoIApplySchema to handle namespaces. We'd need new commands:
class FdoIApplyNamespace { void SetNamespace( FdoSchemaNamespace* namespace ); FdoSchemaNamespace* GetNamespace(); void Execute(); } Class FdoIDescribeNamespace { void SetNamespace( FdoString* namespace ); FdoString* GetNamespace(); FdoSchemaNamespaceCollection* Execute(); }
TBD: Ways to apply and retrieve schema overrides for a namespace or collection of namespaces would also be need to be added.
FdoIApplySchema, FdoIDescribeSchema and FdoIDescribeSchemaMappings are all geared to the idea that the FdoFeatureSchemaCollection is the highest level object. Therefore, the addition of namespaces would affect these commands. For backward compatibility, the best way to handle these commands would be to restrict them to handling feature schemas in the default namespace. The new commands must be used to access and manipulate schemas in other namespaces. It would be possible to allow FdoIApplySchema to handle schemas from non-default namespaces, since the namespace would be the feature schema's parent. However, it would be inconsistent to allow FdoIApplySchema to handle these schemas if they cannot be retrieved through FdoIDescribeSchema.
Feature Commands would also be impacted since these can take qualified class and property names. These qualified names must be able to contain the namespace name if they are to be unique within a particular FDO datastore. This would mean changes to providers that add support for namespaces.
Although a new command adds complexity, this could be an opportunity to add incremental schema describing. Currently, when a schema is described, all of its classes and properties are retrieved. There is no command to just list the schemas or just the schemas and classes. This affects performance, since callers to FdoIDescribeSchema always get the entire schema when they might be just interested in part of it.
The ability to just list certain objects could be provided by an elementLevel attribute on FdoIDescribeNamespace:
SetElementLevel ( elementType level ) elementType GetElementLevel()
where elementType is one of (namespace, schema,. class, property, constraint, all). When set, Execute() would only return elements down to that level. To list only the namespaces, set elementType to namespace; to list namespaces, schemas, and classes set elementType to class. Setting elementType to property would cause everything except for unique and property value constraints to be retrieved (this would have performance benefits for RDBMS providers). Setting elementType to all would retrieve everything.
Pros:
- More generalized than the Schema Name Attribute approach. Instead of putting a schema override on FdoFeatureSchema, we add a new provider-neutral concept to the Fdo Feature schema model.
- Better than the Schema Override approach since a separate Schema Overrides set is not required to customize schema name translation between FDO and GML.
- Flexible. The GML and FDO schema name correspondences can be set on a per-schema basis.
- Provides an opportunity to support incremental schema describing
Cons:
- Existing providers might not immediately add support for namespaces. When these providers are used, it is not possible to persist the GML to FDO schema name correspondences.
- Schema names themselves no longer unique, unless also qualified by namespace. Some applications might rely on schema names being unique
- Introduces a whole new level to the Fdo Feature Schema model, adding to its complexity. This isalso a departure from the OpenGeospatial model, where a schema is a namespace, rather than being contained in a namespace.
- This option may seem to get rid of the problem where schemas read from GML have long names. However, it merely splits these long names and puts the more complex part in the namespace name. Clients still new need both namespace and schema name to uniquely identify a schema.
Conclusion:
- This option is viable but not recommended. The main reasons are:
o it departs from the OpenGeospatial schema model
o it adds complication to the FDO Feature Schema model
o the implementation effort is a bit high.
Just a Name
Under this option, namespace would not be a fully fledged Fdo Schema Element but merely a new attribute on FdoFeatureSchema:
class FdoFeatureSchema { void SetNamespace( FdoString* namespace ); FdoString* GetNamespace(); }
The Schema name would no longer be unique within FDO Datastore, the combination of namespace and schema name would be unique (Otherwise, this option would be the same as the Schema Name Attributes option).
FdoFeatureSchemaCollection would be impacted in that it cannot hold schemas of different namespaces since schema names must be unique within each collection. Because of this, FdoIDescribeSchema cannot retrieve all schemas for an FDO datastore if they are in different namespaces. This necessitates adding a new command:
Class FdoIDescribeNamespace { void SetNamespace( FdoString* namespace ); FdoString* GetNamespace(); FdoFeatureSchemaCollection* Execute(); }
Note that it is a bit different than the FdoIDescibeNamespace from the previous section, in that it returns an FdoFeatureSchemaCollection. Therefore, this command will only be able to retrieve the schemas for a single namespace. This also means we need an extra command to list all the namespaces on a datastore.
We'd still need to add namespace to qualified schema element names and modify the feature commands to handle the namespace component.
Compared to other options, this option has the same pros and cons as the Schema Namespace - Full Object sub-option. When compared with Schema Namespace – Full Object, it has the following pros and cons:
Pros:
- introduces a bit less complexity to the FDO Schema model in that there is no new FdoSchemaNamespace class.
Cons:
- less flexible since FdoIDescribeNamespace cannot retrieve schemas for all namespaces.
- an extra command is required to list namespaces, since there is no FdoSchemaNamespaceCollection class.
Conclusion:
- Same Conclusions as for Schema Namespace - Full Object. However, eliminating the FdoSchemaNamespace and FdoSchemaNamespaceCollection objects doesn't buy us much so this sub-option is not recommended.
Open Issues
- Does MapGuide currently support exposing an FDO datastore as a WFS? If so, have they encountered problems generating the targetNamespace for each schema? If not currently supported, do they plan to support Publish as WFS in the future.
|
https://trac.osgeo.org/fdo/wiki/FdoEnhancedSchemaNameSupport
|
CC-MAIN-2022-33
|
refinedweb
| 4,747
| 62.88
|
Longhorn (heart) RSS
- Posted: Jun 24, 2005 at 10:26 AM
- 232,979 Views
- 147 that I have a huge bias here, but I really think that MS is doing a really great thing when it comes to RSS. The beautiful part of it is that amount of work that an application developer no longer has to do. I think that RSS is going to be so much broader because MS is putting the work they are doing into the platform. The nice part is that this is not novel work… soon you’ll see these kind of platform investments in every platform. The surprising part is that any one else could have done the work first, but MS did. I think this may be the first time in a long time that MS has done something big that other people will emulate. Because knowing what RSS is and parsing XML for a dev is absolutely useless. It’s like knowing how to handle a TCP/IP packet. It’s the start of a brand new world. And when you can synch your databases, web directories, book marks, photos, calendars, reports, contacts, sales pipelines and everything else you can think of over RSS, you can have announcements like this to thank for kicking it off.
Lets hope everyone waits a day or two before someone submits this to /. and Channel 9 goes down again.
Yeah, SlashFUD always posts old news anyhow... I figure it will take them a week to find this.
What's this I hear?
Haven't finished watching the video yet..
mVPstar
I loved the Amazon demo as well.
I crave more info!
Hmm, RSS Everywhere? I thought RSS was very specfic XML for news updates. Wouldn't XML Everywhere be more appropriate?
I gotta say, great application Walter!
And the whole thing is stupendous and great. This makes my day. The team has a tiger by the tail. The best of luck to y'all in delivering a great set of features for us developers.
♥
RSS
Um, cause it does change?
What, the NT kernel? You've got to be joking...
Oh and Neopets + RSS = uber 1337
Kernel changes in XP
I want to be the first to ask for a Longhorn (heart) RSS t-shirt.
Thanks
Ever heard of Itanium?
You really should do more research on some topics before commenting on them.
Take a look at
Thanks
-Dave
Tiger by the tail? Tiger was released almost two months ago and they've had RSS in Safari that whole time. When is Longhorn gonna be released?
Now all I have to do is to teach my IE friends who have no clue about RSS how to actually use it in order to get their news, including my rants on videoblogs.
Raymond M. Kristiansen
Norway
We should be fine. I found the problem. Let's see if I fixed it...
C
Also, here are some close screenshots of IE7 from Bink.nu:
-j
"What happens if there are multiple feeds on a page, but they are for different things? For example, lets say my company site has a "News" feed and a "CEO" feed, will IE7 only see the first one listed on the page?"
I am wondering about this too. Some blogs have an RSS feed per category. I could see a simple solution to this. Make that RSS on IE7 be a button with a drop down. Get the first (or default) feed when you click the button. Press the drop down arrow and see all the other feeds you can subscribe to.
Not everyone, but it sure looks like it at the intro to the video. The PM team is often out in front as the "public face" of a product team.
Seriously, the RSS PM team worked super hard on the RSS demos and the Gnomedex event. My dev team was certainly doing our part making the platform solid (IE7 and the RSS bits are real code checked into a real branch of the Longhorn sources) but the Outlook demos, List demos, etc. were all coded by the PMs.
What you see Amar showing is a testament to the strength of our PM team. Big time kudos to them!
Maybe next time I'll be able to be there for Scoble's camera. I'll make sure to bring along some developers.
Basically, our current thinking is that the dropdown is too complex, too much choice. We want the RSS button to be dead simple "boom, RSS preview", not a dropdown to make a secondary selection. So the RSS feed button connects to the first autodiscovered feed on the page. With that implementation, we hope to encourage websites to list their primary feed via autodiscovery rather than a long list.
Note that with many websites, the autodiscovery list is not really multiple contents feeds so much as multiple content formats. That's not really helpful to very many users.
In the Tools / Feeds menu, you can find a cascade of all autodiscovered feeds on the page.
Likewise, some feeds are offered in multiple formats - there might be HTML and plaintext versions of the same feed. Firefox's built-in RSS subscription method displays a menu of all available <link rel> feeds.
One solution for this is to continue to use orange XML buttons (yuck) but it would be nice if IE could offer a simple UI for this.
On other notes... certainly XML is a good way to distribute content. Imagine an RSS patch-distribution system, or virus/spyware-definition-distribution system. But I have to wonder how far generalization-of-RSS should be pushed. I don't agree with the "RSS for everything" mantra. Some things deserve to be their own XML specialization. The location of one's orange sneakers, for example, is probably sufficiently different from news stories to have its own specification. Similarly, a list of active job opportunities might benefit from having it's own XML specification, and might not be sufficiently RSS-ish to work as an RSS generalization. If the RSS spec + extensions becomes too overly huge, it puts a correspondingly huge burden on applications that want to call themselves "RSS clients."
But surely control should be given to the site publisher to decide how best to serve their user profiles. Sites that are less technical in nature could simply scale back to a single feed option. Ian Hickson could continue to offer plaintext and HTML formats of his feed.
EDIT: I don't mean to come off negative. Integrated RSS is very cool.
What control?
Nothing we're doing prevents a publisher from listing multiple feeds via autodiscovery.
IE's RSS button will show the first one in the list because we chose simplicity over flexibility. We had lots of debates about this, and I think we're making the right choice.
Thus he RSS button takes you to the feed, not dropping a menu of everything possible from the publisher. Our current plan is that IE7 will show the full list off a cascading menu item.
... yes it is. I myself have a website on which I was going to offer multiple autodiscovery feeds (linked from the same HTML page, with different content.) IE7's demoed behavior is causing me to change my mind - I'll have to stick to orange XML buttons so that users won't get confused by the RSS button in the IE chrome. Maybe I'll hack up a conditional comment to hide the autodiscovery feeds from IE7... ah, the irony...
Things should be as simple as possible - but no simpler.
-- Albert Einstein
OK the RSS button is on the toolbar and not in the address bar, but the rest is just the same. I was waiting to see a duplication of the content-length slider in Safari, expecially when he started talking about how long the RSS preview page was.
Whats the benifit of Calender items in RSS over vCal? iCal and Sunbird etc already support vCal subscriptions for much the same effect. These standards already exist and are widely used outside of Microsoft's applications, why invent a new one?
Whats the interface that alerts the use when new items are available in the feeds, or does the user have to keep visiting the RSS preview page?
If any application can add items to the users feed list through the API then I expect to see malware automatically subscribing people to feeds that pop up advertising/pr0n every few minutes. What controls are in place to prevent unwanted 3rd parties from adding to the list without permission, a registered RSS application whitelist? LUA wouldn't apply here since it is the user's own data. I certainly hope is isn't accessible to Javascript. I like the idea of a common platform, but you end up with monoculture issues pretty quickly.
IE7 is being released before Longhorn isn't it? So we should see these features sooner than 18 months.
Will there be at least a basic calender componant in Outlook Express for Longhorn, or do you have to have full Outlook?
So when do we get Link Rel tags on Channel9 to subscribe to feeds of individual threads? Firefox already goes looking for them and comes up empty.
--damn language filter.
Why, I made it up, of course... just like I make up all my facts.
Seriously folks, it seems to be a folk attribution. Here's a subtly different version cited on the VS2005 Team System blog
"Einstein reputedly said (although no one is quite sure), that a theory should be as simple as possible, but no simpler."
EDIT: And another version on a mug sold by the Exploratorium in San Francisco:
"Everything should be made as simple as possible, but no simpler."
EDIT2: Einstein usually spoke German, so maybe it got lost in translation. His last words are lost, because his nurse didn't speak German.
So quite frequently a dropdown approach would show either multiple formats (low value to end users) or it would be a single item list (no value to end users). For pages like that, I think our RSS button has the right implementation.
For the less frequent "index of feeds" pages, then your approach of showing multiple feeds on the page is fine, IMHO. If there is no single "best feed" for the whole page, then it just might be a good idea to not use autodiscovery. Your choice.
Agreed. It's a tricky UI problem.
Couldn't you have a button and a drop-down, show the button for sites with one feed, and show the drop-down for sites with multiple feeds?
Or just have a button, and if the site has multiple feeds, have the button pop up a dialog with a list of checkboxes, with only the first one checked by default?
I'm a little confused as to why you think multiple formats will be of low value to end users. Surely that depends heavily on the audience. Suppose the feed is a video feed - I imagine there's value in allowing at least three feed formats (Windows Media, QuickTime, Real...)
Or if the feed is a news site, there's value in allowing auto-sense subscription to any or all of the various "channel" content from the home page.
(Note the media player is an example of exclusive feed options, whereas the news channel is an example of inclusive feed options.)
With IE7 supporting feed autosense, I'm sure the RSS providers will be quick to reassess how their feeds are presented to browser users. Look how quickly rel="alternate" links were added for Firefox, with a mere < 10% browser share.
EDIT: Or perhaps the answer is to allow publishers to specify an OPML file as an alternate link...
A big part of being simple is being predictable. A button that sometimes navigates to the feed and sometimes needs a secondary choice isn't predictable.
We spun around a lot with discussions like these. I'm happy to listen to more ideas on how to make the RSS button be simple yet keep the functionality people want.
By multiple formats, I mean "RSS .92, RSS 1.0, RSS 2.0, ATOM" - a list of transport formats is of low value to the user. I don't mean video vs. text.
Or an option that can change the behaviour from either a simple button or a dropdown box.
Fair enough... so you agree there would be value in providing multiple feeds for different formatting options of the deliverable content (as opposed to merely different formatting options for the markup?)
Perhaps a solution to the RSS vs. ATOM question is for providers to mark up their rel="alternate" links as:
type="application/rss+xml; rssversion=0.92" (text/html; charset=utf8)
type="application/rss+xml; rssversion=1.0"
type="application/rss+xml; rssversion=2.0"
and whatever ATOM is
Then IE could select the most recent version it understands (hopefully when RSS 3 comes out, IE wouldn't try to interpret it until it was patched to have RSS 3 support)
Well its just about which side of the button you click, either on the icon or on the down arrow. People have coped with it in browsers for years, no need to oversimplify it down to just a single button. Adding a user option to change the button appearance is just unneed complexity.
Speaking of which... where are they???
As for an option, "NFW" is what I generally say to anyone that wants to add one more option. If there was any doubt, take a look at our Internet Options dialog - especially the "maze of twisty passages, all alike" of Advanced Options.
Seems better than having to go look in a menu instead.
Thats a Longhorn style window, so the back-forward buttons are no longer part of the toolbar and are now more like part of the window chrome.
In Longhorn Shell Windows + IE7 + WinFX Navigation Applications will share a common style of back-forward button in to top left corner of the chrome.
They are in fact putting IE in a very tight straightjacket using NT permissions.
The problem with virtualisation is people still want to move content from IE to their computer. Want to right-click on an image and save it/set it as your desktop wallpaper? That image now has to traverse to the real PC in some manner.
With the locked-down IE you need some method of elevating the IE processes permissions so it temporarily has the rights to write just that particular file to the users profile.
If you are using virtualisation you need a way to alert the host environment of a file transfer request initiated from the virtualised environment.
"Do a good job naming your elements prefixes. No one wants to deal with an element of <wqe412> when <color> is a lot more understandable.
Do a good job with your namespace prefix too. woot is crap when shirt makes more sense (combining this with the above maxim, you've got <shirt:color> instead of <woot:wqe412>)."
Quoted material gratuitously borrowed from.
How is it easy? Any action that can be initiated by the IE guest process can also be initiated by exploit code that has taken control of the IE guest process.
How can the host environment detect if the guest IE process has been exploited?
If the host environment accepts file save requests from the guest environment then any exploit code would be able to save files to the real hard disc, which defeats the point of the virtualisation.
I guess it depends on what sort of parser you are using.
If I do a doc.SelectSingleNode("listinfo","")
its not going to have much luck finding a <a:b> tag, but it will find a <foo:listinfo> tag so long as the namespace reference maps foo to the URI.
There always being a way and there always being a SECURE way are two very different things.
You can't claim to ask a security problem, and then get all worked up when you're given a security answer.
Here's the reality: IE will not only have the low-risk settings, it'll also be using the (oh god, I'm not even going to try and enter the acronym... suffice to say that all content that ISN'T from the machine gets effectively sandboxed using this API set, which was introduced in XP SP2), so not only will the browser be locked down, but ALL content that isn't from the machine'll be kept under lock and key as well.
That answer your question (kinda sorta)?
I'll need to go back and listen to the demo again (gnomedex one), because the second presenter actually covered this.
1. You right click save as in VirtualIE.
2. IE is modified to use a special function
SaveRealFile(filename,sourcesite,pointertofilecontents)
3. The virtual environment traps calls to that function.
4. It causes the standard save dialog to appear on the host OS.
"You are attempting to save a file from the Internet. Do you want to save {filename} from {sourcesite}"
5. The user chooses a location to save that file and the data is streamed out of the virtual environment and onto the host OS disk.
To the end user this is just as seamless as the present method.
However if the virtual browser is compromised, the exploit code could call SaveRealFile("onecoolapp.exe","trustedsitename",pointertoviruscode)
The user is then presented with an unexpected save dialog and may make a bad decision to save the file to the host OS and execute it.
Imagine this scenario.
To save a file to your real profile you would need to.
1. In virtual IE right click and choose save as..
2. Save the file to the disk of the virtual OS..
3. Open an explorer window on the host OS
4. Navigate to \\VirtualIE\SavedFiles\
5. Select and copy the file from there and paste it into "My Documents" on the host OS.
How many people would be able to handle that?
MSN desktop search is more of a limited subset of Longhorn's search features.
Ya i want a longhorn loves rss t-shirt too
Btw i'm keeping track of all the articles and pictures currently that i find on
my blog as well in
this article incase anyone missed some
Regards,
Shital.
being truly excited about developer possibilities with RSS integration
iCal on OSX has had a feature for years that lets you share your calender, or subscribe to someone elses. You can choose from thousands of business and social groups.
Maybe you just want to know that your chess club meeting next week has be moved to a different time.
You don't have to include all your details in your shared calender, only those that you want other people to know about.
Lots of people seem to like and use this feature,
Haha...I like people that say "Hey MS, don't copy, INNOVATE!. Look at Apple, they don't copy, it's just you who copies."
8-)
Suggest us, please, some "innovations" you'd like to see coming from MS!
Maybe for you MS products are not exciting but for me, from the developer's point of view, they are...
Have you considered Whidbey, Indigo, Avalon? This is what I call innovation.
OK, now I understand your opinions a bit better
EDIT: What is currently your "wow" feature?
Thats my major WOW feature for Longhorn: "WOW - I get all of those cool things in one box. And they will work hand in hand."
Despite all that as a user I really don't care who came up with what ideas first. If it works and does what I need, I use it. And it is most likely that the next OS by MS codenamed Longhorn will do what I need pretty well and most importantly - better than others.
Take this RSS idea, for example. I bet you a few billion $$ that it has way more enhancements than what we saw on the video presentation today. The only thing we can do now is laugh at the small guys and be anxious for these API's to be released.
My arms hurt.
Steve.
Exposed through managed code?
It's exposed through a documented set of API's. It shouldn't matter if it's managed or not.
Yes, it does matter. Want to know why? Because we want to see CODE!
I have to disagree. If that API is managed or not is crucial. And it wouldn't really make sense to make hat API an umanaged API. BTW: some of the demos shown in that video are said to be written in c# ....
I use FF and I have to admit that it's far better than current IE 6 but I'm also excited about IE 7; it won't get just RSS and tabs, there's gonna be much more in it (I hope
This is more than IE 7. If you think its just IE 7 you didnt watch the whole video. they are integrating RSS into the entire platform. It will be easier for developers and content creators to integrate RSS everywhere. I have heard that RSS will destroy traditional web browsing. I doubt it, it will be complimentary people have to search and find the content before they subscribe. Im a Netscape 8 user but I cant wait to see IE 7. I think Microsoft is doing some very interesting and innovative things with RSS including IE 7. I cant wait to see if IE7 RTM does indeed pass the Acid2 test. Im not expecting the betas to, but maybe we will be surprised. I dont like the new team name, "Longhorn Browsing and RSS", They should call it the "Windows Browsing and RSS" team
it's not that MSFT just got hip to RSS.
thats about the last thing they were telling you.
1) they will ship a set of classes and namespaces to make programming RSS simpler for windows. The goal is to make the basic plumbing "just work" for you and then you do not have to keep doing that part.
2) they see that enclosures are a good thing that can be used much more creativly than they are used today.
3) they are publishing a set of guidelines for how they think RSS can work with more enclosure types.
4) the windows classes will handle a whole slew of enclosures "out of the box" for you.
5) the publising of this work follows creative commons cause they want to "Play nice" with the rest of the RSS world.
ok, so they did not show us how to do warp speed or time travel but the things I just listed see very good to me....
I do understand that you feel the way you do. Allthough MS has been very open about the bowels of Longorn there is not yet too much thrilling to see from a plain user perspective. This antagonism paired with MJFism can lead to prejudices or to the kind of feeling that you have. One needs to keep in mind that longhorn is not even beta yet ( I know, it makes me sigh too ...)
Form the developer's perspective however there is already quite long list of promising and innovative technolgies and concepts publically known and ready to explore. Further as a developer I find it rather easy to imagine what could be implemented with them.
You read that MS ? That's what happens when you start milking the longhorn while it is still a calf.
All I know is, Longhorn users will have a lot of add on downloading to do between 2006 and 2008.
I'm all for playing well, but you have to simplify when transitioning it to the mass market.
Nobody would have to pay me to wear one of those shirts. They just look cool. How much would I need to pay to get one?
I think there's a difference, from a security standpoint, between calling code via interop and calling managed API's to the .NET Framework. I *KNOW* there's a big difference between the two methods from the PITA standpoint.
I agree 100%, I would love to have one of those shirts, I asked for one earlier.
The thats why they are building RSS into Longhorn at platform level so its exposed to every developer building applications on Longhorn. And I know that some of Groove Networks technology is going to tap into this for P2p scenarios.
P.S. That comment on The Centre de Pompidou was unforgivable, I've queued for two hours to get in and its a magnificent building. I'm glad that guy isn't on the Avalon team.
$mplayer -dumpstream mms://wm.microsoft.com/ms/msnse/0506/25055/RSS/rss_longhorn_platform_2005_MBR.wmv.
What you have to think about is the average home user in this situation. If they see that their OS (which is most likely going to be Windows) has a web browser built in (IE), they are probably going to use that instead of researching other broswers and spending time testing them all. As IE hasn't had features like RSS and tabs before, the average home user won't have had the chance to experience them. Now that Microsoft has taken the steps to change that, they are opening up a new world to that section of the public. It might not be revolutionary, but you have to say that at least they are willing to show average users modern advances.
However, from a developer's point of view, I totally agree with you. We access the information that shows us that there are browsers that are better. Yes, we are more concerned about standards compliance while the average user isn't. We know how important this can be to successfully render pages. This is one of the main things I would also like to see from new versions of IE. Standards are there for a reason.
What I'm saying is that IE do not have to innovate to improve their browser. Who says you have to innovate? Sure, I would like to see it, but it's not essential when creating a good browser.
This can/will have very far reaching impacts.....will be fun to watch it evolve out of the "blog" space and into the day to day lives of everyone...
Try this.
Avalanche is a research paper, nothing more. Drop the conspiracy theory and back away slowly, and no one will get hurt.
You know...I respect the guy for the great work he's done with BT, but he comes off as being quite rude and arrogant.
"First of all, I'd like to clarify that Avalanche is vaporware."
Vaporware? It's an MSR research project, not a product that's going to ship anytime soon.
"As you've probably figured out by now, I think that paper is complete garbage."
Again, this statement was completely uncalled for. Research communities often involve groups critiquing each other's work, and everything in that post before this line was all well and good. Calling it "garbage" goes a little over the top though. Constructive criticism is good, but that part of the post was just childish.*)
Yeah, I dont think there's any online community that whines as much as Slashdot.
Not sure how you would make it work...but for example, let's say I were at Gnomedex and subscribed to the schedule. I'd want to see a transparent version of the Gnomedex schedule on top of my personal schedule (the base)...instead of side-by-side.
Probably not an important feature, but it would have a lot of coolness factor.
Anyway, RSS support in the OS...exciting stuff.
Oh and Blogger hats? Isnt Blogger Google?
Multiple major original technologies get dropped from Longhorn (WinFS, Avalon, Indigo, Monad, even the whole .NET2 CLR) and Scoble say "it's OK, there's still great stuff in there, we just can't tell you about it yet". Then this comes out - Longhorn <hearts> RSS. A trivial (sorry, really simple) technology that essentially belongs in userspace and is already well served on existing versions of Windows and other OSes by many 3rd party packages and utilities.
This story should have disappeared without trace and I note that it more or less did in the mainstream media (even the mainstream IT media), but online and particularly among bloggers it runs and runs.
Mainstream if you count the tech press, which makes up the majority of those news items, as mainstream.
I'm not sure what that's supposed to prove except that online news sites are susceptible to press-release journalism. Even BBC News online which usually gives big coverage to anything involving Microsoft didn't make it a "picture story" on the Technology page.
But that's besides the point. My contention is that RSS is a "me too" technology. It's nice to have - maybe it's even important to have, but nobody is going to upgrade to Longhorn becuase it has some RSS support. If this is the big news about stuff that is making it into Longhorn then Microsoft is in big trouble.
All those technologies are developer APIs. And WinFX (Avalon, Indigo, and .NET 2.0) are certainly in there. I don't think anyone outside Microsoft knows what's going in Longhorn in terms of user features. You've heard them go on about a couple features in the shell like desktop search but Longhorn is about big sweeping changes and polish not tons of individual features (although there are many).
There are hundreds of teams inside Longhorn all working on new features or improving existing Windows components. You think when Longhorn comes out next year, all those developers were sitting idle for the past 5 years?
What ever happened to this idea that strongly typed datasets over web services would allow people to consume and use schemas (like WinFS). RSS is not a low level thing, nor is it object oriented. You call a URL and get a calendar back but what about paging, sorting, data integrity (strong typing with schemas[int,string,bool,etc.]), and security.
What about posting data? Our calendars are always read only? Our friends list is always read only? Or do we just go ahead and send an untyped RSS data structure back to some aspx page? This is the slop that I can't stand.
Peer to peer is great but peer to peer can also incorporate schemas to share not only the binary data but the types that are transported between the consumers and senders. There is so much potential out there with WinFS. Lets not get all side tracked with RSS and the fact that the community of non object oriented developers enjoy consuming "items" because they're so "easy". I think RSS is a great add on but to me, it's just another XML structure that allows people, that don't understand what strongly typed objects give you, to create user interfaces that just display data. Anyone can create a wrapper for windows media player
Another problem is the fact that outlook, Active Directory, Exchange server, WINS, DNS, and many other products run on old Microsoft Access databases. The APIs to these things are incomplete, antiquated, and very difficult to use. You also get data corruption from these things. Once WinFS is out, we'll see these critical windows services moving into SQL Server 2005 express or some ambiguous flavor that comes with the install of the application. Then we'll need a way to expose the schemas for these services and applications so that we can consume, send data, and communicate with the APIs.
I will be much more impressed when WinFS releases their library of schemas that work with all of the windows applications and later other languages start adopting XSD. Then you RSS monkeys can go and create all of your own classes in whatever language you want and I'll be over here autogenerating my classes and DataSets with prebuilt schemas. That's when we're off to the races folks!
T
C
Thank you
(Quote from video) "RSS came from blogs"
??
What? RSS was born from Netscape in an effort to broadcast news to it's users.
While I applaud the team adding support directly to Loghorn, no matter who you are, you should give credit where credit is due, even if it was your competitor (who later R.I.P'ed)
Some suggestions as to who would want to publish their calendar. Getting any of these automatically into a calendar would be obvious steps:
- NYSE, London/Tokyo Stock Exchange, etc, showing market holidays. From experience, it is a total pain having to enter by hand a list of holidays for stock exchanges in multiple countries (e.g. for NYSE holdays, not yet RSS);
- Governments listing pblic holidays (e.g. for US federal holidays, not yet RSS);
- Corporates listing their upcoming investor relations announcements. Investors and the media subscribe to companies' email lists, to get announcements. Some companies even RSS-enable their media releases. Taking it one step further, by putting the calendar into RSS would be the ultimate (e.g.);
- This would be a huge project, but you could even have share registries and stock exchanges putting key dates on RSS: e.g. ex-dividend dates, dividend pay dates, share tender dates, deadlines for AGM voting, and so on for all their companies.
So, both you and the team are correct.
How does this work if one have several machines?
I use NewsGator, because it aggregates to Outlook/Exchange, and if I read a RSS post on one machine then it is automatically marked as read on other machines.
With 30 RSS Feeds, one doesn't want to read the same think twice.
I'm not using a roaming profile, because my home PC is not part of my company’s domain.
If this is not supported, I think I'll stick with NewsGator.
Thomas
PS: 5 Program Manager for this job? Why is this so hard? Maybe they should learn about this think called .NET.
Orbit, the ‘other operating systems vs msft’ case has already happened, you know, back in the late 90’s.
see-
However I think it is important that the common store can easily be kept in sync with multiple machines. In fact the main reason I moved to Small Business Server for my home network was to keep outlook in sync between my main PC and Tablet.
However I feel that a sync feature for the RSS common store should be a built in from the beginning. Including the ability to sync your office and home machine, like in RSS Bandit, as well as a more continuous sync option, like you get with Outlook and Exchange.
First off, I definitely think podcasting is a fad. Unlike blogs, where you can get data from a thousand people in a day and make sense of it, podcasting requires real time to take in, and has far lower information density than a blog.
There's a temporary 'cool' factor to hearing the voices behind the words, or putting your words out there. However I believe that many people will only put up with shoddy production values in a text-based blog and now, in the early days of 'podcasts'. Eventually the 'marketplace of ears' will gravitate towards professionally qualified speakers, who will (and already do, from what I can see) dominate the podwaves. There's already an 'abandonment' issue with blogs, and I think that the abandonment rate for podcasts will be far, far higher.
Also, podcasting will never be the 'everyman' movement that blogs have the capability to be, and we shouldn't want it to be. There may indeed end up being more podcasts than there are radio stations, but the 'curve' of who gets listened to will be extra-sharp. This makes it a 'fad' in my eyes, at least.
(We shouldn't want podcasts to be the everyman movement, because it is nearly impossible to extract useful information out of them. A recorded talk show that talks about the decisions of the Supreme Court isn't searchable, indexable, hyperlinkable, or anything else that makes the web...well, the WEB.)
Anyway, I think Microsoft is doing some very cool things with their RSS support, despite my normal dislike for them. That said, I hope that Microsoft takes to heart the idea that this 'feed store' that they are creating should be able to be exposable to the network via an open protocol, that anyone can implement client or server for.
This way, I could kick back on my Mac, running NetNewsWire, and have my subscription feed be the same as when I'm sitting on my Windows box at home, or at work, running a Windows aggregator. I can subsribe from any box, and all my boxes know about it. You have the opportunity to fix the 'bookmark' problem now, before it happens all over again.
One extremely important place that this comes in, is in password-protected syndicated content. It's only a small subset now, but as pay-for site-subscription models and even subscribing to sensitive application data (like the log file aggregator mentioned at Gnomedex) become more popular, you really don't want to be putting those feeds someplace where the passwords are exposed.
Putting it all together, I actually think that Microsoft has the opportunity here to define (or work with the community to define) a good, not-Windows-specific feed storage and retrieval protocol, also opened up under a community-friendly license.
So.
Pipe dream?
-- Morgan Schweers
Interesting to see the IE7 integration - and subscribing to 'calendar' and all - just GREAT..
Acronym - there's another RSS that I've been working with - REPORTING SERVICES SCRIPT
Part of our dev project involves Reporting Services (RDL) - and have some script files to deploy - using 'rs.exe' - Report Server Script Host
And these script files are called RSS as well !!
Oh well - just another 'TLA'... ('Three Letter Acronym')
Well,
but are they allowing going multiple steps backward by a kind of drop-down menu. It doesn't interrest me if common users don't uses them - I have a very heavy use of it. Does the current model allow that? I can't see that from these screenshots.
The users who don't understand (I dont say "need" because that's not the truth) this behavior, are currently just ignoring that behavior. So I don't see the need - and discourage - to remove the drop-down menu functionality.
Greg Cobb
B.S. in Computer Engineering at the University of Texas
I started to download the file thinking that it would be PodCast sized and came back to discover that it was currently at 156MB and still going.
Lift your game guys!
In addition to IE7/Vista having RSS its one thing to have a constant supply of information, but quite another when dealing with the archiving and then easy access to those stories. Consider the best way of storing and searching for those news articles, online or locally? I prefer locally, which means saving the story’s picture and text in a Word file, manually.
Most news articles have an attractive point of reference, this being the little bit of eye candy which visually reproduces the topic of discussion. This often is a far easier point of reference to retain in unconscious memory, so when searching manually through pages and pages of old stories in bookmarks or online often a picture is the best source of reference compared to text.
How can an image be a story? Simple, it can be done today, but not with all image types, only those that allow for meta-data fields, luckily most images online are JPEG’s:
Find an online news article that has a JPEG picture, save this with the relevant file name of the article e.g. ‘Worlds Strongest Woman’ now in the properties/meta-data fields copy & paste the articles body text, then add some more info like category, author, date, URL and a title (if so desired , but not a necessity because of the files name)
Now the image contains the story, thus the story is the image, the catch is to make this a one-click process for the user. To do this an option in Vista /IE7 would allow the user to hover over a picture and select ‘Save Image as an Article’, the browser then automatically saves the image with the title of the story automatically adding meta-data such as:
Title - in the title field (same at file name)
Author of the article
Date in D/M/Y format specific to users region (refers to users computer) come on lets make this intelligent or have the date indisputably displayed as 27th July 2005
URL - for future reference
The story itself - naturally
Obviously the whole idea is that the browser (or whatever we will be using) will collect all the relevant data correctly every time with no mistakes, but I think some users would like more control, so (if configured) the browser would:
i) In a separate window, display a fit-to-page view of the article with sections highlighted to denote what will be collated into the picture, much like the print preview in IE but with boxes.
ii(a) The browser could use pointers or tags in the code to automatically denote what text to save into the specific image fields
ii(b) For a ‘dumb’ webpage then the whole article is boxed and highlighted in a segmented fashion with each text box user selectable, to be included or not
ii(c) The computer would learn what kind of stuff I like through my habits so I could eventually just trust it automatically, especially on regular sites where form past operations the pattern is obvious (a batch feature would be nice)
**Maybe in the options tab have a hi/low collation setting so ‘Low’ = not much info auto-selected, and ‘High’ = most of the pages text.**
Most article images online are in JPEG format. However to avoid the problems of images with no meta-data fields, thus scuppering the process and displaying “Sorry this file contains no room for meta-data, no-can-do”, provide the option when hovering over e.g. a GIF or BMP file to convert the file on the fly to a JPEG so the process could begin.
It would also be useful if the process validated weblinks, nothing like coming back to a story in a year’s time only to find the link added at the time was a dud.
A similar feature which would instantly create a Word document from articles that had no pictures, would work again based on the same principal by collating all the relevant information, this would be a god send - maybe insert the websites logo as a picture (but no adverts!!)
Once locally saved on the computer it would be interesting to see how the ‘image stories’ are manipulated by Vista. I would like to see Vista use the meta-data info effectively and behave according to what is in a files properties.
Not simply organising by date/time/author, add value to image files with their property fields filled by labelling them with a superimposed transparent corner strip to signify ‘it’s a story’ which separates it from ‘genuine’ images. Of course as this becomes commonplace the OS would not have to do this as meta-data becomes richer the OS would take it for granted.
1. Simple features like a menu appearing when highlighted - conjuring up options e.g. an option to visit the website or search for similar stories but more recent.
2. Search for articles of the same category by that author etc...
3. Add the stories to a portable device and use text to speech to dictate the story to me while I look at the picture or out the window
Now don’t tell me this wouldn’t be a better way of saving news stories rather than as hyperlinks, which get lost and are hard to navigate.
Samuel, UK
Not much useful knowledge on the blog.And the blog is leisurely to reveal, albeit interesting.
Remove this comment
Remove this threadclose
|
http://channel9.msdn.com/Blogs/TheChannel9Team/Longhorn-heart-RSS
|
CC-MAIN-2014-41
|
refinedweb
| 7,459
| 71.55
|
Given a sample code:
1 public class Test2 {
2 public static void main(String[] args) {
3 int i = 1;
4 Integer I = new Integer(i);
5 method(i);
6 method(I);
7 }
8 static void method(Integer I) {
9 System.out.print(" Wrapper");
10 }
11 static void method(int i) {
12 System.out.print(" Primitive");
}}
What will be the result of above code ?
(1) Primitive Wrapper
(2) Wrapper
(3) Primitive
(4) Wrapper Primitive
(1)
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
|
http://www.roseindia.net/tutorial/java/scjp/part7/question5.html
|
CC-MAIN-2013-20
|
refinedweb
| 110
| 59.64
|
Opened 5 years ago
Closed 5 years ago
Last modified 5 years ago
#10337 closed (invalid)
syncdb fails to load initial_data with certain __init__.py
Description
If the application's __init__.py contains
from django.contrib.auth import models
"manage.py syncdb" doesn't load the init_data fixture for this application.
import django.contrib.auth.models
doesn't cause this problem.
Attachments (0)
Change History (5)
comment:1 Changed 5 years ago by russellm
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Resolution set to worksforme
- Status changed from new to closed
comment:2 Changed 5 years ago by Alex
I can see why that would break something, but it's not something wrong with django, in python's import process when it sees from module import something the first place it checks is if that item exists in module/init.py, this isn't something Django could fix or work around or anything like that, it's just how python works.
comment:3 Changed 5 years ago by bronger
- Resolution worksforme deleted
- Status changed from closed to reopened
I can reproduce it with the following steps:
- django-admin.py startproject myproject
- ./manage.py startapp myapp
- Add a fixture called initial_data which e.g. simply adds a user in myapp/fixtures/
- set the database settings in settings.py and add "myproject.myapp" to INSTALLED_APPS
- create the database in the database backend
- call syncdb. The fixture is loaded.
- Add myapp/init.py with the above mentioned line
- drop&create the database in the database backend
- call syncdb. The fixture is not loaded.
As to what Alex said, sorry but I don't understand it. Be that as it may, I don't see why a high-level functionality like fixture loading depends on how a module is loaded. Currently it does, but it needn't.
comment:4 Changed 5 years ago by Alex
- Resolution set to invalid
- Status changed from reopened to closed
When python tries to import the models from your application so that it can instantiate them for the initial_data it's import includes the models path(obviously) however python import semantics say to look in the init of the app for the models name, therefore it can't ever find your applications models since it gets the models name from init which doesn't contain your models.
comment:5 Changed 5 years ago by bronger
Granted, but my application doesn't have models of its own anyway. myapp/models.py is deliberately empty. Instead, the fixture adds "User" instances from the auth module.
In other words, why does Django assume that a fixture only adds instances of the app's models? For example, User instances can be a very sensible thing to add.
I can't replicate this problem. I can't even think of a way that I _could_ replicate this problem - there isn't anything that should link the import method to initial_data fixtures.
If you can provide a complete set of instructions (or preferably, a full project definition) that demonstrates the problem, please reopen.
|
https://code.djangoproject.com/ticket/10337
|
CC-MAIN-2014-15
|
refinedweb
| 511
| 63.7
|
Reactive Extensions (Rx) for Python
Project description
A library for composing asynchronous and event-based programs using observable collections and query operator functions in Python
RxPY v3.0
For v1.X please go to the v1 branch.
RxPY v3.x runs on Python 3.6 or above. To install RxPY:
pip3 install rx
About ReactiveX
Reactive Extensions for Python (RxPY) is a set of libraries for composing asynchronous and event-based programs using observable sequences and pipable query operators in Python. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using operators, and parameterize concurrency in data/event streams using Schedulers.
import rx from rx import operators as ops source = rx.of("Alpha", "Beta", "Gamma", "Delta", "Epsilon") composed = source.pipe( ops.map(lambda s: len(s)), ops.filter(lambda i: i >= 5) ) composed.subscribe(lambda value: print("Received {0}".format(value)))
Learning RxPY
Read the documentation to learn the principles of RxPY and get the complete reference of the available operators.
I you need to migrate code from RxPY v1.x, read the migration section.
There is also a list of third party documentation available here.
Community
Join the conversation on Slack!
The gracious folks at PySlackers have given us a home in the #rxpy Slack channel. Please join us there for questions, conversations, and all things related to RxPy.
To join, navigate the page above to receive an email invite. After signing up, join us in the #rxpy channel.
Please follow the community guidelines and terms of service.
Differences from .NET and RxJS
RxPY is a fairly complete implementation of Rx with more than 120 operators, and over 1300 passing unit-tests. RxPY is mostly a direct port of RxJS, but also borrows a bit from RxNET and RxJava in terms of threading and blocking operators.
RxPY follows PEP 8, so all function and method names are lowercase with words separated by underscores as necessary to improve readability.
Thus .NET code such as:
var group = source.GroupBy(i => i % 3);
need to be written with an _ in Python:
group = source.pipe(ops.group_by(lambda i: i % 3))
With RxPY you should use named keyword arguments instead of positional arguments when an operator has multiple optional arguments. RxPY will not try to detect which arguments you are giving to the operator (or not).
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/Rx/
|
CC-MAIN-2019-43
|
refinedweb
| 415
| 50.33
|
Opened 3 years ago
Closed 3 years ago
Last modified 3 years ago
#27971 closed defect (fixed)
py3 failures in sage/misc/sageinspect.py and sagedoc.py
Description (last modified by )
The Python 3 doctest failures in
sage/misc/sageinspect.py and
sage/misc/sagedoc.py all arise because of the second line here (from
sageinspect.py):
spec = sage_getargspec(obj) s = str(inspect.formatargspec(*spec))
The problem is that
inspect.formatargspec is deprecated in Python 3.5, so it prints warning messages. From Sage's point of view, this is annoying, because there is no direct replacement (as far as I can tell) for
inspect.formatargspec. The documentation says to use
signature and
Signature, but we have already obtained the signature information using
sage_getargspec and just want to format it. Also,
inspect.signature doesn't seem to work on Cython functions — see cython issue 1864, or for a Sage-specific example:
sage: import inspect sage: from sage.misc.sageinspect import sage_getargspec sage: from sage.rings.integer import int_to_Z sage: sage_getargspec(int_to_Z) ArgSpec(args=['self', 'x'], varargs='args', keywords='kwds', defaults=None)
At this point, with Python 2:
sage: inspect.getargspec(long_to_Z) ... TypeError: <type 'sage.rings.integer.long_to_Z'> is not a Python function
With Python 3:
sage: inspect.signature(int_to_Z) ... ValueError: no signature found for builtin type <class 'sage.rings.integer.int_to_Z'>
Fixing this may also fix #27578.
Change History (17)
comment:1 Changed 3 years ago by
comment:2 Changed 3 years ago by
Reimplementing
formatargspec (needs doctests ...):
src/sage/misc/sageinspect.py
diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py index b7571b44f1..e46b9866ed 100644
comment:3 Changed 3 years ago by
comment:4 Changed 3 years ago by
As sage has it's own
getargspec i think reimplementing
formatargspec may be the best solution for now. That way sage would not be affected when
inspect.formatargspec will be removed.
Note:
sage_getargspec use
inspect.ArgSpec and i wonder if this class will be removed along with
inspect.formatargspec and
inspect.getargspec.
Maybe we should define our own
ArgSpec too.
comment:5 Changed 3 years ago by
I don't see anything indicating that
ArgSpec will be removed. In
inspect.py, it is defined by a one-liner:
ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
(well, two lines if you count
from collections import namedtuple). So it's trivial for us to implement if we need to.
Or we could switch to using
FullArgSpec, defined in
inspect.py by
FullArgSpec = namedtuple('FullArgSpec', 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
I don't think there is any urgency for either of these.
comment:6 Changed 3 years ago by
- Branch set to u/jhpalmieri/formatargspec
comment:7 Changed 3 years ago by
- Commit set to 56516cf95b775ffab3e6e85fd7c9c78ded927251
- Status changed from new to needs_review
Okay, here is an implementation of
formatargspec, taken directly from Python 3.7's
inspect module. This fixes the py3 doctests in sagedoc and sageinspect, and it also silences all of the deprecation warnings in docbuilding (both Python 2 and Python 3).
New commits:
comment:8 Changed 3 years ago by
It's so nice not to have that
formatargspec deprecation message from sphinx in my build logs anymore. Because there is so much of it you cannot even spot the interesting warnings you should be looking for like
[algebras ] <unknown>:1533: DeprecationWarning: invalid escape sequence \y [repl ] <unknown>:181: DeprecationWarning: invalid escape sequence \) [repl ] <unknown>:365: DeprecationWarning: invalid escape sequence \w
and a few others. Really the stuff of a new ticket but before this branch it was literally impossible to notice that stuff.
comment:9 Changed 3 years ago by
Yes, I noticed that, too. Definitely for a different ticket — the issues can be solved completely independently.
comment:10 Changed 3 years ago by
comment:11 Changed 3 years ago by
Ping?
comment:12 follow-up: ↓ 14 Changed 3 years ago by
- ``annotation`` -- blah What does
blah mean in this context ?
comment:13 Changed 3 years ago by
- Commit changed from 56516cf95b775ffab3e6e85fd7c9c78ded927251 to bbd5b28fc8e451bea4f87c2f2b0c27586386262a
Branch pushed to git repo; I updated commit sha1. This was a forced push. New commits:
comment:14 in reply to: ↑ 12 Changed 3 years ago by
comment:15 Changed 3 years ago by
- Reviewers set to Vincent Klein
- Status changed from needs_review to positive_review
Looks good to me.
comment:16 Changed 3 years ago by
- Branch changed from u/jhpalmieri/formatargspec to bbd5b28fc8e451bea4f87c2f2b0c27586386262a
- Resolution set to fixed
- Status changed from positive_review to closed
comment:17 Changed 3.
This silences the warnings:
src/sage/misc/sageinspect.py
|
https://trac.sagemath.org/ticket/27971?cversion=0&cnum_hist=2
|
CC-MAIN-2022-33
|
refinedweb
| 759
| 57.57
|
Ordered Set and GNU C++ PBDS
Hello everyone, in this C++ tutorial, we will be discussing Ordered Set and GNU C++ PBDS. PBDS stands for Policy-Based Data Structures. Policy-based data structures are not part of the standard C++ library. These data structures are supported by g++ compilers. The Ordered Set is a Policy-based data structure. It can perform all the set data structures operation in STL with two additional operations in log(n) complexity. These two operations are:
order_of_key(k): This returns the number of elements strictly smaller than k.
find_by_order(i): This returns an iterator to the i-th element where i starts from zero.
Both of these functions take O(logn) time. We will see the working of these two with an example program in this tutorial.
In order to use PBDS, we have to include the following in our code.
#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp>
We also need to add the following namespace in our code.
using namespace __gnu_pbds;
Let’s see the C++ program that demonstrated the ordered_set data structure.
#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <iostream> using namespace std; using namespace __gnu_pbds; typedef tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_set; int main() { ordered_set ord_set; ord_set.insert(2); ord_set.insert(4); ord_set.insert(6); ord_set.insert(8); cout << "size of the ordered_set is:\n"; cout << ord_set.size() << endl; cout << "Number of values less than 4 are:\n"; cout << ord_set.order_of_key(4) << endl; cout << "Number of values less than 7 are:\n"; cout << ord_set.order_of_key(7) << endl; cout << "Value at index 1:\n"; cout << *(ord_set.find_by_order(1)) << endl; cout << "Value at index 3:\n"; cout << *(ord_set.find_by_order(3)) << endl; return 0; }
Output:
size of the ordered_set is: 4 Number of values less than 4 are: 1 Number of values less than 7 are: 3 Value at index 1: 4 Value at index 3: 8
Instead of ordered_set, we can use any name in the above program for this data structure but since it is an extended version of set data structure, it is generally used and known as ordered_set in competitive programming.
Also read: Difference between GCC and G++ in C++
|
https://www.codespeedy.com/ordered-set-and-gnu-c-pbds/
|
CC-MAIN-2021-17
|
refinedweb
| 368
| 57.27
|
Content-type: text/html
#include <stdio.h>
char *ctermid(char *s);
char *ctermid_r(char *s);
The ctermid() function generates the path name of the controlling terminal for the current process and stores it in a string.
If s is a null pointer, the string is stored in an internal static area whose address is returned and whose contents are overwritten at the next call to ctermid(). Otherwise, s is assumed to point to a character array of at least L_ctermid elements. The path name is placed in this array and the value of s is returned. The constant L_ctermid is defined in the header <stdio.h>.
The ctermid_r() function behaves as ctermid() except that if s is a null pointer, the function returns NULL.
The difference between ctermid() and ttyname(3C) is that ttyname() must be passed a file descriptor and returns the actual name of the terminal associated with that file descriptor, while ctermid() returns a string (/dev/tty) that will refer to the terminal if used as a file name. The ttyname() function is useful only if the process already has at least one file open to a terminal.
The ctermid() function is unsafe in multithreaded applications. The ctermid_r() function is MT-Safe and should be used instead.
When compiling multithreaded applications, the _REENTRANT flag must be defined on the compile line. This flag should be used only with multithreaded applications.
See attributes(5) for descriptions of the following attributes:
ttyname(3C), attributes(5)
|
http://backdrift.org/man/SunOS-5.10/man3c/ctermid.3c.html
|
CC-MAIN-2017-04
|
refinedweb
| 246
| 62.98
|
APIs changed the way we build applications, there are countless examples of APIs in the world, and many ways to structure or set up your APIs. Today we will discuss how I use Python and Flask to build and document REST APIs that scale to every need.
As usual, I’m providing sample applications, for this case a starter kit for everyone to use and build upon, here is the link to the final code we will review today.
Before we start with code…
Let’s first discuss the project dependencies, why each of them is necessary and how it can benefit our project.
- flask:Flask is a micro web framework which has a minimal footprint compared to others like django, and allows us to select which components and modules we want to integrate with it. Flask is highly reliable and performant.
- flasgger:It’s a module that helps us integrate swagger docs to a flask API.
- flask-marshmallow:Object serializer, ideal for parsing and dumping JSON data in and out of our API.
- apispec:Required for the integration between marshmallow and flasgger.
Project Layout
We will start discussing how the project layout looks like by taking a look into the folder structure:
project/ api/ model/ __init__.py welcome.py route/ home.py schema/ __init__.py welcome.py test/ route/ __init__.py test_home.py __init.py .gitignore app.py Pipfile Pipfile.lock
I think that the folder structure is self-explanatory, but let’s look at it part by partAPI Module
The API module will host our application code, from models, routes, schemas and controllers if needed (though I usually don’t create those).
- The
modelsare the data descriptor of our application, in many cases related to the database model, for example when using
sqlalchemy, though they can be any class which represents the structure of our data.
- The
routesare the paths to our application (e.g. /api/home or /api/users) and it’s where we will define the route logic, data retrieval, insertion, updates, etc.
- The
schemasare the views (serializers) for our data structures. We should have at least one schema per model. The schemas will have it’s own definition as we will see later.
Route example
home.py
from http import HTTPStatus from flask import Blueprint from flasgger import swag_from from api.model.welcome import WelcomeModel from api.schema.welcome import WelcomeSchema home_api = Blueprint('api', __name__ ) @home_api.route('/') @swag_from({ 'responses': { HTTPStatus.OK.value: { 'description': 'Welcome to the Flask Starter Kit', 'schema': WelcomeSchema } } }) def welcome(): """ 1 liner about the route A more detailed description of the endpoint --- """ result = WelcomeModel() return WelcomeSchema().dump(result), 200
This is an example of the most basic definition for a route, let’s take a look into it line by line:
home_api = Blueprint('api', __name__ )
Blueprint creation, I like to separate the application in different blueprints, where I provide at the beginning of the file the parent route, in this case
/api and all the subsequent routes will be relative to this one.
@home_api.route('/') @swag_from({ 'responses': { HTTPStatus.OK.value: { 'description': 'Welcome to the Flask Starter Kit', 'schema': WelcomeSchema } } }) def welcome(): """ 1 liner about the route A more detailed description of the endpoint --- """ result = WelcomeModel() return WelcomeSchema().dump(result), 200
Next is the route itself, in this case we first define the route for the application, there are several ways to do this, and they are very well covered in the flask docs.Right after the route definition we need to provide information for the swagger documentation. I’ve set an example where we define the response object, and the endpoint description as string literals, but there’s more you can do if you follow the official documentation.
Then we need to place the code for our application, to eventually return an object from the API. To serialize the object we use our schemas as can be seen on the code.
Schemas
The schemas are a very important part of this setup, and they are covered in detail in the flask-marshmallow documentation, but in essence a schema is a class that defines the properties and relationships among models and others in so that python can serialize the objects.
Here are some sample schemas from my blockchain code.
from flask_marshmallow import Schema from marshmallow.fields import Nested, Str, Number from api.schema.transaction import TransactionSchema class BlockSchema(Schema): class Meta: # Fields to expose fields = ["index", "timestamp", "transactions", "nonce", "previous_hash", "hash"] index = Number() nonce = Str() timestamp = Number() previous_hash = Str() hash = Str() transactions = Nested(TransactionSchema, many=True) from flask_marshmallow import Schema from marshmallow.fields import Nested from api.schema.block import BlockSchema class BlockchainSchema(Schema): class Meta: # Fields to expose fields = ["blockchain"] blockchain = Nested(BlockSchema, many=True)
Tests
As with any other application, tests are super important, and I could have an entire post discussing why. But here we will keep it simple. For tests I’m simply using unittest module from python, and I try to build tests for each component. Here is an example for our home route:
from unittest import TestCase from app import create_app class TestWelcome(TestCase): def setUp(self): self.app = create_app().test_client() def test_welcome(self): """ Tests the route screen message """ rv = self.app.get('/api/') # If we recalculate the hash on the block we should get the same result as we have stored self.assertEqual({"message": 'Hello World!'}, rv.get_json())
Application
Finally, we need the place where we glue it all together, and we create our python API
from flask import Flask from flasgger import Swagger from api.route.home import home_api def create_app(): app = Flask( __name__ ) app.config['SWAGGER'] = { 'title': 'Flask API Starter Kit', } swagger = Swagger(app) app.register_blueprint(home_api, url_prefix='/api') return app if __name__ == ' __main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on') args = parser.parse_args() port = args.port app = create_app() app.run(host='0.0.0.0', port=port)
In the file app.py we define the python flask application. Inside the
create_app function you would need to specify your app name for the swagger configuration, each one of your blueprints, any other initialization step such as the db connection, all that would happen here, and there are good examples in the flask quick starter.
Environment Set Up
Install requirements
pipenv install
Start the server with:
pipenv run python -m flask run
Run tests:
pipenv run python -m unittest
Visit for the home api
Visit for the swagger documentation
I hope this tutorial and project help you build your next API and as usual please let me know if you have any other ideas on twitter at @livecodestream, or simply create an issue, or a PR on the github project.
Thanks for reading!
Discussion (0)
|
https://dev.to/livecodestream/python-flask-api-starter-kit-and-project-layout-ehk
|
CC-MAIN-2021-43
|
refinedweb
| 1,122
| 62.58
|
Sinorca-Design
Download the files of this theme here: ThemeMarket/sinorca4moin
Please have a look at HelpOnThemes for installation questions etc. before asking questions here.
This theme is (also) used by the SciPy-Wiki - so you can have a more detailed look at the theme there.
The newer versions (>0.4) of the design work out of the box for farms and for single wikis. The headers can be customized as can be seen in the following screenshots (see below for more info):
- Many of the suggestions posted here for version 0.3 have been integrated in 0.4. Thanks for the feedback!
- The middle header shows the logo (if configured) and the sitename (as given in the config). Both items link to the frontpage of that wiki. The best height for the logo is 46px.
Add logo_string = u'' to your config if you don't want a logo. If you forget that the name of the wiki will be shown twice.
The contents in the superheader are determined by the config variable page_header1:
- If it is empty (default of moin), the userform-data will be shown on the right.
If it is not empty, the contents of page_header1 will be shown. E.g. add the following to your farmconfig (you may use the classes left / right to position the elements in the superheader):
page_header1 = '\n'.join([ u'<div class="left">', u' <a href="">Leibniz-Institute for Catalysis</a>', u'</div>', u'<div class="right">', u' <a href="">Python Homepage</a> |', u' <a href="">Google</a>', u'</div>', ])
- The subheader contains different contents for a farm or a single wiki:
Single-Wiki:
subheader: The content specified in the config variable page_header2 is displayed, e.g. add the following to your wikiconfig:
page_header2 = '\n'.join([ u'<a href="">Python Homepage</a> |', u'<a href="">Google</a>', ])
Wiki-Farm:
An auto-created list of links to the respective frontpage of the wikis in the farm and their RecentChanges pages (diff-icon) is shown; the list is created from the tuples of the list wikis in your farmconfig.py-file. If you use the config-variable interwiki_preferred, this list of wikis is used to build the subheader (this is useful for large farms). If the active wiki is in the list, it's name will be highlighted in orange.
If you (or your users) want to be more happy with IE 6.0 / IE 7.0 you may want to change the tablewidth in RecentChanges to 99%. Otherwise the table is always displayed below the sidebar. Also if the window is too small the RecentChanges table drops below the sidebar.
The design was originally insprired by the Sinorca design from "haran" published at.
Changes
For Rel. 0.1 --> Rel. 0.2:
- Improved compatibility with IE 6
- Fixed several minor formatting problems
For Rel. 0.2 --> Rel. 0.3:
- Theme produces now valid HTML pages.
For Rel. 0.3 --> Rel. 0.4:
- Now compatible with moin-1.5.4
- Better support for single wikis
- Autogenerated subheader for farms
- Nicer design of sidebar, info msg etc.
- Several minor fixes of css bugs
For Rel. 0.4 --> Rel. 0.4.1:
- Corrected margin for #message
- Fixed IE-specific problem with left margin for Text-Editor area (GUI-Editor was OK)
For Rel. 0.4.1 --> Rel. 0.4.2:
Theme is now compatible with standard DesktopEdition (1.5.4.1)
- Missing interwikiname and some other possible miss-configurations are tolerated now.
For Rel. 0.4.2 --> Rel. 0.4.3:
- Added title method to sinorca 4moin to improve dsiplay of page title for subpages with IE.
- Fixed (config-dependant) problem with generation of linklist to subwikis of the farm.
For Rel. 0.4.3 --> Rel. 0.4.4 (2006-08-30):
- sinorca4moin.py does no longer raise config.error for links missing in the interwiki-list
- css-changes to display fontsize of table correctly in GUI editor on Mozilla, Firefox and IE6
- Added new method to sinorca4moin.py for constructing better short names for hierarchical page names.
For Rel. 0.4.4 --> Rel. 0.4.5 (2006-12-17):
- Fixed IE7-specific problem where the preview area was partly hidden by the edit-field.
sinorca4moin.py now overrides the default splitNavilink-method to solve MoinMoinBugs/NavibarDoesNotShortenPagenamesForQuicklinks in the theme.
- Show edit-icon only if user is allowed to edit the page.
- Added icons for links (like the globe for urls).
For Rel. 0.4.5 --> Rel. 0.4.6 (2006-12-27):
- Last version that is compatible with moin-1.5.x
Moved all MS IE specific hacks to separate file msie.css
Probably some minor changes...
For Rel. 0.4.6 --> Rel. 0.5 (2006-12-29):
- First version for moin-1.6
Tests mad for different moin-1.6.0 wikis: a farm, a single wiki, DesktopEdition
Issues / Comments / Suggestions
Old stuff related to version 0.3 was deleted. Look in page history if you still need it (revision 30)!
With moinmoin 1.9.2-2, python 2.6.5, using sinorca4moin theme breaks config. If user in preferences changes to sinorca4moin, or in wiki config there is theme_default = 'sinorca4moin', I get on my browser: 'data_dir "data" does not exist, or has incorrect ownership or permissions.'. data_dir is on farmconfig given with full, absolute path, and that setting is lost if I use sinorca4moin. Tried v0.5b and version available on Wiki's config available on
REQUEST: sinorca4moin is a terrific theme and I'd like to use it again. However, it doesn't seem to be compatible with MoinMoin 1.6 because of internal changes to the MoinMoin object model (I think). I hope an upgrade to 1.6 compatibility is on its way. Thanks!!!
Thanks for the compliments on the theme. Once there is an official stable release of moin 1.6 (or 1.7?) I will adjust sinorca4moin. I don't have enough time to keep sinorca4moin compatible with the development versions. -- DavidLinke 2007-06-27 20:36:15
Addendum to REQUEST above: I think I fixed it myself. I made the following changes in sinorca4moin.py (again, for MoinMoin 1.6a only):
- Replace the string "d['title_link']" with "d['title_text'] -- I don't know why, but this resolves an error.
Replace the string "from MoinMoin.multiconfig import" to "from MoinMoin.config.multiconfig import" . In other words, there's evidently an object model revision that makes the "multiconfig" object a subclass of a new(?) "config" object that wasn't there before.
Replace the string "page = wikiutil.getSysPage(request, text)" with the string "page = wikiutil.getLocalizedPage(request, text)". This resolves another runtime error when the theme is put into a MoinMoin 1.6 wiki.
there is also an error if you're using farmwikis: Config instance has no attribute '_interwiki_list' . So the following code need to be updated wiki_url = self.request.cfg._interwiki_list[cfg.interwikiname] . well maybe someone could help; due I'm not a realy python-coder. -- MarcelHäfner 2007-12-29 12:55:39
Better use the new version of the theme that is adjusted for moin-1.6. -- DavidLinke 2007-12-29 22:13:50
Addendum to ADDENDUM above: current stable release is MoinMoin-1.7.2 - is there a 1.7.x compatible version of Sinorca? Great theme.
- Long pagenames in the left container just get truncated at the right. Maybe use similar code as we use in trail to render them shorter. If mouse is over those pagenames, it looks strange.
Sinorca4moin now (in Rel. 0.4.4) overrides the default shortenPagename-Method for nicer short names. A bug in moin has to be fixed too to make this fully work (MoinMoinBugs/NavibarDoesNotShortenPagenamesForQuicklinks).
- I like this theme very much with one exception. I'd like the have a larger space between paragraphs and before and after images. I've been forcing it by putting in breaks, but it isn't ideal. Any suggestions on what to adjust to allow more space?
- Change the margin in lines 238-241 of screen.css to a higher value
238 #page p { 239 margin: 0 0 0.25em 0;
- Perfect! Thanks very much. One issue I have trying to tweak things is that I'm not fluent in HTML and I don't find the themes I've looked at provide many comments as to what each section does and how one might tweak them. Thanks.. Eric
- I don't want to be a bother, so feel free to ignore this request if you want. I'm trying to edit the default table settings to look more like the wikitable class used in wikipedia. I'm editing the common.css file. I've managed to change the overall table color and borders, but can't get the heading text (th) to center or bold. Also the height of each cell it too great and editing the padding and margin doesn't seem to help. Any hints how to proceed?
Compared to the modern theme, Sinorca4Moin on my wiki has much more padding in table cells. Where in the CSS is this controlled? I've tried everything obvious to me. Thanks.
You may try something like Web Developer (similar tools are available for Firefox or IE) to find out which part of css is responsible for the element. Is's the "td" section in common.css you are looking for.
Found the problem. It was in screen.css around line 238 where # page p is defined. Changed the margin here and it now looks fine. I really like this theme, but it is frustrating trying to figure out exactly where changes need to be made. I've been playing with DokuWiki and one of their their themes (monobook) has a nice approach where there is a separate user.css file which can be used to override the theme css without editing the theme's css. This makes upgrading a theme much easier. Eric
What is farmconfig.wiki-dictionary, and how I add my wikis to it to make links on subheader?
See "Configuration of multiple wikis" on page HelpOnConfiguration.
string farmconfig.wiki is only found on this page with moinmoin search or google , and HelpOnConfiguration doesn't contain that, or word 'dictionary'. I know how to config wiki farm, but don't know how to make sinorca4moin to display links to other wikis in farm. Please provide more accurate instructions how to do it.
In your farmconfig.py file should be a list (not a dictionary, sorry) with tuples of (wikiname, url regular expression). Sinorca4moin picks up the data from there to display the list of wikis (except if interwiki_preferred is used as described above). If you have a farm working with the standard theme, sinorca4moin should just work without additional modifications. Note, that I haven't yet tested the theme with the new 1.6 version but only with 1.5.x.
- Was trying to add a comment, but the comment link is not working... hence adding in here. Found an issue with the left nav menu in firefox (ver 2), the menu had a padding almost to half of the page there by pushing the content of the page to teh right side. I could resolve it by changing screen.css, adding to #sidebar to additional style attributes - position: absolute; left: 0px
Thanks for the problem report. Could you tell which wiki-page showed the problem? I am using Firefox as standard browser but have not yet observed this behavior. Thanks! -- DavidLinke
Hi David! I made some small updates and changes to your greate theme and updated the ThemeMarket/sinorca4moin page. I'm a bit unsure about your licence... even if it's ok that I uploaded my changes... maybe it would be easier to put your theme under some gpl v2 like license. if my changes are a problem, I will deleted it, just let me know, thx! bye -- MarcelHäfner 2008-12-09 21:44:39
Hi Marcel, thank you very much for your work on updating the theme. I am OK with gpl v2 (since moin-code was partly reused this seems to be the right license). I hope to have some time in the next weeks to create a new version based on your input. -- DavidLinke 2008-12-09 22:32:30
moin is "GPV v2 or later" licensed. David, please check and speak up in case you are not OK with using exactly same license declaration as in moin" (e.g. if you didn't want the "or later" part). -- ThomasWaldmann 2009-10-06 15:50:55
I am fine with "GPV v2 or later". -- DavidLinke 2009-10-06 19:23:31
Hi David, I am using Sinorca4moin 0.4.6 with MoinMoin 1.5.3. I love your theme, but unfortunately under IE 6 and 7 a weird left margin for the text-editor area shows up on all wiki pages. Although I know this is due to a CSS bug of IEs and I personally don't use IE, I would like to fix it for my colleagues' convenience. I figured out that this is caused by IE's inherited margin bug. The textarea is inheriting the margin from the outer div element which has a left margin of 215px. Therefore it is actually doubly displaced by 215+215 = 430px. I tested and confirmed that giving the textarea a negative left margin of -215px sorts out this layout problem for sure. So I added the corresponding code to "msie.css". However it doesn't seem to be taking any effect on wiki pages. Also I couldn't find any code making use of this "msie.css" file. So could you please let me know how to use this "msie.css" or otherwise how to apply a conditional style for IEs in your theme. Thanks! -- HirokiTakahashi
Please read SecurityFixes and upgrade to a much more recent version
-- ReimarBauer 2010-06-02 23:23:00
Iconbar not working anymore
Today I uptated my moinmoin with the latest changes in 1.6 (f5e7da98f2ae from Sun Apr 27 14:36:07 2008) and received for your theme the following error:
'NoneType' object has no attribute 'link_to_raw' * args = ("'NoneType' object has no attribute 'link_to_raw'",)
Well, the latest update/change in theme/__ini__.py file (see hg.moinmo.in) will break the current def IconBar on this theme. If you change it to the same as used in classic theme, then everything seems to be ok.
def iconbar(self, d): """ Assemble the iconbar @param d: parameter dictionary @rtype: string @return: iconbar html """ iconbar = [] if self.cfg.page_iconbar and self.request.user.show_toolbar and d['page_name']: iconbar.append('<ul id="iconbar">\n') icons = self.cfg.page_iconbar[:] for icon in icons: if icon == "up": if d['page_parent_page']: iconbar.append('<li>%s</li>\n' % self.make_iconlink(icon, d)) elif icon == "subscribe" and self.cfg.mail_enabled: iconbar.append('<li>%s</li>\n' % self.make_iconlink( ["subscribe", "unsubscribe"][self.request.user.isSubscribedTo([d['page_name']])], d)) else: iconbar.append('<li>%s</li>\n' % self.make_iconlink(icon, d)) iconbar.append('</ul>\n') return ''.join(iconbar)
hope it helps; bye -- MarcelHäfner 2008-05-05 19:45:23
CSS Issue with IE7
Hi there; I saw that the IE7 always display on the bottom of the page a vertical scrollbar. To remove this stupid behavior of IEX, you just need make the pageinfo a bit smaller. bye -- MarcelHäfner 2008-05-09 15:05:55
adding to the msie.css file:
p#pageinfo { width: 99%; text-align: right; }
|
http://www.moinmo.in/DavidLinke/Sinorca4Moin
|
crawl-003
|
refinedweb
| 2,576
| 67.55
|
So I am kinda new to java and was given a program to do.
a. Create one or more arrays to hold the names of the months and the number of days in each month. Assume that February always has 28 days.
b. Display the contents of the array(s).
c. Ask the user for a number to represent the month: 1 = Jan, 2 = Feb, etc. Search for the corresponding month and display the name of the month and the number of days. If the number is not found, display an error message.
d. Ask the user for the name of a month. Search for the corresponding month and display the number of the month and the number of days. If the month is not found, display an error message.
I have done a-c but i am having trouble with d.
package array;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int [] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Array holds number of days in month
String [] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; // array holds months
for (int index = 0; index < months.length; index++) // loop to display number of days in month
{
System.out.println(months[index] + " has " + // displays number of days in month
days[index] + " days ");
}
Scanner keyboard = new Scanner(System.in); // creates scanner
System.out.println("Enter a number to represent the month");
int search = keyboard.nextInt(); // saves user value into search
search--; // subtracts 1 from user input to account for the index of 0
if(search > months.length)
System.out.println("Can not find number"); // yes if search is more then months display error
else
System.out.println( months[search] + " has " + days[search] + " days "); // no if search is less then months display contents
Scanner string = new Scanner(System.in); //creates new scanner
System.out.println("Enter the name of the month");
String input = string.nextLine(); // saves user strin in to input
for (int index = 0; index < months.length; index++) //loop to compare user input to months array
{
if(input.equals(months[index])) // yes display month and days
System.out.println(months[index] + " has " + // displays number of days in month
days[index] + " days ");
else
if(!(input.equals(months[index]))) // no display error
System.out.println("can not find month");
}
}
}
Its kinda hard to explain the problem but if you run it you will see when it asks the user to input the name of the month that is where the error occurs. Any help would be appreciated.
|
http://www.javaprogrammingforums.com/whats-wrong-my-code/9268-need-help-array.html
|
CC-MAIN-2015-18
|
refinedweb
| 428
| 66.64
|
..
Recall that a mutex is a lock that only one thread can “hold” at any given time. If a thread tries to acquire the lock while another thread “holds” it, that thread will be blocked until the lock is released. This mechanism is quite helpful when you want only one thread executing certain code at a given time (for example, when a common variable’s value is read and then written).
However, imagine a situation where you have multiple resources that are being used concurrently. This occurs all the time: ten cashiers at Fry’s Electronics, five copiers at Kinko’s, three servers at Ben and Jerry’s and so on. In each of these cases, customers “compete” for the resources available, and whenever all the resources are busy, the remaining unserved customers must wait.
You may be wondering how these examples relate to programming. It’s true that you are unlikely to write a computer program that tells people standing in line that they cannot be served until a cashier, copier, or ice-cream server is ready to serve them.
However, picture a “virtual” line, like when you call a ticket agent to buy a plane ticket. If all the ticket agents are serving other customers when you call, you will be put on hold until “the next available ticket agent” can take your call. Somehow, the resources (ticket agents) must be distributed to the consumers (you and anyone else who wishes to fly) in such a way that all ticket agents are taking calls and no ticket agent is assigned more than one customer at a time.
If you try to solve this problem using only mutexes, you will probably have great difficulty. Luckily for us, there are better ways to solve this type of problem.
Introducing Semaphores
A “semaphore” is a counter that can be used to keep track of resources in threaded applications. It basically represents a non-negative value that can be signaled or waited on. If a thread signals a semaphore, the value of the semaphore increases by one. If a thread waits on a semaphore, two things can happen. If the value of the semaphore is greater than zero, that value is decreased by one, and the call to wait returns. However, if the value of the semaphore is zero, the thread that waited on it is blocked until the value is greater than zero. The value of the semaphore can be thought of as the number of unused resources. When this number reaches zero, a thread that wishes to use a resource must wait until one is available.
To create a semaphore in your threaded program, simply call the function sem_init(). Its prototype, as listed in <semaphore.h>, is:
int sem_init (sem_t* sem, int pshared, unsigned int value);
All semaphore functions return zero on success and non-zero on failure. See the manual page for more information on error codes that can be returned. This function takes in a sem_t as the first argument. This is the semaphore to be initialized. Normally you would declare the semaphore statically and then pass the address of the variable to this function for initialization. The second argument, pshared, should always be zero when programming in Linux. It is for semaphores that can be shared across processes — a feature not supported in Linux. The last argument, value, is the initial value of the semaphore. So, for example, if you had five ticket agents and a semaphore to represent them, you would initialize it with a call like:
#define NUM_AGENTS 5
sem_t agent_semaphore;
sem_init (&agent_semaphore, 0, NUM_AGENTS);
To signal the semaphore, you call sem_post():
int sem_post (sem_t* sem);
This will increase the value of the semaphore by one. To wait on the semaphore, you call sem_wait():
int sem_wait (sem_t* sem);
This will return immediately if the value of the semaphore is greater than zero and block the thread otherwise.
Condition Variables
Sometimes semaphores do not conceptually represent all the types of synchronization you might want to use when programming with threads. For an example, we’ll again turn to the ticket agency. Once the agency has successfully sold the total number of tickets available, someone might have the job of closing the books concerning the venue, changing the status of the venue to “Sold Out,” etc. However, we only want this bookkeeping to occur when all of the tickets are sold. Although we could use a semaphore to do this, it would be clearer conceptually if we had a way to tie the condition (total sold = total available) to a lock that will only wake a thread when this is true. To do this, Linux provides “condition variables,” or “conditions” for short.
A condition variable is tied to a mutex and can be used to block multiple threads until another thread signals the condition. This then wakes all the threads that were waiting on it. Whenever you want to use a condition variable, you must have a mutex for the condition. Unlike semaphores, condition variables have no memory. When one thread signals the condition, the threads that are currently waiting on it are woken up immediately. Any thread that isn’t waiting on it does not receive the signal. By tying a mutex to the condition, you can insure that a race condition does not occur between the thread waiting on the condition and the thread signaling the condition. (Again, see last month’s column if you want to brush up on race conditions.)
The functions to initialize condition variables (as defined in <pthread.h>) are as follows:
int pthread_cond_init
(pthread_cond_t* cond,
pthread_condattr_t*
cond_attr);
Alternately, you may use the static initializer like this:
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
to get the default attributes for the condition. To wait on a condition, simply call the wait function:
int pthread_cond_wait
(pthread_cond_t*cond,
pthread_mutex_t*mutex);
Note, as I described above, that each condition variable must be used with a mutex. You must acquire the mutex (with the pthread_mutex_lock() function) before calling pthread_cond_wait(). To signal a single thread that is waiting on the condition, use the following signal function:
int pthread_cond_signal
(pthread_cond_t* cond);
This will wake a waiting thread at random and allow it to continue execution. Note that there is no way to control which thread is woken up, so the function you wish to use instead of pthread_cond_ signal() is often the broadcast function:
intpthread_cond_broadcast
(pthread_cond_t* cond);
This function wakes up all threads that are currently waiting on the condition and allows them to continue execution. As is true with the other thread functions, these all return zero on success and non-zero on failure. Make sure to see the manual page for information about failure codes for these functions.
The Ticket Agency Again
Let’s now look at a complete version of the ticket agency example we’ve been using, employing all the techniques we’ve described so far. Using locks, semaphores and condition variables, we will construct a program that can: 1) handle callers and distribute them to ticket agents without allocating two callers to any agent simultaneously; 2) have all ticket agents responding to calls when there are customers waiting to buy tickets; 3) assure that only the total number of tickets available are sold; 4) notify a bookkeeper that will perform certain actions once all the tickets are sold (and not before). Of course, this program will only be the framework (i.e., the synchronization techniques necessary to make sure each of the parts cooperate as desired).
First, let’s start with the callers. The rule for callers is simple to state and splits into two cases. Case 1: If there is at least one ticket agent available when a call comes in, the call should be answered immediately by a ticket agent. Case 2: If there are no ticket agents available when a call comes in, the caller will be placed on hold until a ticket agent is available.
To code this, we will assume that we have a queue data structure with functions to place an integer on a queue and to remove the first integer put on the queue (the functions queue_add() and queue_remove() respectively). Thus, we will simply keep a queue of callers. These callers will be our “resource” in the synchronization sense of the word, and the ticket agents will be the consumer of the resources (callers). Therefore, we will have a semaphore to keep track of the number of callers who are waiting to be helped. This will ensure that two ticket agents don’t attempt to help the same customer.
By using a mutex for the queue of callers, we can verify that when two customers are waiting on one of two agents to help them, each customer will be helped. We will use another semaphore for the communication from the agent to the line signifying that the call is over and should be hung up. Each line will have a semaphore that it will wait on once it queues the caller. The agent that takes that call will signal the corresponding semaphore when the call is over before taking another call.
To handle bookkeeping after all the tickets have been sold, we simply use a condition variable on the condition (total_sold < NUM_TICKETS). While this is true, the bookkeeper just waits. We could just as easily have used a while() loop with no body, but this would take a lot of processor time constantly executing the instructions necessary to test the condition. For now, let’s look at the code in Listing One (pg. 68).
The code in Listing One is a demonstration of the synchronization features described in this and last month’s articles. It is a program that is probably similar to those used when you are on hold waiting for tech support or to buy airline tickets. After studying this code, other possible solutions for this specific problem will probably occur to you. For example, we could use a semaphore for the bookkeeper instead of a condition variable.
As I alluded earlier, in general, a semaphore can be used to achieve the same functionality as a condition variable. In fact, simple mutexes can be used to mimic the behavior of semaphores and condition variables (and vice versa). Given any one of the synchronization techniques I’ve described so far, you can build any of the others. These different mechanisms exist to allow programmers to use the method of synchronization best suited for the problem at hand.
The Right Tool For the Right Job
Semaphores and condition variables are two more tools you can use to synchronize your threaded applications. It’s important to pick the correct tool when writing your programs, not only to make it easier for you to write, but also to aid those who will later need to read and understand your code. Hopefully, by this time, you’ve got a pretty good sense of the options available (and when to use specific options) for writing threaded code.
Enjoy experimenting with concurrent programming, and as always, happy hacking!
Listing One: ticket_agent () with Semaphores and Conditions
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <semaphore.h>
#define NUM_TICKETS 100
#define NUM_AGENTS 5
#define NUM_LINES 10
int total_sold = 0;
pthread_mutex_t tickets_sold_lock = PTHREAD_MUTEX_INITIALIZER;
queue line_of_callers;
/* A lock for the queue of callers. */
pthread_mutex_t line_lock = PTHREAD_MUTEX_INITIALIZER;
/* Semaphore representing the current number of callers in line. */
sem_t num_in_line;
/*Semaphores for communication from agents to phone lines to indicate
when a call is finished. Basically used for the agent to tell
the line to “hang up” the call. */
sem_t lines[NUM_LINES];
/* Mutex and condition variable for the bookkeeper to use to
wait for all the tickets to be sold. */
pthread_mutex_t finish_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t finish_cond = PTHREAD_COND_INITIALIZER;
void* call_line (void* data)
{
/* An identifier for which line this is */
int my_num = *((int*)data);
while (1)
{
/* Dummy function that simulates waiting for this line
to ring. */
wait_for_caller ();
/* Get the lock for the line to make sure two call lines
don’t add a caller to the line at the same time. */
pthread_mutex_lock (&line_lock);
queue_add (line_of_callers, my_num);
pthread_mutex_unlock (&line_lock);
/* Signal the semaphore for the total number of callers in
line so that one of the agents will pick up. */
sem_post (&num_in_line);
/* Wait on the signal from the ticket agent so that we know
that the call has been handled and can therefore
handle another call on this line. */
sem_wait (&lines[my_num]);
}
return NULL;
}
void* ticket_agent (void* foo)
{
int currently_helping;
while (1)
{
/* Wait until there is a caller in the line. */
sem_wait (&num_in_line);
/* Get the lock for the line and take the first caller
in line off of the list.*/
pthread_mutex_lock (&line_lock);
currently_helping = queue_remove (line_of_callers);
pthread_mutex_unlock (&line_lock);
printf(”Helping caller on line %d.n”, currently_helping);
pthread_mutex_lock (&tickets_sold_lock);
if (total_sold < NUM_TICKETS)
{
/* If we still have tickets left, sell the ticket
to the customer. */
if (sell_ticket_to_customer ())
{
/* Add one to the total number sold. If we are
all sold out now, tell the bookkeeper to clean
up through the condition variable. */
pthread_mutex_lock (&finish_mutex);
total_sold++;
if (total_sold == NUM_TICKETS)
pthread_cond_broadcast (&finish_cond);
pthread_mutex_unlock (&finish_mutex);
}
}
else
{
/* Otherwise, tell them we are sold out. */
tell_customer_sold_out ();
}
pthread_mutex_unlock (&tickets_sold_lock);
/* Signal the semaphore telling the line that this
call is over. */
sem_post (&lines[currently_helping]);
printf (”Done with caller on line %d.n”, currently_helping);
}
return NULL;
}
void* bookkeeper (void* foo)
{
/* Use the condition wait to make sure that we do not do any
bookkeeping until the total_sold is equal to the total
number of tickets. */
pthread_mutex_lock (&finish_mutex);
while (total_sold < NUM_TICKETS)
pthread_cond_wait (&finish_cond, &finish_mutex);
do_bookkeeping ();
pthread_mutex_unlock (&finish_mutex);
return NULL;
}
int main ()
{
pthread_t agents[NUM_AGENTS];
pthread_t phone_lines[NUM_LINES];
pthread_t cleanup;
void* return_val;
int i;
srand (time (0));
/* Initialize the semaphores. */
sem_init (&num_in_line, 0, 0);
for (i = 0; i < NUM_LINES; i++)
sem_init (&(lines[i]), 0, 0);
/* Create the ticket agents. */
for (i = 0; i < NUM_AGENTS; i++)
pthread_create (&agents[i], NULL, ticket_agent, NULL);
/* Create the lines for callers. */
for (i = 0; i < NUM_LINES; i++)
pthread_create (&phone_lines[i], NULL, call_line, &i);
/* Create the bookkeeper. */
pthread_create (&cleanup, NULL, bookkeeper, NULL);
/* We only need to wait on the bookkeeper because we know
that once the bookkeeper is done, we are done with
the program and can exit. The other threads will loop
forever handling calls. */
pthread_join (cleanup, &return_val);
printf (”Sold all the tickets: %dn”, total_sold);
}
Benjamin Chelf is an
|
http://www.linux-mag.com/id/770
|
crawl-002
|
refinedweb
| 2,377
| 59.84
|
AI & Machine Learning
Building ML models for everyone: understanding fairness in machine learning
Fairness in data, and machine learning algorithms is critical to building safe and responsible AI systems from the ground up by design. Both technical and business AI stakeholders are in constant pursuit of fairness to ensure they meaningfully address problems like AI bias. While accuracy is one metric for evaluating the accuracy of a machine learning model, fairness gives us a way to understand the practical implications of deploying the model in a real-world situation.
Fairness is the process of understanding bias introduced by your data, and ensuring your model provides equitable predictions across all demographic groups. Rather than thinking of fairness as a separate initiative, it’s important to apply fairness analysis throughout your entire ML process, making sure to continuously reevaluate your models from the perspective of fairness and inclusion. This is especially important when AI is deployed in critical business processes, like credit application reviews and medical diagnosis, that affect a wide range of end users.
For example, the following is a typical ML lifecycle:
Below, in yellow, are some ways ML fairness can be applied at various stages of your model development:
Instead of thinking of a deployed model as the end of the process, think of the steps outlined above as a cycle where you’re continually evaluating the fairness of your model, adding new training data, and re-training. Once the first version of your model is deployed, it’s best to gather feedback on how the model is performing and take steps to improve its fairness in the next iteration.
In this blog we’ll focus on the first three fairness steps in the diagram above: identifying dataset imbalances, ensuring fair treatment of all groups, and setting prediction thresholds. To give you concrete methods for analyzing your models from a fairness perspective, we’ll use the What-if Tool on models deployed on AI Platform. We’ll specifically focus on the What-if Tool’s Fairness & Performance tab, which allows you to slice your data by individual features to see how your model behaves on different subsets.
We’ll be using this housing dataset from Kaggle throughout this post to show you how to perform fairness analysis in the What-if Tool. As you can see in the preview below, it includes many pieces of data on a house (square feet, number of bedrooms, kitchen quality, etc.) along with its sale price. In this exercise, we’ll be predicting whether a house will sell for more or less than $160k.
While the features here are specific to housing, the goal of this post is to help you think about how you can apply these concepts to your own dataset, which is especially important when the dataset deals with people.
Identifying dataset imbalancesBefore you even start building a model, you can use the What-if Tool to better understand dataset imbalances and see where you might need to add more examples. With the following snippet, we’ll load the housing data as a Pandas DataFrame into the What-if Tool:
config_builder = (WitConfigBuilder(data.tolist(), data.columns.tolist())
WitWidget(config_builder, height=800)
When the visualization loads, navigate to the Features tab (note that we’ve done some pre-processing to turn categorical columns into Pandas dummy columns):
Here are some things we want to be aware of in this dataset:
This dataset is relatively small, with 1,460 total examples. It was originally intended as a regression problem, but nearly every regression problem can be converted to classification. To highlight more What-if Tool features, we turned it into a classification problem to predict whether a house is worth more or less than $160k.
Since we’ve converted it to a classification problem, we purposely chose the $160k threshold to make the label classes as balanced as possible—there are 715 houses less than $160k and 745 worth more than $160k. Real world datasets are not always so balanced.
The houses in this dataset are all in Ames, Iowa and the data was collected between 2006 and 2010. No matter what accuracy our model achieves, it wouldn’t be wise to try generating a prediction on a house in an entirely different metropolitan area, like New York City.
Similar to the point above, the ”Neighborhood” column in this data is not entirely balanced—North Ames has the most houses (225) and College Circle is next with 150.
There may also be missing data that could improve our model. For example, the original dataset includes data on a house’s basement type and size which we’ve left out of this analysis. Additionally, what if we had data on the previous residents of each house? It’s important to think about all possible data sources, even if it will require some feature engineering before feeding it into the model.
It’s best to do this type of dataset analysis before you start training a model so you can optimize the dataset and be aware of potential bias and how to account for it. Once your dataset is ready, you can build and train your model and connect it to the What-if Tool for more in-depth fairness analysis.
Connecting your AI Platform model to the What-if ToolWe’ll use XGBoost to build our model, and you can find the full code on GitHub and AI Hub.
Training an XGBoost model and deploying it to AI Platform is simple:
model = xgb.XGBClassifier(objective='binary:logistic')
model.fit(data, labels)
model.save_model('model.bst')
!gsutil cp model.bst gs://your_gcs_bucket
!gcloud ai-platform versions create v1 \
--model=model \
--framework='XGBOOST' \
--runtime-version=1.14 \
--origin=gs://your_gcs_bucket \
--python-version=3.5
Now that we’ve got a deployed model, we can connect it to the What-if Tool:
# This prediction adjustment function is needed since the What-If Tool expects
# a model's prediction output as a list of scores for each class.
def adjust_prediction(pred):
return [1 - pred, pred]
config_builder = (WitConfigBuilder(test_examples.tolist(), data.columns.tolist() + ['SalePrice'])
.set_ai_platform_model('your-gcp-project', 'housing', 'v1', adjust_prediction=adjust_prediction)
.set_target_feature('SalePrice')
.set_label_vocab(['Under160', 'Over160']))
WitWidget(config_builder)
Running the code above should result in the following visualization:
If you select Partial dependence plots on the top left, you can see how individual features impact the model’s prediction for an individual data point (if you have one selected), or globally across all data points. In the global dependence plots here, we can see that the overall quality rating of a house had a significant effect on the model’s prediction (price increases as quality rating increases) but the number of bedrooms above ground did not:
For the rest of this post we’ll focus on fairness metrics.
Getting started with the Fairness tabOn the top left of the visualization, select the Performance & Fairness tab. This is what you’ll see first:
There’s a lot going on! Let’s break down what we’re looking at before we add any configuration options.
In the “Explore overall performance” section, we can see various metrics related to our model’s accuracy. By default the Threshold slider starts at 0.5. This means that our model will classify any prediction value above 0.5 as over $160k, and anything less than 0.5 will be classified as less than $160k. The threshold is something you need to determine after you’ve trained your model, and the What-if Tool can help you determine the best threshold value based on what you want to optimize for (more on that later). When you move the threshold slider you’ll notice that all of the metrics change:
The confusion matrix tells us the percentage of correct predictions for each class (the four squares add up to 100%). ROC and Precision / Recall (PR) are also common metrics for model accuracy. We’ll get the best insights from this tab once we start slicing our data.
Applying optimization strategies to data slicesIn the Configure section in the top left of the What-if Tool, select a feature from the Slice by dropdown. First, let’s look at “GarageType_Attchd”, which indicates whether the garage is attached to the house (0 for no, 1 for yes):
Notice that houses with an attached garage have a higher likelihood that our model will value them at more than $160k. In this case the data has already been collected, but let’s imagine that we wanted our model to price houses with attached and unattached garages in the same way. In this example we care most about having the same percentage of positive classifications across classes, while still achieving the highest possible accuracy within that constraint. For this we should select Demographic parity from the Fairness section on the bottom left:
You’ll notice that our threshold sliders and accuracy metrics change when we set this strategy:
What do all these changes mean? If we don’t want the garage placement to influence our model’s price, we need to use different thresholds for houses depending on whether their garage is attached. With these updated thresholds, the model will predict the house to be worth over $160k when the prediction score is .99 or higher. Alternatively, a house without an attached garage should be classified as over $160k if the model predicts 0.52 or higher.
If we instead use the “Equal opportunity” strategy, it will optimize for high accuracy predictions within the positive class and ensure an equal true positive rate across data slices. In other words, this will choose the thresholds that ensure houses that are likely worth over $160k are given a fair chance of being classified for that outcome by our model. The results here are quite different:
Finally, the “Equal accuracy” strategy will optimize for accuracy across both classes (positive and negative). Again, the resulting thresholds are different from either of the outcomes above:
We can do a similar slice analysis for other features, like neighborhood and house type, or we can do an intersectional analysis by slicing by two features at the same time. It’s also important to note that there are many definitions of the fairness constraints used in the What-if Tool; the ones you should use largely depend on the context of your model.
TakeawaysWe used the housing dataset in our demo, but this could be applied to any type of classification task. What can we learn from doing this type of analysis? Let’s take a step back and think about what would have happened if we had not done a fairness analysis and deployed our model using a 0.5 classification threshold for all feature values. Due to biases in our training data, our model would be treating houses differently based on their location, age, size, and other features. Perhaps we want our model to behave this way for specific features (i.e. price bigger houses higher), but in other cases we’d like to adjust for this bias. Armed with the knowledge of how our model is making decisions, we can now tackle this bias by adding more balanced training data, adjusting our training loss function, or adjusting prediction thresholds to account for the type of fairness we want to work towards.
Here are some more ML fairness resources that are worth checking out:
ML Fairness section in the Google’s Machine Learning Crash Course
Google I/O talk on ML Fairness
Human-centered AI guidebook
Code for the housing demo shown in this post in GitHub and AI Hub
Is there anything else you’d like to see covered on the topics of ML fairness or explainability? Let me know what you think on Twitter at @SRobTweets.
|
https://cloud.google.com/blog/products/ai-machine-learning/building-ml-models-for-everyone-understanding-fairness-in-machine-learning
|
CC-MAIN-2020-16
|
refinedweb
| 1,962
| 56.39
|
#include <CH_Timer.H>
TraceTimer class is a self-tracing code instrumentation system.
The first macro is what people will use the. <br><br> In serial, you will see a file called <em>time.table</em> (in parallel, you will get a <em>time.table.n</em> (where n is the rank number) files). If you want fewer files, you can do setenv CH_OUTPUT_INTERVAL nproc and it will only output every nproc processors time.table.n files (where n%n. <br><br> By default, Chombo compiles in the instructions for the timers wherever the macros appear. If the compiler macro <b>CH_NTIMER</b> is defined, then all the CH_TIME* macros evaluate to empty expressions at compile time. \par So, you put some CH_TIME calls in your code and ran it, and nothing happened: Chombo looks for the environment variable <b>CH_TIMER</b>. If it is set to anything (even if it is set to 'false' or 'no' or whatever) then the timers will be active and reporting will happen. If this environment variable is not set, then all the timers check a bool and return after doing nothing. \par One point of interest with using the environment variable: In parallel jobs using mpich, only processor 0 inherits the environment variables from the shell where you invoke 'mpirun', the rest read your .cshrc (.bashrc, etc.) file to get their environment. To time all your processes, you need to make sure the <b>CH_TIMER</b> environment variable gets to all your processes. \par Auto hierarchy: The timers automatically figure out their parent/child relationships. They also can be placed in template code. This has some consequences. First, if you have a low level function instrumented that has no timers near it in the code call stack, you will see it show up as a child of a high level timer. the root timer "main" will catch all orphaned timers. So, even though you might make no call to, say, 'exchange' in your 'main' function, you might very well call a function, that calls a function, that calls 'exchange'. Since no code in between was instrumented, this exchange is accounted for at 'main'. This might look strange, but it should prove very powerful. An expensive orphan is exactly where you should consider some more timers, or reconsidering code design. \par For performance reasons, child timers have only one parent. As a consequence each CH_TIME("label") label can show up at multiple places in your output. Each instance has it's own timer. So, each path through the call graph that arrives at a low-level function has a unique lineage, with it's own counter and time. Thus, I can instrument LevelData::copyTo once, but copyTo can appear in many places in the time.table file. The next level up in complexity is the set of *four* macros for when you want sub-function resolution in your timers. For instance, in a really huge function that you have not figured out how to re-factor, or built with lots of bad cut n paste code 're-use'.: - double start called - double stop called - start called when another child is also started - you leave the function with a child not stopped the following will generate compile time errors: - more than one CH_TIME macro in a function - invoking CH_TIMER("child", t) without having first invoked CH_TIMERS - re-using the timer handle ie. CH_TIMER("bobby", t1); CH_TIMER("sally", t1) - mixing CH_TIME macro with CH_TIMER - mixing CH_TIME macro with CH_TIMERS You do not have to put any calls in your main routine to activate the clocks or generate a report at completion, this is handled with static iniitalization and an atexit function. <br><br>Leaf::AutoStartLeaf().
|
http://davis.lbl.gov/Manuals/CHOMBO-RELEASE-3.2/classTraceTimer.html
|
CC-MAIN-2019-22
|
refinedweb
| 618
| 70.53
|
Design Guidelines, Managed code and the .NET FrameworkiceType");
}
Abstract This series of articles takes a look at the current state of RIA development leveraging Silverlight
URL :... I hate to just link other blogs, but this example
Brad, do you think SL 2 (by RTM) will get a built-in client library to use these services?
Thanks!
..Ben
> Brad, do you think SL 2 (by RTM) will get a built-in client library to use these services?
Ben - Thanks for your interest.. I don't think there will be something productized in the SL2 timeframe, but it is something we are looking into in the future.
Brad, thank you for the reply. This was a ver valuable blog.
Let me ask you this. All those Web.Config setups and codes that you showed, where did you find and learn these from? Where they in Stefan's book? The reason I'm asking, if the security is not going to be in SL2, how can I go about implementing myself and have the proper resources to learn from?
> All those Web.Config setups and codes that you showed, where did you find and learn these!
I would be good if these services were also made available for Win2000 Server, like AJAX extensions, as many of our customers have not yet move to newer servers.
ASP.NET membership authentication ed authorization in Silverlight
In ASP.NET 2.0, we introduced a very powerful!<<
Thanks Brad;
When you mentioned that the ASP.Net security system will not make it into SL2 as a production product, I understand that and we don't want delays on SL2. However, last night I was thinking all those components that are in ASP.Net (i.e. Create a new user, Forgot Password, Show logged in user and etc.) which we will need eventually in SL. So, how about at least giving us some formal directions and docs, so at least we can role out our own version until the Std version is done by you guys? This way for those new apps that don't have the ASP backend, can still use these services.
What you have done in the blog, was worth a million, it just needs a bit more to take it home all the way.
Thank you for your efforts!
Tamir Khason on DrawingBrush, Mike Taulty on Uploading to Silverlight Streaming, Jesse Liberty on creating
Can you show me how to use session (same a ASP.NET website) to save UserID, userPass in SL ?
Congratulation Brad, finally someone wrote a clear description about authorization in Silverlight.
I think you have to add some controls in SL2 for login stuff.
My question here is another. Is there a way to define a session timeout for the login ?
Great article!
What's next, maybe encrypted tickets, or setting up the database to handle the security
Hi there Brad, i have being messing with your examples in my app..
in my case, i use a normal aspx.net page to do the login, and then in the silverlgiht i get the role of the user to see if i need to show or hide something..
it works fine if i add the service reference of my localhost, but when i go to put my app online, i copy the service and webconfig, but when trying to see the roleservice.svc online i get the following error in :
This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.
Parameter name: item
can u help me on this?
after going by many blogs, i finally see in yours just what i was looking the integration betwwen silverlight and asp.net 2.0, thank you
Ru ?
Karen - If your goal is to store the profiles, roles, etc on machine A but expose the WCF services off another machine B then it might be best to build custom WCF services on B, that call into the services exposed off A...
This is a great help, and I've used this tutorial as a base for a login control.
I was wondering if there is a similarly elegant way to create and manage users instead of adding them through the ASP.NET Configuration page. I would like to expose a registration page to the user where they can sign up. As far as I know, the CreateUserWizard is not available through WCF so I'm not sure how to leverage that functionality.
>I was wondering if there is a similarly elegant way to create and manage users instead of adding them through the ASP.NET Configuration page.
Jeff -- thanks. You are right we don't expose user management via the web services, but you could roll your own web services to do this pretty easily I think.. just call into the ASP.NET implemention.
Hi Brad,
Great article but unfortunately, I can't download the source code from:
Could you fix that asap please? There is something I want to check in your project because I have a problem with mine.
Thank you,
Fabien
Fabien -- Sorry about that, my ISP was down this weekend.. they tell me it will be up sometime today.. If it is urgent, send me an email and i will send you the attachment. Check out the "Contact Me" section.
Brad,
Thanks for the tutorial, I have been implementing this in my own project with some success but I have one problem that I'm hoping you have run into before.
With the profile services I am able to work with it normally in VS development server but when I attempt to use IIS Web Server(on XP) it fails. The response code is [UnexpectedHttpResponseCode] a protocol exception.
In fiddler the response tells me "You must log on to call this method"
I should note that I update the service reference before testing on the local webserver. Any advice would be greatly appreciated. Thanks
Brian
Hi there brad, i have put u a question above, but u must forgot to answer...
i have create an exaple like yours and it works fin if i add servicereference for WCF in my computer, but if i try to do this in a webserver we get the following error
"This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.
Parameter name: item"
i think is related to the WCF factory something like that, but all the examples i saw to sovle this are with svs.cs codebehind. our services authservice, roleservice and profileserve don't have cs code...
Do i have to create other .svc with codebehind, or can i just creat the class factory?
can u give some lighs on this?!
thanks very much in advance.
A great article by Brad Adams on accessing the ASP.NET Authentication, Profile and Role Services in Silerlight!
Creating a custom Principal and Identity for Silverlight 2
I think that in order to do the services access on a web server you need a clientaccesspolicy.xml file setup. (For those [UnexpectedHttpResponseCode] exceptions)
Brad has a great post on this subject at
Over at Brad Abrams blog , he has a super article on Role based Security in Silverlight applications?
Vitya, I beleive Stefan shows how to do this in his book... Once you have it accessable from ASP.NET, then accessing it from Silverlight is easy!
Thanks for this utterly super, fantastic, right-on, unbelievably great, I-finally-got-what-really-to-know article. Just a few minor points that need correction:
(1) The line in your description that reads:
<%@ ServiceHost Language="C#" Service="System.Web.ApplicationServices.ProfileService
should instead read:
(2) The screenshot that accompanies the text:
has "Services" in the namespace rather than "AuthenticationService"
Thanks for a winner!
Brad, thanks for pulling this together. This helps a lot
I ran the sample code and in BeginLogin() I got a cross domain error. The following link:
says that the way to fix this is to set the web site to a static port. I did this and still get the same error. Thanks for your help.
I am very excited about Silverlight Beta2 shipping recently ... I took a few minutes to update
So now that I've logged in and Gotten my roles on the agent how do I enforce those roles on the server for my own custom WCF services?
I'm not sure how this login/role management is useful without knowing how to make use of it inside my own WCF services that I would be calling after I logged in.
Thanks
Ett scenario som kommer att bli allt vanligare i takt med att fler och fler verksamhetsstödjande system
I implemented a custom silverlight login control similar to yours. I call the LoginAsync method passing the username and password and I am able to authenticate users. Once a user is authenticated they can access other pages in my website which I have locked down with a combination of <allow /> and <deny /> elements. The problem comes when a user logs out. I call the LogoutAsync method just as in your code. However, users are still able to access the restricted pages, it seems that calling logout does not clear the authentication cookie.
I read something about having to do a page refresh from the logout so the cookie can be cleared. I tried combinations of logout and clear and nothing seems to work.
Strange thing is the problem is consistent on our production server and intermittent when running in the VS development server.
Any thoughts?
A reader recently asked me to expand on the ASP.NET Authentication + Silverlight concept I started..
Based on the questions I received in the last period, I’d like to share here some links that will eventually
If the entire contents of the password box are hilighted, and key.backspace or key.delete is pressed, the password text is not cleared.
in OnTextBoxTextChanged(..)
{
....
if (text.Length == 0)
{
ADD THIS _password = "";
return;
}
....
}
I need to get a list of the users in the aspnet_users table - any suggestions?
Great post, thanks, really complete and useful.
@Steve, create a WCF Service and expose a method GetAllUsers, in your service implementation just delegate to the Membership class to get them, if you only need the names and not the full MembershipUser class (nor sure even if you could sent it directly) you can return the following
return from u in Membership.GetAllUsers().OfType<MembershipUser>()
select u.UserName;
This is very good for web sites that have ASP.NET Authentication (or plan to have) and have Silverlight
Hello,
Thanks for the great article.
I tried to run the example but I got, at runtime, the page asking me to download Silverlight.
The Microsoft Silverlight site tells me:
version installed version 2.0.30523
requested version 2.0.30226
So it seems that the source code is compiled with a slighty out-of-date version. How can I update the solution ? I tried removing all the references and replacing with mine but with no success.
I have the beta sdk 2 installled with vs2008 and the last sl tools for vs 2008
Thanks for any help/tip
Bye
Nicola
Brad Abrams wrote an excellent post about how to set everything in the server and client to consume this
Silverlight 2 line-of-business application
Accessing the Membership Provider from Silverlight
I wanted to try and follow up on this idea of the XAML Continuum and the basic example that I did with
|
http://blogs.msdn.com/brada/archive/2008/05/03/accessing-the-asp-net-authentication-profile-and-role-service-in-silverlight.aspx
|
crawl-002
|
refinedweb
| 1,930
| 72.56
|
Results 1 to 2 of 2
Dear all, Can anyone help me out in finding the processor time spent on the kernel network stack ? I have a TCP/IP offload Engine module that bypasses the INET, ...
- Join Date
- May 2008
- 1
Processor time spent on Network stack
- Join Date
- Apr 2005
- Location
- Romania
- 42
Hi,
1. Try to run your program with strace:
strace -c -r -T ./program
2.
#include <time.h>
#include <iostream.h>
main() {
clock_t start, stop;
start=clock();
<-Your code here->
stop=clock();
cout<<"Total time:"<< (double)(stop-start)/CLOCK_PER_SEC<<"sec"<<"\n";
return 0;
}
Has Your TOE a packet generator too ?
|
http://www.linuxforums.org/forum/kernel/122882-processor-time-spent-network-stack.html
|
CC-MAIN-2014-52
|
refinedweb
| 104
| 72.66
|
The profiler class has a hard coded constant that is added to each event handling time to compensate for the overhead of calling the time function, and socking away the results. The following procedure can be used to obtain this constant for a given platform (see discussion in section Limitations above).
import profile pr = profile.Profile() print pr.calibrate(100) print pr.calibrate(100) print pr.calibrate(100)
The argument to calibrate() is the number of times to try to do the sample calls to get the CPU times. If your computer is very fast, you might have to do:
pr.calibrate(1000)
or even:
pr.calibrate(10000)
The object of this exercise is to get a fairly consistent result. When you have a consistent answer, you are ready to use that number in the source code. For a Sun Sparcstation 1000 running Solaris 2.3, the magical number is about .00053. If you have a choice, you are better off with a smaller constant, and your results will ``less often'' show up as negative in profile statistics.
The following shows how the trace_dispatch() method in the Profile class should be modified to install the calibration constant on a Sun Sparcstation 1000:
def trace_dispatch(self, frame, event, arg): t = self.timer() t = t[0] + t[1] - self.t - .00053 # Calibration constant if self.dispatch[event](frame,t): t = self.timer() self.t = t[0] + t[1] else: r = self.timer() self.t = r[0] + r[1] - t # put back unrecorded delta return
Note that if there is no calibration constant, then the line containing the callibration constant should simply say:
t = t[0] + t[1] - self.t # no calibration constant
You can also achieve the same results using a derived class (and the profiler will actually run equally fast!!), but the above method is the simplest to use. I could have made the profiler ``self calibrating,'' but it would have made the initialization of the profiler class slower, and would have required some very fancy coding, or else the use of a variable where the constant ".00053"was placed in the code shown. This is a VERY critical performance section, and there is no reason to use a variable lookup at this point, when a constant can be used.
See About this document... for information on suggesting changes.See About this document... for information on suggesting changes.
|
http://docs.python.org/release/2.1.3/lib/profile-calibration.html
|
crawl-003
|
refinedweb
| 397
| 67.25
|
Lease vs Purchase, Capital Budgeting
1) Lease vs. Purchase: The Hot Bagel Shop wishes to evaluate two plans, leasing and borrowing to purchase, for financing an oven. The firm is in the 40% tax bracket.
Lease. The shop can lease the oven under a 5-year lease requiring annual end-of-year of $5000. All maintenance costs will be paid by the lessor, and insurance and other costs will be borne by the lessee. The lessee will exercise its option to purchase the asset for $4000 at termination of the lease.
Purchase the oven costs $20,000 and will have a 5-year life. It will be depreciated under MACRS using a 5-year recovery period. The total purchase price will be financed by a 5 year, 15% loan requiring equal annual end-of-year payments of $5,967. The firm will pay $1000 per year for a service contract that covers all maintenance costs; insurance and other costs will be borne by the firm. The firm plans to keep the equipment and use it beyond its 5-year recovery period.
a. For the leasing plan, calculate the following:
(1) The after-tax cash outflow each year.
(2) The present value of the cash out flows, using a 9% discount rate.
b. For the purchasing plan, calculate the following:
(1) The annual interest expense deductible for tax purposes for each of the 5 years.
(2) The after-tax cash outflow resulting from the purchase for each of the 5 years.
(3) The present value of the cash outflows, using a 9% discount rate.
c. Compare the present value of the cash outflow streams from each plan, and determine which would be preferable. Explain your answer.
2) Marking Norwich Tool's Lathe Investment Decision: Norwich Tool, a large machine shop, is considering replacing one of its lathes with either of two new lathes-lathe A or lathe B. Lathe A is a highly automated, computer-controlled lathe; lathe B is a less expensive lathe that uses standard technology. To analyze these alternatives, Mario Jackson, a financial analyst, prepared estimates of the initial investment and incremental (relevant) cash inflows associated with each lathe. These are shown in the following table.
Lathe A Lathe B
Initial Investment (II) $660,000 $360,000
Year (t) Cash inflows (CFt)
1 $128,000 $ 88,000
2 182,000 120,000
3 166,000 96,000
4 168,000 86,000
5 450,000 207,000
Note that Mario plans to analyze both lathes over a 5-year period. At the end of that time, the lathes would be sold, thus accounting for the large fifth-year cash inflows.
One of Mario's major dilemmas centered on the risk of the two lathes. He feels that although the two lathes have similar risk, lathe A has a much higher chance of breakdown and repair due to its sophisticated and not fully proven solid-state electronic technology. Because he 9is unable to effectively quantify this possibility, Mario decides to apply the firms, 13 percent cost of capital when analyzing the lathes. Norwich Tool requires all projects to have3 a maximum payback period of 4 years.
a. Use the payback period to assess the acceptability and relative ranking of each lathe.
b. Assuming equal risk, use the following sophisticated capital budgeting techniques to assess the acceptability and relative ranking of each lathe:
1) Net present value (NPV).
2) Internal rate of return (IRR).
c. Summarize the preferences indicated by the techniques used in a and b, and indicate which lathe you recommend, if either, if the firm has (1) unlimited funds or (2) capital rationing.
d. Repeat part b assuming that Mario decides that, due to its greater risk, lathe A's cash inflows should be evaluated by using a 15% cost of capital.
e. What effect, if any, does recognition of lathe A's greater risk in d have on your recommendation in c?
Solution Summary
Evaluates a Lease vs Purchase decision. Uses payback, NPV, IRR to evaluate an equipment purchase decision
|
https://brainmass.com/business/capital-budgeting/lease-vs-purchase-capital-budgeting-12653
|
CC-MAIN-2017-13
|
refinedweb
| 674
| 61.87
|
Zumero for SQL Server (ZSS) allows you to synchronize data from Microsoft SQL Server with data stored locally on a mobile device, enabling your app to keep an offline copy of your server-side data. The local data takes the form of a SQLite database file, allowing your app to interact with it using the familiar and ubiquitous SQLite library. A single call to Zumero will synchronize the remote SQL Server data with the local SQLite data. Zumero takes care of two-way synchronization, data type translation, permission validation, and conflict resolution.
This extension is part of the ZSS Client SDK, which is freely available. It contains the client-side code necessary to sync with a ZSS Server, which is an IIS add-on that is licensed and installed on your own server infrastructure. The ZSS Server then communicates with your SQL Server as needed.
This extension contains a .NET assembly that allows you to invoke Zumero synchronization from WinRT apps written in any .NET language. This extension depends on the "Zumero WinRT Component" extension. Once both are installed, just add a reference to them from your project and start using the functionality in the Zumero namespace. Start with ZumeroClient.Sync(...).
Notes:
|
https://marketplace.visualstudio.com/items?itemName=ZumeroLLC.ZumeroNETAssemblyforWinRT
|
CC-MAIN-2019-22
|
refinedweb
| 202
| 63.29
|
Opened 4 years ago
Closed 4 years ago
Last modified 4 years ago
#16022 closed Bug (needsinfo)
Cyclic reference in FieldFile causes memory usage to grow considerably
Description
django.db.models.fields.files:FieldFile creates a cyclic reference to the model instance it's attached to via django.db.models.fields.files:FileDescriptor.
The effects can be considerable. In our Web site, for example, it causes the process running Django to increase the memory used by over 1MB after every request.
The patch is generated against Django trunk, even though it's only been tested under Django 1.1.4 (but the cyclic reference doesn't seem to have been fixed).
Attachments (1)
Change History (10)
Changed 4 years ago by Gustavo
comment:1 Changed 4 years ago by Gustavo
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
Please disregard the patch, it breaks file uploads. I'm trying to improve it at the moment (and suggestions are much appreciated).
comment:2 Changed 4 years ago by Gustavo
I've tried replacing weakref.ref() with weakref.proxy(), which does work but then memory keeps growing as usual. I think a proper way to fix it is to break the cyclic reference, but that'd be backwards incompatible.
I cannot afford spending more time on this, so I'll leave it to someone else. I'm happy to test any eventual fix though. In the meantime, we'll be using mod_wsgi's maximum-requests to mitigate the consequences of this problem.
A hint to whoever will have a look at this: Try setting self.instance to None in FieldFile.__init__ and you won't notice any memory growth when you query many records. This breaks creation, modification and deletion of files, but helps demonstrate that this is the problematic reference.
comment:3 Changed 4 years ago by Gustavo
- Has patch unset
- Keywords memory leak added
comment:4 Changed 4 years ago by Gustavo
- Summary changed from Cyclic reference in FieldFile to Cyclic reference in FieldFile causes memory usage to grow considerably
comment:5 Changed 4 years ago by aaugustin
Python's gc is supposed to be able to collect reference cycles these days, unless there are __del__ methods. I didn't see any that could by linked with this bug.
comment:6 Changed 4 years ago by aaugustin
- Resolution set to worksforme
- Status changed from new to closed
OK, I tried to reproduce this seriously. I created a project called madupload and an app called receiver inside.
madupload ├── __init__.py ├── manage.py ├── receiver │ ├── __init__.py │ ├── models.py │ ├── views.py ├── settings.py └── urls.py
receiver/models.py:
from django import forms from django.db import models class UploadModel(models.Model): upload = models.FileField() class UploadForm(forms.ModelForm): class Meta: model = UploadModel
receiver/views.py:
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import UploadForm @csrf_exempt def upload(request): form = UploadForm(request.POST, request.FILES) try: model = form.save(commit=False) return HttpResponse("Saved %i bytes.\n" % model.upload.size, status=201, content_type='text/plain') except ValueError: return HttpResponse(repr(form.errors) + "\n", status=400, content_type='text/plain')
urls.py:
from django.conf.urls.defaults import patterns, url urlpatterns = patterns('', url(r'^$', 'receiver.views.upload'), )
All other files are unchanged from Django's template.
Then I launched runserver and started uploading:
myk@mYk madupload % dd if=/dev/random of=1mb.bin bs=1024 count=1024 1024+0 records in 1024+0 records out 1048576 bytes transferred in 0.146655 secs (7149958 bytes/sec) myk@mYk madupload % while true; do curl -F "upload=@1mb.bin"; done Saved 1048576 bytes. Saved 1048576 bytes. Saved 1048576 bytes. ...
I've let it run more than one hundred of uploads, and the memory footprint of the Python process handling runserver is flat.
At this point, I have proven that the cyclic reference in FileField is not a problem in itself.
I still don't know what's causing your bug. You may have a global variable referencing your FileField objects somewhere.
comment:7 Changed 4 years ago by Gustavo
- Resolution worksforme deleted
- Status changed from closed to reopened
Hello, aaugustin.
Thank you very much for looking into this!
I forgot to add a useful piece of information here, which I mentioned on Google Groups: Memory increases considerably when you query a model that has a FileField. I'm sorry about that.
To reproduce this, you could create, say, 2000 records and iterate over them like this inside a Django view:
for record in MyModel.objects.all(): echo record.upload
As you refresh the page, you'll notice that memory increases.
Cheers.
comment:8 Changed 4 years ago by aaugustin
- Resolution set to needsinfo
- Status changed from reopened to closed
I read your email to django-users which had more info and I updated my test code above as follows.
receiver/models.py:
from django import forms from django.db import models class UploadModel(models.Model): upload = models.FileField(upload_to='receiver') class UploadForm(forms.ModelForm): class Meta: model = UploadModel
receiver/views.py:
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import UploadForm, UploadModel @csrf_exempt def upload(request, commit=False): form = UploadForm(request.POST, request.FILES) try: model = form.save(commit=commit) action = "Saved" if commit else "Received" return HttpResponse("%s %i bytes.\n" % (action, model.upload.size), status=201, content_type='text/plain') except ValueError: return HttpResponse(repr(form.errors) + "\n", status=400, content_type='text/plain') def names(request): upload_names = [model.upload.name for model in UploadModel.objects.all()] return HttpResponse("%i objects \n" % len(upload_names), status=200, content_type='text/plain')
urls.py:
from django.conf.urls.defaults import patterns, url urlpatterns = patterns('', url(r'^fake/$', 'receiver.views.upload', {'commit': False}), url(r'^save/$', 'receiver.views.upload', {'commit': True}), url(r'^read/$', 'receiver.views.names'), )
I added a database, etc. to the settings and ran syncdb.
I uploaded 100 1kb files:
myk@mYk madupload % dd if=/dev/random of=1kb.bin bs=1024 count=1 1+0 records in 1+0 records out 1024 bytes transferred in 0.000232 secs (4414149 bytes/sec) myk@mYk madupload % for i in {1..100}; do curl -F "upload=@1kb.bin"; done Saved 1024 bytes. Saved 1024 bytes. Saved 1024 bytes. ...
And then I read them over and over:
myk@mYk madupload % while true; do curl; done 100 objects 100 objects 100 objects ...
I've been heating the planet like this for a few minutes and the memory curve climbed a little bit at the beginning, then stabilized.
Initially, I was using Python 2.6; I switched to Python 2.5 but the result was the same.
So, unfortunately, we still don't have a proof that the bug is in Django itself.
At this point, I am afraid you didn't provide sufficient information for me to reproduce the bug. You could:
- try to play with gc.garbage to see what happens in your app, see
- modify my example until it exhibits the memory leak
- come up with your own reproducible example, and provide complete instructions of how to run it
Thanks!
comment:9 Changed 4 years ago by aaugustin
PS : closing the ticket as "needsinfo" is part of the standard triaging procedure when we can't reproduce a problem. It doesn't mean the problem doesn't exist.
Fixed cyclic reference by making it a weak one
|
https://code.djangoproject.com/ticket/16022
|
CC-MAIN-2015-40
|
refinedweb
| 1,229
| 60.92
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.