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
|
|---|---|---|---|---|---|
![if gte IE 9]><![endif]>
Hi
I'm working on a project where I need to compress XML, convert to Base64 and send it to a SOAP web server.
I couldn't find a better way to do this, without having to export the XML to some temp directory, execute a external lib to compress the file and then import the compressed file so I could convert it to Base64 and send it.
I was wondering if there was a better solution for this.
Any suggestions?
Thanks
Brian got there first. But if you have access to the .NET classes then this is a good way to go. I set up compression of all the blobs in a database and it didn't take long to sort out at all.
Hi Brian,
Thanks for replying.
Current OE version is 10.2b, although we've already started working with 11.6.
OS is windows server.
We're not using .net classes, but I'll take a look either way.
there is a "standard library" on eo hive with some zlib content...
NB. haven't used it myself.
If you use the WRITE-XML() Method you can use a MEMPTR as target-type. To encode just use the base64-encode function passing the memptr. You will get a longchar with base64 encoded text Is this what you are looking for?
> On Jan 26, 2016, at 8:11 AM, Brian K. Maher wrote:
>
> For 10.2B, you should google for zlib,
zlib is part of OpenEdge. You should have it in the DLC/bin or lib directory.
--
regards,
gus (gus@progress.com)
"If I set here and stare at nothing long enough, people might think I'm an engineer working on something."
-- S.R. McElroy
> On Jan 26, 2016, at 9:24 AM, Peter Judge wrote:
> While true, there are some caveats, not least of which is that it doesn't ship with all products (only with the dev products, IIRC).
it was put in for the 4GL client / appserver stream compression
it is actually very simple to use but i do not have any 4gl examples. but there are on oehive
Is it possible to use .net class DeflateStream in 10.2b?
I'm trying to create an example but I'm unable to define the enumerator CompressionLevel, which is the second parameter of the DeflateStream Constructor.
I'm not used to work with .net within ABL.
Thanks Peter,
On 11.6 it seems to work, but on 10.2b it doesn't compile due to the following error:
Could not locate element 'CopyTo' in class 'System.IO.FileStream'. (12927)
Anyway, I wonder if I could use a MemoryStream instead of a FileStream in order to work just with just memptrs.
I was able to convert a memptr into a MemoryStream, though I'm not sure if it works as I couldn't convert it back to memptr.
def var mXML as memptr no-undo.
def var mResult as memptr no-undo.
def var streamSize as int no-undo.
def var memStream as MemoryStream no-undo.
def var i as int no-undo.
/* load memptr var with some value */
/* memptr to MemoryStream */
streamSize = get-size(mXML).
memStream = new MemoryStream(streamSize).
do i = 1 to streamSize:
memStream:WriteByte(get-byte(mXML, i)).
end.
/* MemoryStream to memptr*/
set-size(mResult) = memStream:Length.
do i = 1 to memStream:Length:
put-byte(mResult, i) = memStream:ReadByte().
end.
Answering my own question.
CopyTo doesn't work on 10.2b because it is available just for .NET version 4.0 and above.
According to progress, 10.2.b only supports .NET 3.0.
knowledgebase.progress.com/.../000054406
There are some compression examples included in the download of my PugChallenge presentation on .Net.
I 'm not sure if they will work on 10.2B.
Look in PugUtils.cls
Tom
|
https://community.progress.com/community_groups/openedge_development/f/19/t/22692
|
CC-MAIN-2018-13
|
refinedweb
| 640
| 78.14
|
.NET Memory Management and Finalization
Finalization and Resurrection
As you may have noticed in the previous section, objects become reachable again when they're placed in the ReadyToFinalize queue. This is sometimes called "resurrection," since the objects seem to come back to life from being dead. (Of course, then they are supposed to die again, but why not enjoy life for 50 milliseconds more?)
But you, as a developer, have the power to bring objects back to life for considerably longer. To do that, just make the object reachable from your application code. Here is an example:
public class MyFinalizableObject {
public MyFinalizableObject() {
}
public override void Finalize() {
// Assign pointer to this object to static data member in MyApplication
MyApplication.somePointer = this;
}...
public class MyApplication {
static public Object somePointer; // Defaults to null
...
}
Inside the Finalize() code, the MyFinalizableObject type saves a reference to itself into a static data member in the MyApplication class during finalization. Saving a reference makes the object undergoing finalization reachable again, and the garbage collector will not consider it collectable. However, resurrecting an object brings unwanted consequences. When it's being finalized, the object is no longer part of the RegisteredForFinalization queue; it has been removed from the queue by Finalizer thread. That means this object will never be finalized again. Your class should contain logic to allow the cleanup of the resources used by the type in some other place.
There are very few good uses of resurrection. The best approach is to avoid it whenever possible. However, if resurrection is absolutely necessary, you may use a method called ReRegisterForFinalize, which takes a single parameter - the pointer to the object - and puts that object back in the RegisteredForFinalization queue. Doing so ensures that the Finalize() method is run again when the object is garbage collected. If you call ReRegisterForFinalize multiple times, the Finalize() method ends up being called a corresponding number of times. That's probably not the result you would expect from finalization.
Finalization and Weak References
Going back to the garbage collection basics, when a root points to an object, that object is considered reachable and cannot be garbage collected. .NET has special kind of references, called weak references, which allow an object to be garbage collected when still referenced, and at the same time allow an application to access the object before it is actually garbage collected. The process of accessing the object via weak reference is slightly different from accessing the object via plain reference. Let's consider what happens when an object is referenced via a weak reference.
Assume the only reference to an object is a weak reference. The garbage collection engine decides to perform the collection and encounters that object. The object is considered not reachable (that's why the reference is called "weak") ,and is garbage collected. Later, an application tries to access that same object via weak reference and fails, because the object no longer exists.
On the other hand, let's assume the application tries to access the same object via weak reference before garbage collection is run. To access the object via weak reference, your application has to obtain a strong reference to the object first. But, as soon as the strong reference to object is obtained, the object is no longer collectable, because it just became reachable through that strong reference. When the application is done with using that object, the strong reference is destroyed, but the weak reference still exists. Now, if the garbage collector decides to collect that object, it may very well do so.
A good question would be: why do we need that type of reference? In certain memory-tight conditions (or in your own virtual memory implementation) you may choose to keep the objects (currently not being used) around only if the environment you are running in can afford to do so. If the environment decides to do a garbage collection, it may collect objects not currently in use; later, our application will try to access them and, in case of failure, can create that same objects again and de-serialize them from some kind of persistent storage.
The WeakReference type offers two constructors:
WeakReference(Object target);
WeakReference(Object target, Boolean trackResurrection);
The target parameter identifies the object to which this reference points; the trackResurrection parameter indicates if WeakReference should continue tracking the object after the Finalizer thread has called the Finalize() method for that object. Most of the time, tracking objects after the Finalize() method is called is not needed, so the first constructor is used.
Most of the time, when a weak reference to an object is created, the strong reference to the same object is set to null. That allows garbage collection to collect that object if needed. If a strong reference to an object still exists, garbage collection won't be able to collect that object, and having a weak reference to the same object does not make a lot of sense. So, as soon as a weak reference is created, get rid of the strong reference pointing to the same object.
Dispose and Garbage Collection
As we all know by now, garbage collection is non-deterministic, and there is no guarantee as to when a particular object will be garbage collected and the Finalize() method will be called. Yet, you want to dispose of resources you no longer need as soon as possible, to reduce the strain on the system. For instance, as soon as you have retrieved your data from a database connection, the connection should be closed. Not closing the connection immediately after use results in eating up system resources you do not really need. .NET provides the IDisposable interface and the Dispose() method for resource cleanup.
The main difference between Dispose and Finalize() is that Finalize() is protected and can not be called explicitly; Dispose() can be called explicitly. Calling Dispose() on an object accomplishs two things: it cleans up any resources that were allocated by the object, and it marks the object so that the garbage collection does not call its Finalize() method when this object is being garbage collected. Finalize() is not called, because all resources has already been cleaned up by Dispose(). By calling Dispose(), we save the overhead of a call to Finalize() (by removing the object from RegisteredForFinalization queue), and perform resources cleanup at the most appropriate time. However, keep in mind that Dispose() can be called more than once (for example, from different threads), so you need to make sure you don't perform resource cleanup more than once. Here is an example:
public class MyDisposableClass : IDisposable {
bool done; // indicate if object is already disposed
public MyDisposableClass() {
done = false;
public ~MyDisposableClass() {
Dispose(true);
public void Dispose(bool done) {
if (!done) {
GC.SuppressFinalize(this);
// TODO: perform resource cleanup here
done = true;
}
To ensure that resources are released only once, make sure you always call GC.SuppressFinalize() in the Dispose method so that Finalize does not get called later in the process.
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
|
http://www.dotnetspark.com/kb/3407-net-memory-management-and-finalization.aspx
|
CC-MAIN-2018-26
|
refinedweb
| 1,179
| 50.06
|
...one of the most highly
regarded and expertly designed C++ library projects in the
world. — Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
View on a range, either closing it or leaving it as it is.
The closeable_view is used internally by the library to handle all rings, either closed or open, the same way. The default method is closed, all algorithms process rings as if they are closed. Therefore, if they are opened, a view is created which closes them. The closeable_view might be used by library users, but its main purpose is internally.
template<typename Range, closure_selector Close> struct closeable_view { // ... };
#include <boost/geometry/views/closeable_view.hpp>
|
http://www.boost.org/doc/libs/1_50_0/libs/geometry/doc/html/geometry/reference/views/closeable_view.html
|
CC-MAIN-2017-04
|
refinedweb
| 108
| 65.01
|
How to use Pixotope Gateway
Introduction
Pixotope Gateway is a service to relay HTTP requests to Data Hub and to respond with meaningful data when it makes sense. The service is automatically launched by Pixotope Daemon. There’s an instance of it running on every Pixotope machine.
Network
Listening/Sending
Port 16208
Data hub
PX_Datahub.exe as well as Gateway
PX_Gateway.exe, which are auto started by Pixotope, are expected to run on your machine.
Sending HTTP Requests
HTTP POST messages with a JSON data body are the main way of publishing messages via Pixotope Gateway. The whole functionality of a regular ZeroMQ Data Hub client should be available to anyone using HTTP POST.
Request specification
Target URL
The target URL is a versioned Gateway endpoint following this pattern:
IPAddress - local network IP of the machine running Pixotope Gateway,
Port - port Pixotope Gateway listens on, 16208 by default (can be configured),
Version - Pixotope version used, for example: 2.2.0
Requests based on an older version (using an older version number) should still work unless there has been a breaking API change.
For example, for Pixotope 2.2.0 and a localhost URL, HTTP publishing would be:
Request body
Data body is a JSON containing Topic and Message objects, formatted in accordance with the general Data Hub guidelines.
Gateway specifics
Any field signifying the identity of the sender (Source, RespondTo) don’t need to be sent. These fields will be filled in by Gateway.
For Call messages, the ID field will always be set/overridden by Gateway. It therefore doesn’t have to be included.
Request header
HTTP headers can be empty.
Example
Python example to Set CompositingColorSpace value on the Store:
import json, requests url = " payload = json.dumps({ "Topic": { "Type": "Set", "Target": "Store", "Name": "State.General.CompositingColorSpace" }, "Message": { "Value": "Video" } }) response = requests.request("POST", url, data=payload)
Sending URL-only HTTP requests
Some messages can be formatted using a URL only HTTP GET method. This will make them easier to execute, but certain complexities will not be available (for example setting the whole struct with Set at once).
Use the Target URL (shown above) and add named URL parameters corresponding to Topic and Message fields of a regular Data Hub request.
Example
Python example to Set camera Delay value on the Store:
import requests requests.request("GET", "
You can also just execute the above URL from your web browser. Try it!
It can be useful for experimenting with your project.
Call type requests
Additionally, for Call Type requests, you can add named RPC arguments by adding URL parameters with a “Param“ prefix.
Example
Python example to Call a method CallFunction on TJCGWS040-Engine:
import requests requests.request("GET", "
Going against the standard practice we allow changing the state of our system with HTTP GET requests. This will be configurable in the future.
HTTP response
Any HTTP request sent to Pixotope Gateway will result in a response. In many cases the response is going to be quite minimal (for calls that only trigger changes without querying any data).
Responses to the different Type of the request
|
https://help.pixotope.com/phc/2.2/How-to-use-Pixotope-Gateway.3291545888.html
|
CC-MAIN-2022-21
|
refinedweb
| 516
| 56.35
|
19 September 2011 11:23 [Source: ICIS news]
LONDON (ICIS)--UBS has lowered its share-price target for Germany-based specialty and pharmaceutical company Merck KGaA to €63 ($86) from €76, the Swiss investment bank said on Monday.
“Upcoming competitor data may suggest enhanced pressure on [Merck’s] key pharma products,” UBS said.
The investment bank also lowered estimates for Merck’s liquid crystal business in the second half of 2011, seeing potential for weaker demand because of softer LCD sales.
UBS maintains it “neutral rating” for Merck, it added.
In July, Merck recorded a net loss of €85.9m in the second quarter of 2011 as its Merck Serono division struggled with overcapacity problems and the firm wrote off the value of several experimental treatments.
Revenues for the quarter jumped by 16% to €2.56bn, compared with €2.2bn during the same period in 2010, however, the company made a net loss of €85.9m compared with a profit of €183.4m a year earlier.
UBS had raised Merck’s share price target in June to reflect the performance of the European pharmaceutical sector and expectations of less near-term risk.
At 09:19 GMT on Monday, Merck’s shares were trading on ?xml:namespace>
(
|
http://www.icis.com/Articles/2011/09/19/9493198/ubs-cuts-germanys-merck-group-share-price-target-to-63-from.html
|
CC-MAIN-2015-18
|
refinedweb
| 206
| 56.66
|
Paramiko key pair gen. Error IV must be 8 bytes long.
I'm working on an ssh client for pythonista and have ran into a problem generating a password protected key pair. I keep getting an error which I think is from pycrypto. The error occurs when trying to encrypt the private key. Any ideas would be greatly welcome.
Error: IV must be 8 bytes long.
import paramiko def keygen(fil,passwd=None,bits=1024): k = paramiko.RSAKey.generate(bits) k.write_private_key_file(fil, password=passwd) o = open(fil+'.pub' ,"w").write(k.get_base64()) keygen('rsa_test','password')
Fixed it. There was a bug in paramikos cipher.
Can you please post the workaround?
Change the following line in pkey.py to hardcode the 'AES-128-CBC' cipher instead. The comment states that there is a single cipher that is used. The error is from trying to use DES. I just hard coded it to AES.
_write_private_key() # cipher_name = list(self._CIPHER_TABLE.keys())[0] cipher_name = 'AES-128-CBC'
Nice. Yes, you definitely want AES instead of DES which was proven insecure long ago. A good summary of the history at
|
https://forum.omz-software.com/topic/846/paramiko-key-pair-gen-error-iv-must-be-8-bytes-long/5
|
CC-MAIN-2022-33
|
refinedweb
| 186
| 72.32
|
Not:
1 = 2).
The way that I'd encourage you to approach Elixir's match operator is to realize that it behaves differently based on the types involved. And, in the case of a variable on the left side, that behaviour is an assignment. Beyond that, understanding the match operator's full potential requires the right examples.
First, consider a login page which, through some web framework, calls a method with a map hopefully containing an
"password" field:
def create(%{"email" => e, "password" => p}) do ... end
The above will only match when three conditions are met. First, the argument has to be a map. Second, it has to have an
"password" key. Put differently, when the left side of the match operator is a map, then it will only match another map that has at least the same keys. The behaviour on such a match is to deconstruct the map (into the
e and
p variables, for the above case).
If we try to call
create with something other than a map, or with a map that doesn't have both a
"password" key, Elixir will raise an exception. Since we probably want something a little less dramatic for a web application, we'll add another method:
# underscore means we don't care about the parameter # though it's better to use something like _params to improve understandability def create(_) do # display a nice error message end
It's important that we place this method last, else it'll match everything. If you're thinking that it would be nice if Elixir could properly prioritize these, consider that it's pretty trivial to get into ambiguous situations.
As another example, we have users which need to be handled differently based on their
version:
The
%{...} = user syntax matches a map or structure and assigns the parameter to
user.
It turns out that the "id" comes in as a string, but we want it as an integer. We'll rewrite that last method:
defp load_context(context, id) do case Integer.parse(id) do {id, _remainder} -> Map.put(context, :user_id, id) :error -> context # could also use _ on the left side end end
Here we see matching with a tuple and an atom (aka, symbol / intern). What if we expected all our user ids to be suffixed with the letter "u"? We could rewrite that one case condition to be:
{id, "u"} -> Map.put(context, :user_id, id)
Matching is a powerful and it changes how you write and organize your code. The result tends to be very small and focused functions. This certainly isn't without its downsides, but overall I think it's a clear win.
|
https://www.openmymind.net/Pattern-Matching-In-Elixir/
|
CC-MAIN-2021-39
|
refinedweb
| 445
| 70.53
|
Post your Comment
Redefine property in the children Target
Redefine property in the children Target....
If any given property file which is not available on local target... to define the property file whether it is
local or global. When you create
Flex target property example
Flex target property example
... object property target
. We also have another event object property... target and currentTarget differ in their targeting jobs. target
property may
Children's Writing
Article Writing for Children
Future lies in hands of Children or a child... on what should be the content
while writing articles for children. Do we understand.... In this environment writing articles for
children is more of a task of responsibility
Flex current target property example
Flex current target property example
The example below describes the working flex currentTarget property. Code below shows a method
Spark Animate effect in Flex4
Spark Animate Effect in Flex4:
Spark Animate effect animates any property of the
component or target. In this example we create a instance of the
SimpleMotionPath class for each property to animate. The tag of Animate effect
Spark AnimateColor effect in Flex4
Spark AnimateColor effect in Flex4:
Spark AnimateColor effect changes the color property of
the component or target.
The tag of AnimateColor effect is <s:AnimateColor>. The syntax of AnimateColor
effect is following:
<s
@property nsinteger
@property nsinteger Hi,
How to declare @property nsinteger?
Thanks... myvariable;
}
@property (nonatomic) NSInteger myvariable;
@end
Thanks
...;
}
@property (nonatomic) NSInteger myvariable;
@end
Thanks
Property File
Property File how to store key & values pair in property file?
Note: In property file keys should be displayed in ascending order.
please reply the answer as soon as possible.
Thanking You
import java.io.
adding mouse listeners to drop target
with adding mouse listeners to "table" which is drop target, to accept drop... in to a drop target it always goes to a default position. i cant customize the position on drop target. please someone help me with this.
thanks in advance
jpa one-to-many persist children with its ID
jpa one-to-many persist children with its ID @Entity
public class... can see from my annotaiton, When Item pesist, it will also persist its children... it's children
Reflection api :Invocation target exception - JDBC
Reflection api :Invocation target exception Am using a function to insert a record into the database .Using reflection api am invoking... in Invocation target Exception .How to resolve
Target attribute in anchor tag, Use of target attribute of anchor tag in HTML5.
Target attribute in anchor tag, Use of target attribute of anchor tag in
HTML5.
In this tutorial, we will see the use of target attribute of anchor tag in
HTML5. Target attribute tells the browser where to display linked document
jpa one-to-many persist children with its ID by EntityListeners
jpa one-to-many persist children with its ID by EntityListeners jpa one-to-many persist children with its ID by EntityListeners
Wats Deploying war in Target Server - Development process
Wats Deploying war in Target Server
Hi Friends,
I am new to web application, can u explain briefly wat is "Deploying a .war,.jar,.ear files in target server.
Thank u in advance
Hi rajendra
property in javascript get set
property in javascript get set How to create the get and set property in JavaScript?
Creating Get and Set properties in JavaScript example..
myVar Sample = {
nval : "",
get get() { return this.nval; },
set do i create the node for target SMO in java..???
How do i create the node for target SMO in java..??? How do i create the node for target SMO in java..??? or else whats the method for accessing the target SMO
property datasource required - Spring
property datasource required Hi I am using java springs I am using mysql as backend I am getting one error when i compile the application.property datasource required.
This is my dispatcher-servlet.xml
Multibox property - Struts
Multibox property I am trying to implement a multibox property. I get the values for them through a populated VO object from the Server.
In the form I have defined two array variables
They are Daysoftheweek : contains all
how to custom location of a object after dragging to the drop target
;how to change the position of a button when after it drags on the drop target... how to drag the object inside the drop target. (that means how to change the position of the object after it drops on to the drop target
Read Property file From Jmeter
Read Property file From Jmeter Hi,
I am running web driver script from Jmeter,
but while reading property file I am getting "File Not Find Exception".
Please tell me how to read ".properties" file from Jmeter
SPEL-System Property
Accessing System Property Using SpEL
Spring 3 provides powerful Expression...: The MyClass class contains property named "prop"
which is of String...;spel.systemproperty.MyClass">
<property name="prop" value="
Post your Comment
|
http://www.roseindia.net/discussion/21927-Redefine-property-in-the-children-Target.html
|
CC-MAIN-2014-10
|
refinedweb
| 818
| 56.25
|
It’s been a while since I’ve posted about Axum as I’ve been posting about other asynchronous and parallel programming models. After two releases of the Axum standalone language and lots of good user feedback, it’s time to ponder what could be with Axum. Overall, the goals of Axum to provide an agent-based concurrency oriented system is important as we consider the emerging hardware trends. Many of these ideas would in fact benefit most languages, whether mainstream or not. With all the success that it has had, there have also been some issues as well, which leads me to wonder, what else could we do here? Let step through some of those issues today and see where we could go.
Should It Be Its Own Language?
One of the highlighted concerns was the need to have yet another language. Creating and maintaining languages is a large effort, not to be undertaken lightly at any organization. To base your language on C# while adding additional constructs was a great way to get started and create some buzz and buy-in, but it also brought its own set of problems.
One problem is that it is an enormous effort to keep on par with the C# compiler and add these constructs on a continuing basis. The Spec# project, also based upon C# realized that it wasn’t feasible to keep up with the rapid pace of the language and instead went as a language neutral approach. Not only keeping up with the language, but to enforce many functional programming constructs that Axum embraces such as immutability and purity are harder to enforce given a language which is built upon object-oriented and imperative approaches, an approach which encourage the encapsulation and manipulation of state. So, instead of creating a separate language, why not fold these constructs into an existing language instead?
The Case For F#
Given the impedance mismatch between the C# language and the overall goals of Axum for a safe, isolated, agent-based system that is great for concurrency, why not consider another language such as F#? Now that F# is a first-class citizen within Visual Studio going forward, there can be a strong case made. Given some of the features of F#, which we will discuss, could potentially be a happy marriage with Axum. The F# language and its associated libraries have many of the constructs that are essential to an agent-based messaging system, including immutability (albeit shallow), encouraging side effect free programming, and library functions such as the mailbox processor messaging classes.
In Praise Of Immutability
In the world of concurrency we find that shared mutable state is evil. Often we have to protect certain parts by using low level constructs such as locks, semaphores, mutexes. Because of this, we find that most people tend to avoid concurrency programming as it tends to be too hard to get just right. Instead, communication through message passing in languages such as Axum and Erlang, immutability is the standard. This way, we can freely reference the values without any worry of whether they will change underneath us. Providing first-class support for immutability goes a long way towards making safe concurrency programming easier for the masses. With the F# language, we get that approach by default and with rich types such as records, discriminated unions, lists, tuples and more.
Of particular note, Discriminated Unions are quite useful in messaging systems to define the types of messages your system accepts. For example, we could model our auction messages quite easily using discriminated unions to define which interactions are legal, such as the following code:
type AuctionMessage = | Offer of int * MailboxProcessor<AuctionReply> | Inquire of MailboxProcessor<AuctionReply> and AuctionReply = | Status of int * System.DateTime | BestOffer | BeatenOffer of int | AuctionConcluded of MailboxProcessor<AuctionReply> * MailboxProcessor<AuctionReply> | AuctionFailed | AuctionOver
In this case, we have succinctly defined what messages can be processed. Adding to this, Axum, through the use of data-flow networks and channel protocols could be a nice compliment to determine how these messages are processed. Where else could they match up nicely?
Built For Concurrency
To talk about a potential marriage between F# and Axum, we need to talk about the language and its libraries and how they support concurrency. From first class events, to asynchronous workflows, to mailbox processors, F# has a wide array of asynchronous and parallel programming libraries available out of the box. In particular, the asynchronous workflows and the mailbox processor could match well with the Axum programming model. Interestingly, Luca Bolognese has built upon the mailbox processor for his LAgent framework to show some more interesting scenarios where agent based programming could work. This includes such things as advanced error handling, hot swapping, implementing MapReduce and so on.
With little effort, we can model such things as the standard ping-pong example using F# mailboxes:
let (<--) (m:MailboxProcessor<_>) msg = m.Post(msg) type PingMessage = Ping of MailboxProcessor<PongMessage> | Stop and PongMessage = Pong let ping iters (pong : MailboxProcessor<PingMessage>) = new MailboxProcessor<PongMessage>(fun inbox -> pong <-- Ping inbox let rec loop pingsLeft = async { let! msg = inbox.Receive() match msg with | Pong -> if pingsLeft % 1000 = 0 then printfn "Ping: pong" if pingsLeft > 0 then pong <-- Ping inbox return! loop(pingsLeft - 1) else printfn "Ping: stop" pong <-- Stop return () } loop (iters - 1)) let pong () = new MailboxProcessor<PingMessage>(fun inbox -> let rec loop pongCount = async { let! msg = inbox.Receive() match msg with | Ping sender -> if pongCount % 1000 = 0 then printfn "Pong: ping %d" pongCount sender <-- Pong return! loop (pongCount + 1) | Stop -> printfn "Pong: stop"; return () } loop 0) let ponger = pong() let pinger = ping 100000 ponger pinger.Start() ponger.Start()
And you’ll notice from all of this, there are no mutable values anywhere nor shared global state and all communication happens through message passing. We have certain limitations here such as we cannot remote these calls, so all interaction happens inside the single application. Not only that, but how do we enforce no shared state?
What Would It Look Like?
So, now that we looked at some of the reasons why F# and Axum might be a good marriage, what might it actually look like? That’s a great question! Some of the concepts from Axum could map perfectly to F# whereas some might need a little more coaxing. Let’s go back to the basic building blocks of Axum. They consist of the following:
- Agents and domains
- Channels
- Schema
- Networks
The first three items are concerned mostly with state isolation and the exchange of information between our isolated regions of our application, while the last item deals more with the how messages are passed.
The domain is the most basic isolation concept where all data is encapsulated and only constructors are exposed outside of the domain definition. Agents are defined to run within the isolated space of a domain with each agent on a separate thread of control. These agents are exposed to one another through passing messages back and forth via channels which define ports through which our data flows. The data that passes between our domains can be defined in a schema, similar in nature of XML Schemas, to define structure and rules of our data. Now to think about message passing, F# already has asynchronous behavior already built in to the mailbox processor, so we could take advantage here and build on top of it and our networks could guide us as to what order messages are passed.
Let’s look at some possible code examples of what things might look like. I’ll choose just a couple as they might work nicely out of the box. Let’s first look at how we might define a port which accepts a given message.
type ProductInput = Multiply of int * int | Done type ProductOutput = Product of int | AckDone
This way, we could define what our payload type for both incoming and outgoing. Another area would be to look how schemas might be done. In our earlier example, we used simple data types such as integers, but what about more complex types? Using F#, we could think of using records here to simulate the not only the data, but what is and is not required:
type PersonSchema = { Name : string Employer : string Age : int option } let matt = { Name = "Matthew Podwysocki" Employer = "Microsoft Corporation" Age = None }
By marking the fields we require as standard fields and those which are optional as option types works out nicely. Using F#, we’re able to have concise syntax with a language that is already defined and quite flexible.
Conclusion
As you can see from this post, a potential marriage between Axum and F# would certainly be a great fit. Instead of focusing on Axum as a separate language, focusing the effort on top of an existing language which matches many of the design goals can bear a lot of fruit. I believe Axum is important for the .NET programming stack, giving us more options on how to deal with concurrency and changing hardware architectures. What do you think?
|
http://codebetter.com/matthewpodwysocki/2009/09/25/pondering-axum-f/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+CodeBetter+%28CodeBetter.Com%29
|
crawl-003
|
refinedweb
| 1,506
| 58.11
|
Hi every body i am a new bie to MC9S08DN16 controller and i am facing problem in toggling the port the code is as below.
/* [sample program to toggle the port D of the micro controller ] */
#include <hidef.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */
void port_initialize(void);
void delay(void);
void main(void)
{
EnableInterrupts;
/* include your code here */
port_initialize();
while(1)
{
PTED = 0x00; /* flashing 0's on to port D */
delay(); /* delay function */
PTED = 0xff; /* flashing 1's on to port D */
delay(); /* delay function */
}
/* loop forever */
/* please make sure that you never leave main */
}
void port_initialize(void )
{
PTEDD = 0xff; /* port D data direction register configured as output */
PTEPE = 0x00; /* Internal pull-up/pull-down device disabled for port D */
PTESE = 0x00; /* Output slew rate control disabled for port D */
// PTEPE = 0x00; /* Port disabled as interrupt */
}
void delay()
{
unsigned int i,j;
for(i=0; i<255; i++)
for(j=0; j<255;j++);
}
The problem i am facing is that although the code is in infinate loop. when i run the program after few seconds the code will exit unexpectedly and will lead to a new window and displays the following.
#pragma NO_EXIT
__EXTERN_C void _Startup(void) {
/* set the reset vector to _Startup in the linker parameter file (*.prm):
'VECTOR 0 _Startup'
purpose: 1) initialize the stack
2) initialize run-time, ...
initialize the RAM, copy down init data, etc (Init)
3) call main;
called from: _PRESTART-code generated by the Linker
*/
INIT_SP_FROM_STARTUP_DESC(); /*lint !e960 MISRA 14.3 REQ, not a null statement (instead: several HLI statements) */
#ifndef __ONLY_INIT_SP
Init(); /*lint !e522 function 'Init' contains inline assembly */
#endif
#ifndef __BANKED__
__asm JMP main; /* with a C style main(); we would push the return address on the stack wasting 2 RAM bytes */
#else
__asm CALL main;
#endif
}
hi Vikas,
from your description, your program got reset when running in loop.
I wonder the reset was caused by COP. please try to add feed dog code inside for() loop:
for example:;
for(;;) {
... ...
__RESET_WATCHDOG(); /* feeds the dog */
... ...
} /* loop forever */
this can avoid watchdog reset.
=====================================================
this answer is for you. if it helps, please click on "correct answer " button. thanks!
Best Regards,
Jennie
|
https://community.nxp.com/thread/325154
|
CC-MAIN-2019-26
|
refinedweb
| 363
| 60.85
|
An ASP.NET project I'm working on requires localization in different languages. It's nice to use .NET Resource files (.resx), because they are really integrated with the framework and you do not have to worry about explicitly managing the resources. Resource files are, though, really un-maintainable. When you edit the resource files in Visual Studio, ore use the "Generate Local Resources" function, it only updates the default language resources. For example, the file Default.aspx.resx, and not all the translated files, for example, Default.aspx.it-IT.resx. This is obviously a big problem, since you have to update them one by one, manually. RESX Synchronizer allows you to synchronize resource files, adding new keys and removing the deleted ones. It also processes a set of resource files, the "master" file, and all its translated "brothers".
This tool uses the two classes
System.Resources.ResXResourceReader and
System.Resources.ResXResourceWriter, contained in the assembly System.Windows.Forms.dll. These classes allow to read and write .resx files, including comments.
We'll use the name of "source file" to indicate the "master" resource file, for example, Default.aspx.resx, and the name of "destination file" to indicate a "brother" resource file, for example, Default.aspx.it-IT.resx, which must be synchronized. The tool must perform two operations in order to get the files synchronized:
The core of the tool is the class
Synchronizer. Its code is reported here, and the concepts behind it are explained below.
public class Synchronizer { string sourceFile, destinationFile; public Synchronizer(string sFile, string dFile) { sourceFile = sFile; destinationFile = dFile; } public void SyncronizeResources(bool backup, bool addOnly, bool verbose, out int added,out int removed) { added = 0; removed = 0; if(backup) { string destDir = Path.GetDirectoryName(destinationFile); string file = Path.GetFileName(destinationFile); File.Copy(destinationFile, destDir + "\\Backup of " + file, true); } string tempFile = Path.GetDirectoryName(destinationFile) + "\\__TempOutput.resx"; // Load files in memory MemoryStream sourceStream = new MemoryStream(), destinationStream = new MemoryStream(); FileStream fs; int read; byte[] buffer = new byte[1024]; fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read); read = 0; do { read = fs.Read(buffer, 0, buffer.Length); sourceStream.Write(buffer, 0, read); } while(read > 0); fs.Close(); fs = new FileStream(destinationFile, FileMode.Open, FileAccess.Read, FileShare.Read); read = 0; do { read = fs.Read(buffer, 0, buffer.Length); destinationStream.Write(buffer, 0, read); } while(read > 0); fs.Close(); sourceStream.Position = 0; destinationStream.Position = 0; // Create resource readers ResXResourceReader source = new ResXResourceReader(sourceStream); // Enable support for Data Nodes, important for the comments source.UseResXDataNodes = true; ResXResourceReader destination = new ResXResourceReader(destinationStream); destination.UseResXDataNodes = true; // Create resource writer if(File.Exists(tempFile)) File.Delete(tempFile); ResXResourceWriter writer = new ResXResourceWriter(tempFile); // Compare source and destination: // for each key in source, check if it is present in destination // if not, add to the output // for each key in destination, check if it is present in source // if so, add it to the output // Find new keys and add them to the output foreach(DictionaryEntry d in source) { bool found = false; foreach(DictionaryEntry dd in destination) { if(d.Key.ToString().Equals(dd.Key.ToString())) { // Found key found = true; break; } } if(!found) { // Add the key ResXDataNode node = d.Value as ResXDataNode; writer.AddResource(node); added++; if(verbose) { Console.WriteLine("Added new key '" + d.Key.ToString() + "' with value '" + d.Value.ToString() + "'\n"); } } } if(addOnly) { foreach(DictionaryEntry d in destination) { ResXDataNode node = d.Value as ResXDataNode; writer.AddResource(node); } } else { int tot = 0; int rem = 0; // Find un-deleted keys and add them to the output foreach(DictionaryEntry d in destination) { bool found = false; tot++; foreach(DictionaryEntry dd in source) { if(d.Key.ToString().Equals(dd.Key.ToString())) { // Found key found = true; } } if(found) { // Add the key ResXDataNode node = d.Value as ResXDataNode; writer.AddResource(node); rem++; } else if(verbose) { Console.WriteLine("Removed deleted key '" + d.Key.ToString() + "' with value '" + d.Value.ToString() + "'\n"); } } removed = tot - rem; } source.Close(); destination.Close(); writer.Close(); // Copy tempFile into destinationFile File.Copy(tempFile, destinationFile, true); File.Delete(tempFile); } }
The two operations described above are implemented in the two
foreach cycles. The first one iterates over the source keys, searching for keys with the same name in the destination. If no key is found, then the current key in the source file is new, and must be added to the output (destination) file. The second cycle iterates over the destination keys, searching for keys with the same name in the source. If a key with the same name is found in the source file, then the key is still needed, and then it must be copied to the output. If no key is found, then that key has been deleted and therefore it is not copied to the output.
The
Synchronizer class is also able to:
The
Synchronizer class has been wrapped into a command-line tool, which parses the parameters and performs the synchronization using the class. The code of this utility is really simple, and therefore does not need to be reported.
Since the tool is still in a development stage, I don't want to report here the usage instructions which might be obsolete in a few days, so I point you to the official page of the tool, available at this address.
General
News
Question
Answer
Joke
Rant
Admin
|
http://www.codeproject.com/KB/dotnet/ResxSync.aspx
|
crawl-002
|
refinedweb
| 873
| 51.14
|
Adafruit CircuitPython Register library¶
This library provides a variety of data descriptor class for Adafruit CircuitPython that makes it really simple to write a device drivers for a I2C and SPI register based devices. Data descriptors act like basic attributes from the outside which makes using them really easy to use.
API¶
Creating a driver¶
Creating a driver with the register library is really easy. First, import the register modules you need from the available modules:
from adafruit_register import i2c_bit from adafruit_bus_device import i2c_device
Next, define where the bit is located in the device’s memory map:
class HelloWorldDevice: """Device with two bits to control when the words 'hello' and 'world' are lit.""" hello = i2c_bit.RWBit(0x0, 0x0) """Bit to indicate if hello is lit.""" world = i2c_bit.RWBit(0x1, 0x0) """Bit to indicate if world is lit."""
Lastly, we need to add an
i2c_device member of type
I2CDevice
that manages sharing the I2C bus for us. Make sure the name is exact, otherwise
the registers will not be able to find it. Also, make sure that the i2c device
implements the
busio.I2C interface.
def __init__(self, i2c, device_address=0x0): self.i2c_device = i2c_device.I2CDevice(i2c, device_address)
Thats it! Now we have a class we can use to talk to those registers:
import busio from board import * with busio.I2C(SCL, SDA) as i2c: device = HelloWorldDevice(i2c) device.hello = True device.world = True
Adding register types¶
Adding a new register type is a little more complicated because you need to be careful and minimize the amount of memory the class will take. If you don’t, then a driver with five registers of your type could take up five times more extra memory.
First, determine whether the new register class should go in an existing module or not. When in doubt choose a new module. The more finer grained the modules are, the fewer extra classes a driver needs to load in.
Here is the start of the
RWBit class:
class RWBit: """ Single bit register that is readable and writeable. Values are `bool` :param int register_address: The register address to read the bit from :param type bit: The bit index within the byte at ``register_address`` """ def __init__(self, register_address, bit): self.bit_mask = 1 << bit self.buffer = bytearray(2) self.buffer[0] = register_address
The first thing done is writing an RST formatted class comment that explains the
functionality of the register class and any requirements of the register layout.
It also documents the parameters passed into the constructor (
__init__) which
configure the register location in the device map. It does not include the
device address or the i2c object because its shared on the device class instance
instead. That way if you have multiple of the same device on the same bus, the
register classes will be shared.
In
__init__ we only use two member variable because each costs 8 bytes of
memory plus the memory for the value. And remember this gets multiplied by the
number of registers of this type in a driver! Thats why we pack both the
register address and data byte into one bytearray. We could use two byte arrays
of size one but each MicroPython object is 16 bytes minimum due to the garbage
collector. So, by sharing a byte array we keep it to the 16 byte minimum instead
of 32 bytes. Each
memoryview also costs 16 bytes minimum so we avoid them too.
Another thing we could do is allocate the
bytearray only when we need it. This
has the advantage of taking less memory up front but the cost of allocating it
every access and risking it failing. If you want to add a version of
Foo that
lazily allocates the underlying buffer call it
FooLazy.
Ok, onward. To make a data descriptor
we must implement
__get__ and
__set__.
def __get__(self, obj, objtype=None): with obj.i2c_device: obj.i2c_device.write(self.buffer, end=1, stop=False) obj.i2c_device.read_into(self.buffer, start=1) return bool(self.buffer[1] & self.bit_mask) def __set__(self, obj, value): with obj.i2c_device: obj.i2c_device.write(self.buffer, end=1, stop=False) obj.i2c_device.read_into(self.buffer, start=1) if value: self.buffer[1] |= self.bit_mask else: self.buffer[1] &= ~self.bit_mask obj.i2c_device.write(self.buffer)
As you can see, we have two places to get state from. First,
self stores the
register class members which locate the register within the device memory map.
Second,
obj is the driver class that uses the register class which must by
definition provide a
I2CDevice compatible
object as
i2c_device. This object does two thing for us:
- Waits for the bus to free, locks it as we use it and frees it after.
- Saves the device address and other settings so we don’t have to.
Note that we take heavy advantage of the
start and
end parameters to the
i2c functions to slice the buffer without actually allocating anything extra.
They function just like
self.buffer[start:end] without the extra allocation.
Thats it! Now you can use your new register class like the example above. Just remember to keep the number of members to a minimum because the class may be used a bunch of times.
|
https://circuitpython.readthedocs.io/projects/register/en/latest/
|
CC-MAIN-2017-39
|
refinedweb
| 868
| 64.91
|
import interfaces 17 from buildbot.process.properties import Properties 1819 -class BuildRequest:20 """I represent a request to a specific Builder to run a single build. 21 22 I am generated by db.getBuildRequestWithNumber, and am used to tell the 23 Build about what it ought to be building. I am also used by the Builder 24 to let hook functions decide which requests should be handled first. 25 26 I have a SourceStamp which specifies what sources I will build. This may 27 specify a specific revision of the source tree (so source.branch, 28 source.revision, and source.patch are used). The .patch attribute is 29 either None or a tuple of (patchlevel, diff), consisting of a number to 30 use in 'patch -pN', and a unified-format context diff. 31 32 Alternatively, the SourceStamp may specify a set of Changes to be built, 33 contained in source.changes. In this case, I may be mergeable with other 34 BuildRequests on the same branch. 35 36 @type source: a L{buildbot.sourcestamp.SourceStamp} instance. 37 @ivar source: the source code that this BuildRequest use 38 39 @type reason: string 40 @ivar reason: the reason this Build is being requested. Schedulers 41 provide this, but for forced builds the user requesting the 42 build will provide a string. 43 44 @type properties: Properties object 45 @ivar properties: properties that should be applied to this build 46 'owner' property is used by Build objects to collect 47 the list returned by getInterestedUsers 48 49 @ivar status: the IBuildStatus object which tracks our status 50 51 @ivar submittedAt: a timestamp (seconds since epoch) when this request 52 was submitted to the Builder. This is used by the CVS 53 step to compute a checkout timestamp, as well as the 54 master to prioritize build requests from oldest to 55 newest. 56 """ 57 58 source = None 59 builder = None # XXXREMOVE 60 startCount = 0 # how many times we have tried to start this build # XXXREMOVE 61 submittedAt = None 629764 assert interfaces.ISourceStamp(source, None) 65 self.reason = reason 66 self.source = source 67 self.builderName = builderName 68 69 self.properties = Properties() 70 if properties: 71 self.properties.updateFromProperties(properties)7273 - def canBeMergedWith(self, other):74 return self.source.canBeMergedWith(other.source)75 7879 - def mergeReasons(self, others):80 """Return a reason for the merged build request.""" 81 reasons = [] 82 for req in [self] + others: 83 if req.reason and req.reason not in reasons: 84 reasons.append(req.reason) 85 return ", ".join(reasons)86 87 # IBuildRequestControl 88 90 """Cancel this request. This can only be successful if the Build has 91 not yet been started. 92 93 @return: a boolean indicating if the cancel was successful.""" 94 if self.builder: 95 return self.builder.cancelBuildRequest(self) 96 return False98 - def getSubmitTime(self):99 return self.submittedAt100
|
http://docs.buildbot.net/0.8.3/reference/buildbot.buildrequest-pysrc.html
|
CC-MAIN-2014-52
|
refinedweb
| 473
| 59.4
|
Canonicalization
by Bilal Siddiqui
|
Pages: 1, 2
Only double quotes should be used to encapsulate attribute values in
canonical form. Have a look at Listing 4, where the
name attribute of the product element is
enclosed inside single quotes. In Listing 5, we have replaced
the single quotes around the name attribute value with double
quotes.
name
product
When we replaced single quotes with double quotes, we introduced a
problem in Listing 5. It
is no longer a well formed XML file, as the string representing value of
the name attribute already contained double quotes as part of the string
value. In order to solve this problem, the Canonical XML specification
requires that all special characters (e.g. double quotes) in attribute
values and element content be replaced with character entities
(e.g. " for double quotes). Listing 6 is the result of
applying this rule to Listing
5.
Listing 6 contains a
DTD declaration, which defines an entity named testhistory. The
testhistory entity is referenced by the comments element content.
Canonical XML requires that all entity references be replaced with the
content represented by the entity (e.g. in Listing 6, the
testhistory entity represents the string "Part has been tested
according to the specified standards."). Listing 7 is the resulting
XML file after entity references in Listing 6 have been replaced.
The DTD declaration in Listing 7 defines a default
attribute named approved for each part element. None of the
part tags in Listing 7 contains this attribute.
Canonical XML requires that default attributes should be included in
the canonical XML form. Listing 8 is the result of
including the approved attribute with default value in Listing 7.
Canonical XML does not require XML and DTD declarations. Therefore XML
and DTD declarations should be removed in the canonical form. Although we
have used the DTD declaration while replacing entity references and adding
default attributes, the actual XML and DTD declarations need to be removed
as shown in Listing 9.
A Canonical XML document starts with the '<' character. This means
that there should be no white space before the first node.
Start and End elements should have normalized white space in canonical
form. This means there should be:
Listing 10 is the result
of normalizing white space in start and end elements of Listing 9.
Canonical XML requires start-end tag pairs for all elements, which
includes empty elements as well. Therefore, all empty elements of the form
<emptyElement/> need to be converted to
<emptyElement></emptyElement>. Listing 11 shows the result
of applying this rule to Listing 10.
Listing 11 contains three namespace declarations, two in the
product element and one in the second part
element. Canonical XML requires preserving all namespace declarations as
such (along with the namespace prefixes) except superfluous namespace
declarations (those namespace declarations that have no effect on the
namespace context of any node in the XML file).
The namespace declared in the second part element in Listing 11
is superfluous. You can remove it from the element with no effect on the
namespace context of any node in the file. That's why Listing 12 does not include
this namespace declaration, while preserving the rest of Listing 11 as such.
Canonical XML requires the inclusion of namespace declarations and
attributes in ascending lexicographic order. Inside an opening element,
all namespace declarations should appear first, followed by the
attribute-value pairs. Listing 13 shows how Listing 12 will look like
after the ordering rule is applied.
Listing 13 is the final
canonical form of all listings from 3 to 12.
Just to give you a bit of variety, we have provided another example in
the Listing 14 and 15 pair (Listing 15 is the
canonical form of Listing 14). We didn't produce Listing 15 by hand. We
rather generated it using the Canonical XML implementation by IBM
alphaWorks, which is part of their XML Security Suite (refer to
resources). However, curious readers may start with Listing 14 and follow the
thirteen steps described above to arrive at Listing 15.
Note: There is no DOCTYPE declaration in Listing 14. Therefore, some
of the canonicalization steps such as replacing entity references and
adding default attributes are not relevant in this case.
In the second article in this series, we will take this concept
further and discuss more advanced concepts such as dealing with parts of
XML documents, CDATA sections, comments and processing instructions. We
will also discuss tricky situations where canonicalization process renders
XML documents uesless for their intended function.
© , O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
|
http://www.xml.com/pub/a/ws/2002/09/18/c14n.html?page=2
|
CC-MAIN-2014-10
|
refinedweb
| 779
| 55.24
|
This tutorial is a simplified, or at least condensed, version of the equivalent tutorial pages on developer.android.com, which are mostly fine, but they aren’t quite brainless enough to suit me. Plus, for the latest version of Android there was a missing step in there that made it impossible to create a new Android Virtual Device, so I’ve incorporated the fix for that as well.
- Download and install the Java Development Kit (JDK). As of this writing, the latest version of the installer is available at ““.
- Download and install (or rather, extract) Eclipse. Eclipse is an open-source IDE (integrated development environment) that allows users to develop software in a variety of languages, and on a variety of platforms. As of this writing, a .zip file for the Windows version of Eclipse can be downloaded from ““. Select the “Eclipse Classic” item from the list.
- Download and install the Android SDK Starter Package. As of this writing, the SDK is available at ““. When the installation is complete, the installer will automatically load the SDK Manager, and a list of packages that can be installed will be displayed.
- On the Android SDK Manager, click the Install button to install the recommended packages, which should be pre-selected. After the packages are downloaded (which seems to take quite a while), close the SDK Manager.
- Navigate to the directory to which Eclipse was installed and double-click the file “Eclipse.exe” to run it. A dialog will appear prompting for the “workspace” to use for this session. Click OK to accept the default and dismiss the dialog.
- Once Eclipse has loaded, select the “Help – Install New Software…” item from the main menu. The “Install” dialog will appear, and the first page of the dialog, named “Available Software”, will be visible.
- On the Available Software page, click the Add button. The “Add Repository” dialog will appear.
- On the Add Repository dialog, enter the value “ADT Plugin” in the Name box and ” ” in the Location box, then click the OK button. Focus will return to the Available Software page, and a new item named “Developer Tools” will be available in the list box.
- Click the checkbox next to the Developer Tools item to select it, then click the Next button. The dialog will advance to the next page, named “Install Details.”
- On the Install Details page, review the items in the list and click the Next button. The dialog will advance to the next page, named “Review Licenses”.
- On the Review Licenses page, click the radio button labeled “I accept the terms” and click the Finish button. The Install dialog will disappear, and a new dialog named “Installing Software” will appear. The ADT plugin will load.
- When the plugin finishes loading, click the “Restart Now” button to restart Eclipse. Wait for Eclipse to restart, then click OK on the Workspace Launcher dialog to accept the default workspace (again).
- Once Eclipse has started, a dialog may appear titled “Welcome to Android Development”. Click the Next button on this dialog (and on the next page, which just asks whether Google can gather statistics on your usage of the SDK). Yet another dialog will appear.
- Click the Install button on the latest dialog to download and install the latest version of the Android SDK files.
- Once everything has finished loading and focus has returned to the Eclipse environment proper, select the “Window – AVD Manager” item from the main menu. A dialog named “Android Virtual Device Manager” will appear.
- On the Android Virtual Device Manager dialog, click the New button. The “Create New Android Virtual Device”, will appear.
- On the Create New AVD dialog, enter the value “AVDTest1” in the Name box, then select the appropriate value in the Target box. For this example, the value “Android 4.0.3 – API Level 15” was selected.
- Click the Create AVD button to create the AVD. The dialog should disappear, and focus will return to the parent dialog. If clicking the Create AVD button causes an error that says something like “unable to find a ‘userdata.img’ file for ABI armeabi” to appear in the Eclipse console pane, proceed to the next step.
- If an error occurs when clicking the Create AVD button, it may be necessary to select the “Run – Run Configurations” menu item to bring up the Run Configurations dialog, double-click the “Android Application” node in the tree view in the left pane to create a new configuration, click the Target tab in the right pane, click the “Automatic” radio button (even though it’s already selected), and then click the OK button. After that, it should be possible to create the AVD as described in the preceding steps.
- From the main menu, select the item “File – New – Project”. The New Project dialog will appear.
- On the New Project dialog, select the “Android – Android Project” tree node and click the Next button. The dialog will advance to the “New Android Project” page.
- On the New Android Project page, enter the value “HelloWorldAndroid” in the Project Name box and click the Next button. The dialog will advance to the “Select Build Target” page.
- On the Select Build Target page, accept the default target by clicking the Next button. The dialog will advance to the “Application Info” page.
- On the Application Info page, enter the value “com.example.HelloWorldAndroid” in the Package Name box and click the Finish button. The dialog will disappear, a new project will be created, and focus will return to the Eclipse workspace.
- In the Package Explorer pane, click on the “src” tree node, then the “com.example.HelloWorldAndroid” node underneath it, and then double-click the HelloWorldAndroidActivity.java” node underneath that to open it.
- Replace the contents of the HelloWorldAndroidActivity.java file with the following text, then save the file. This code is based on the sample on developer.android.com, with very slight modifications.
package com.example.HelloWorldAndroid; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloWorldAndroidActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView txtHelloWorld = new TextView(this); txtHelloWorld.setText("Hello, world!"); setContentView(txtHelloWorld); } }
- Select the “Run – Run” item from the main menu, select the “Android Application” item from the dialog that appears, and click the OK button. The Android emulator will start and boot (which may take a surprisingly long time), and then display the “Hello, world!” message.
Notes:
- As previously stated, this tutorial is basically a digest of information on developer.android.com. If the Android folks change the way things work a lot (which they pretty much do every release, apparently), it may render this tutorial invalid. Or at least less valid.
- I found the workaround for the “can’t create an AVD” problem at “tech.thecoolblogs.com/2012/01/unable-to-find-userdataimg-file-for-abi.html”. I dunno, I guess it’s a pretty “cool blog”, but judging by the posts on the homepage, it seems kind of fakey/spammy/sleazy to me. Specifically, this week’s posts are about the nature of God, Epicurus, meditation for smoking cessation, free “antivirus” software, and printing free coupons right at home for big big savings! Anyway, credit where credit’s due, but I’d be afraid that they’re going to p0wn your box or something if you paste that link into your address bar. Or maybe I’m just being hypocritical. I mean, I have a sleazy blog of my own, after all. But at least mine’s on a relatively trustworthy domain, right?
- A change to how wordpress.com works at some point made the sleazy link from that last list item live and clickable, so I had to remove the “http” protocol prefix to prevent that. Way to go, powers that be.
- Sigh… Eclipse still has “workspaces”. They just won’t let it go.
Advertisements
Thanks for the clean explanation.. This website also addresses something similar.. Have a look, may help..
Pavan @ ( Pavanh )
Thank you for this tutorial , you can also check the same @ android hello world
|
https://thiscouldbebetter.wordpress.com/2012/05/19/hello-world-in-android-using-eclipse/
|
CC-MAIN-2017-13
|
refinedweb
| 1,349
| 66.33
|
How to Toggle Sound Globally (AS2)
Flash is a great medium for presenting sound, whether narration, music, or basic UI clicks and whirs. That said, it’s a good idea to provide a way for people to toggle sound off, if they prefer silence. You may have heard or read about the global
stopAllSounds() function. It’s good in a pinch, because it does exactly what its name implies: any sound currently playing is abruptly shut off. Of course, additional audio in subsequent frames continues to be heard. If other buttons are wired to produce sound, they continue to do so when clicked.
stopAllSounds() isn’t a toggle, it’s just an immediate silencer.
This topic comes up a lot in the forums, actually. You may have heard about using the
Sound class to trigger sounds with ActionScript. It’s possible in this way to check against a single, globally accessible Boolean variable before invoking
Sound.start(). Naturally, this means that every last sound in your SWF would have to be programmed, which may be a daunting prospect. Personally, I’m a fan of the
Sound class. It’s great for games and ActionScript-based presentations, but there’s certainly something to be said for the drag-and-drop utility of placing sound assets by hand in a timeline. So … is there an easy way to toggle these sounds (any sounds) off — and then on again? You betcha.
An answer, short and sweet
Add the following to frame 1 of your scripts layer.
var globalVolume:Sound = new Sound();
I know, pretty short, right? This allows you to adjust the volume of the whole SWF from two buttons. Assuming the instance names
btnSoundOff and
btnSoundOn …
btnSoundOff.onRelease = function():Void { globalVolume.setVolume(0); } btnSoundOn.onRelease = function():Void { globalVolume.setVolume(100); }
How it works
A variable is declared with the arbitrary name
globalVolume. This points to an instance of the
Sound class, so the declaration includes the
:Sound suffix. The
Sound instance is generated by the constructor
new Sound(), which is built to accept an optional parameter (a reference to a movie clip) — but since it’s optional, we’re leaving it out. Why? When the parameter is omitted, the
Sound instance governs audio across the whole SWF.
The buttons simply invoke the
Sound.setVolume() method on our
globalVolume instance. Enter
0 to silence the SWF and
100 to unsilence it.
Variation
Two buttons are fine, but often enough, you see a single button that handles the whole procedure. Let’s see how to accomplish that. All we need is a Boolean to keep track of what state we’re in: volume on or off.
var volumeOn:Boolean = true; var globalVolume:Sound = new Sound(); btnSoundOff.onRelease = function():Void { if (volumeOn) { globalVolume.setVolume(0); } else { globalVolume.setVolume(100); } volumeOn = !volumeOn; }
The
if statement could be written like this …
if (volumeOn == true) { … };
… but the shorter version makes just as much sense: all an
if statement does is evaluate an expression to decide if the result is
true or
false — which are precisely the two values
volumeOn returns.
Note that if
volumeOn returns
true,
globalVolume.setVolume() is set to
0 and vice versa, but in all cases, the value of
volumeOn is set to its own opposite. The logical NOT operator (
!) handles that part (
volumeOn equals not-
volumeOn; in other words, whatever
volumeOn isn’t).
May 12th, 2006 at 10:23 pm
I don’t think people really pay much attention to the optional target parameter. A lot of the time, people have multiple sound objects using new
Sound(). And then they try to change the volume of one and the rest of them change!
Here’s another way to write the toggle button:
May 13th, 2006 at 2:25 pm
NSurveyor,
That’s very cool! Done that way, you don’t even need the
volumeOnvariable I used in my example.
Here’s how this one works, starting from the inside out.
Sound.getVolume()returns the value of a
Soundinstance’s current volume. By default, volume is 100, so the first time this button is clicked, the value of
globalVolume.getVolume()is 100.
This number is added to 100, which makes 200. This sum (inside parentheses) is evaluated against the number 200 by way of the modulo operator (
%); in other words, the expression now under evaluation is 200 % 200. Modulo calculates the remainder of one number is divided by another. In this case, 200 is divided by 200, which leaves a remainder of 0. Therefore,
globalVolume.setVolume()is fed the parameter 0, which silences the audio.
The next time this button is clicked,
globalVolume()returns 0, which is added to 100. This sum is divided by 200, which leaves a remainder of — well, wait a minute! 100 / 200 is 0.5. There is no remainder, but the division does not resolve to an integer. In ActionScript, it looks as if any number modulo a number higher than itself equals the number it was before the operation. So, here
globalVolume.setVolume()is once again set to 100.
Pretty slick programming!
May 13th, 2006 at 3:14 pm
Thanks… and if you think about it… 100/200 = 0 R100.
The a%b = a when a is less than b is not always true… (well, because of negatives)
(-3) % ( 2) = -1
(-3) % (-2) = -1
(-3) % ( 4) = -3
(-3) % (-4) = -3
The sign of a%b matches the sign of a.
And of course, when b=0, you get NaN…
alert(”uhoh”)
May 13th, 2006 at 3:32 pm
And here’s an easier way… should’ve thought of this earlier
When the volume is 0, it becomes 100-0 or 100, and when the volume is 100, it becomes 100-100 or 0.
May 14th, 2006 at 6:30 pm
There are a million ways of writing this!
May 15th, 2006 at 8:21 am
Yup, makes perfect sense.
These are creative solutions, NSurveyor. What I like about these is that you’re using the resources given — namely,
Sound.getVolume()and a variety of operators — and using them succinctly to accomplish a goal.
June 6th, 2006 at 10:38 pm
Here’s another one:
June 18th, 2006 at 4:31 pm
Hi David,
Is there any way I could put all of that script into the buttons themselves? I’ve tried a bajillion varients on the code above, and I can’t seem to get it to recognize my instances. Is there anyplace i can find a fla example of this?
Thanks!
Conan
June 18th, 2006 at 5:55 pm
Conan,
You certainly could put the button code directly on your buttons — and I’ll show you how to do that — but the instance name approach is a fundamental skill. To my thinking, you should do what it takes to understand how that works. Fortunately, there’s nothing to it, in this case. It all comes down to paths. If your ActionScript is in the main timeline and your button is, too, then you simply need to reference the button’s instance name. If the button is nested inside a movie clip, you must reference the movie clip’s instance name first as part of your path, and then the button’s instane name. My hunch is that your paths are wrong, somehow.
Since you asked, here’s the other way to do it — the older way. Keep in mind, the
on()event handler is a Flash 5-era mechanism. It still works, but it’s not on the list of current best practices.
As before, instantiate the
Soundclass first, in a frame of the main timeline.
Then, on each of your buttons …
September 19th, 2006 at 5:27 am
I’ve placed a sound clip on the OVER frame of a button, (inside the button). So when ever the mouse goes over it plays. Likewise im planning to have different clips played here and there.
I tried your code but it just doesn’t seems to solve the problem. It stops the background music but when ever i go above the buttons it sounds.
May its not effecting the upper level, please help me.
September 19th, 2006 at 7:18 am
Uchitha,
Wow, good find! I’m surprised at Flash, but you’re absolutely right: button timeline sounds seem to be immune to global volume settings. Here’s how you can work around it.
Note the Boolean variable,
volumeOn, in the Variation above. You can use that same variable to give your buttons a way to check if they should play or not. Keep using the original
Soundinstance to control your global volume, and instantiate a second
Soundobject to hold your button sound effects. You could use the variable name
sfxfor that. Make sure each button has an instance name (say,
button1).
Those three Button events represent their corresponding button symbol frames. You can use that same
sfxvariable for all your buttons. Each time, you’re simply invoking the
Sound.attachSound()method, to attach a sound from your Library, then the
Sound.start()method to play the attached sound.
Make sure you set a Linkage id for each sound in the Library you intend to trigger in this way.
One last step. Remember that Boolean variable? Assuming you’ve used the Variation above the
volumeOnvariable will either be
trueor
falsedepending on the global volume setting. Use an
ifstatement in your button event handlers to test whether or not to play …
September 23rd, 2006 at 5:36 am
Thanks
for help, it works now !
September 23rd, 2006 at 8:51 pm
Glad to help, Uchitha.
December 14th, 2006 at 6:10 pm
This saved my life. I’ve been looking for a mute function that works all day. This is SO easy and quick! Just wanted to thank you!
KC
January 10th, 2007 at 3:05 am
Great post,
thx
VD
January 19th, 2007 at 5:17 pm
I’ve been looking for this, but in slider form. Thoughts?
January 19th, 2007 at 6:45 pm
mike,
A slider suggests more of a gradual change to me than a toggle. But either way, if you want to adjust the volume for your whole movie, the key is simply to instantiate a
You could have your slider set the
Soundinstance, as above, without the optional target parameter — see details in “Understanding the Sound Contructor.” The instance name (the variable’s name) doesn’t make any difference, but I like to give variables descriptive names, and
globalVolumefits the bill.
Sound.setVolume()method to any number between zero and 100, and as long as your Sound instance applies to the whole move — thanks to the absent constructor parameter — you’re good.
March 17th, 2007 at 9:08 am
Just wanted to thank you for a great post! Been using this for several projects of mine. However, I just encountered a little problem.
When loading external swf’s into my main movie clip the sound toggler doesn’t quite work as intended. It can turn the sound off for the current swf, it can turn it on if it was muted from start. BUT if turning off the sound on the particular page, it wont start play again if i turn it on, unless I reload my page. Any solutions for this? (if i manage to make myself understood here ^^)
Also I was checking around YouTube at the same time i was looking at my website and toogled the sound off on my site, and the sound of the YouTube movie, in another firefox tab also stopped playing o.O
March 17th, 2007 at 1:02 pm
Mikaela,
I’m not sure I fully understand your issue, but I’ll try to reply.
The ActionScript I showed adjusts the volume for the whole movie (that is, a SWF). It doesn’t pause or restart sounds. Those continue playing (or not) on their own, as if nothing had happened. The volume control is very much like temporarily turning off your speakers. If your loaded SWFs contain sounds triggered by a keyframe (just for example) and you turn down the volume in the main SWF, that keyframe in the loaded SWF may pass. When you turn up the volume again, that passed sound will only occur again if its triggering keyframe is visited a second time by the playhead. Does that make sense?
I’m curious about your YouTube experience, for sure. As far as I know, the ActionScript I showed shouldn’t affect the volume of SWFs on another page.
March 17th, 2007 at 11:40 pm
Yea, I know that it works as if you turn down the volume of your speakers but i kind of hope there was a way around this, but what you describes makes fully sense so i guess there isnt
Yea, i was pretty surprised myself. And plus it didnt only stop the sound - it also paused the movie playing in YouTube :S
April 17th, 2007 at 1:33 am
Thanks dude… I’ve spent like 2 hours trying to figure this out. You’re my savior. Great tutorial!
April 17th, 2007 at 10:03 pm
Kyle,
Rock on!
April 17th, 2007 at 10:28 pm
Thank you so much!!! I’ve been hunting for hours trying to find something with these results.
I added a fade to mine. Works great. Thanks.
April 17th, 2007 at 11:01 pm
Jeremy,
Glad to hear it!
April 20th, 2007 at 4:22 am
I only found this after I created a whole sound manager system. Although the manager does allow sounds to be paused (they fade out to a pause) and started up again from the last point as well as a bunch of other functions like force starting sounds (cos of flash bugging out in complicated sites). But I really wish I’d seen this post first. Woulda negated me having to fade out each sound individually.
Nice code-wars on the toggle button:)
April 23rd, 2007 at 12:09 pm
Hey two questions:
–You guys are talking about fading the sound, that sounds awesome, how do you do that?
–When I’ve used this I’ve created a movieclip with frames showing on and off, and I’ve had the AS toggle between them. Would there be a way make a parameter to tell it that if the volume=100 to show the onframe and vice versa?
April 23rd, 2007 at 10:32 pm
Casey,
To fade sounds, you update your volume over time. You could use, say, a
MovieClip.onEnterFramehandler or
setInterval()to invoke
Sound.setVolume()repeatedly on an instance and increment/decrement the value until you hit the desired volume. For example, this would fade in an existing instance,
s, from zero to one hundred, counting by fives:
As for showing one keyframe or another — I assume these keyframes are part of a movie clip “button,” right? — just invoke the
Sound.getVolume()method to determine the volume. If this button has an
onReleasehandler, and contains frame labels “toggle off” and “toggle” on, with a
Soundinstance named
s…
April 24th, 2007 at 4:25 pm
Cool.
I’m not sure what I’m doing wrong on the sound fade. I’m using the global volume paramater for S, is that big no no?
April 25th, 2007 at 10:05 am
Hey just wanted to say thanks for the great work above to everyone else that contributed via comments, but mostly to David as you saved me a lot of potential baldness!
Be Exellent to each other!
April 25th, 2007 at 11:57 pm
To Casey …
Not sure what you mean by “global volume” parameter. In the above sample code, the letter “s” represents a
Soundinstance; that is, it’s a variable,
s, declared earlier — not shown in the my reply sample code. A more complete sample might be …
To Alan Fair …
Party on!
April 26th, 2007 at 11:55 pm
Thanks David!
I got everything to work! If folks like you don’t understand, while many of us are learning a full understanding of AS you folks help us understand and acheive goals big and small and we appreciate it.
Thanks again.
April 29th, 2007 at 8:27 am
Hi David,
I have a movie in which there are several movie clip symbols containing sound and visuals. I move from obe clip to the next by loading the appropriate movies into the main timeline using the attach method –
this.target_mc.attachMovie(mcName, “target_mc2″, 0)
I have tried a variety of ways to try to control the volume using the methods you described above without success. I can control the volume if the sound and visuals reside on the main timeline but this creates a host of other problems. Is there a method by which the volume for embedded movie clisp can be controlled?
May 1st, 2007 at 3:09 am
Chris,
Once the Library clip is attached, it becomes available to ActionScript via its instance name. Rather than constructing a
Soundinstance associated with the whole movie, as shown in the original article, you could construct your
Soundinstance and pass in, as a parameter, the instance name of the newly attached movie clip. That will associate the
Soundobject with that clip, controlling its audio.
May 7th, 2007 at 12:00 pm
Hi,
I’ve found your posts on using sound in Flash extremely helpful. I am struggling with a challenge that I’m sure is a pretty common procedure.
I have created a global sound object, to which I am attaching various sound files throughtout a Flash presentation. Essentially, there is a sound file associated with a scene. Within the scene I want to sync simple animations (image fades from one to another) with specific points in the sound file. I understand the theory of the position property, but I am having trouble making it useful in a script that will basically state:
When the sound reaches a position of 5 seconds, advance the playhead.
I have a global variable named “narration” which is where my Sound object lives.
I use the following statement on an earlier frame:
narration.attachSound(”01-01″);
narration.start(0,0);
The sound begins playing.
I want to stop the playhead at a subsequent frame, and place a command that only advances the playhead when the sound’s position reaches a certain point.
I’ve tried something like this:
stop();
if (narration.position/1000 == 5) {
play();
}
I need a function or command that I can reuse several times per sound file.
Any guidance you can provide would be fantastic.
May 13th, 2007 at 8:10 pm
Chris,
My first inclination, here, is to send you to my cue points article on Adobe.com. The article walks you through a way to associate cue points with MP3 files in both ActionScript 2.0 and 3.0. My editor recently asked me to update that article, because I originally wrote it for the public alpha version of Flash, which is no longer available. If you’re coding in AS2, it won’t matter; if you’re coding in AS3, you can probably still get all you need out of the article, but I do plan to update it as soon as I find a moment.
June 7th, 2007 at 1:47 pm
A method to fade the sound:
var globalVolume:Sound = new Sound();
function globalMusicVol(target:Number):Void {
var temp:Number = new Number(globalVolume.getVolume());
this.createEmptyMovieClip(”fader”, this.getNextHighestDepth());
fader.onEnterFrame = function() {
if (target>temp) {
temp += Math.ceil((target-temp)/10);
} else {
temp += Math.floor((target-temp)/10);
}
globalVolume.setVolume(temp);
trace(temp);
if (temp == target) {
delete this.onEnterFrame;
}
};
}
Then simply call the function and the target sound on the button, for example:
globalMusicVol(100)
… to make it become full volume.
June 7th, 2007 at 7:41 pm
Ryan,
Thanks for the input!
I use a technique similar to this myself. The only thing I would suggest is to omit the re-instantiation of
fadereach time the function is called (no need to create a new movie clip object every time, especially if it’s only being used for its
onEnterFrameevent) — or do away with the new extra movie clip altogether by looping on
setInterval().
July 3rd, 2007 at 8:32 pm
very nice comments from both the editor and Ryan…creating a movieclip containing in second frame the loop and fading in/out with ryan’s script from the main timeline helped me solve the problem i had with sound looping gaps between loops by using the edit envelope for the sound in second frame….
thx guys….helped a lot here.!….
July 5th, 2007 at 12:37 am
cafeine,
Glad to hear it!
July 5th, 2007 at 3:16 am
I’m trying to fade down/mute the background music sound when playing the flv using the Netstream object, so the FLV file audio is the only one being heard. When pausing the audio or getting out of the video page.. background music sound is fade up/unmute.
In shortwords, separating the background music with the Video music, so either or sound is heard. Not both
Thanks..
July 5th, 2007 at 7:18 am
TicoXX,
To control sound for individual objects in ActionScript 2.0, you’ll need a separate movie clip for each source of sound. For video, in particular, you’ll want to read “How to Adjust the Audio Portion of Flash Video.”
July 16th, 2007 at 9:33 am
Hi there.
Is there anyway to make a global volume SLIDER?
For instance, I have a slideshow, of 100 slides.
I would like the user to be able to adjust one slider once and have it affect the volume of all slides.
thanks!
July 16th, 2007 at 1:19 pm
Mike,
Sure thing. A slider would operate along the same lines as as the progress bar/scrubber described here: produce two movie clips (a knob and a track), and note the ratio of the knob’s distance across the track. Use that ratio to determine a number between 0 and 100 to use as the
Sound.setVolume()method’s parameter. I’ll do up a blog entry on this topic.
July 25th, 2007 at 10:57 am
Mike,
Quick update: the slider blog entry is here. kweku asked for pretty much the same thing, and I had forgotten you were also interested. In your case, you won’t need the video portion mentioned at the bottom, but it should be pretty easy to see how you can modify it for a
Soundinstance.
August 5th, 2007 at 3:57 pm
Hello everyone. This is going to sound a little naive, but how do I start a .SWF file with the sound off, then when I hit play, the sound plays from that point in the .SWF
Thank you so much!
August 5th, 2007 at 7:01 pm
Rick,
Check out “How to Pause Sound and Resume Where it Left Off.”
August 5th, 2007 at 8:23 pm
David,
Thanks for that. However, how do i start with the sound off? I only want the sound to play when the viewer clicks the sound button. However, I want the movie to continue playing and the viewer can watch the movie. The sound picks up in the correct spot so that it matches the video.
August 5th, 2007 at 8:47 pm
Rick,
If you’re using the trick above to silence the whole SWF at once, then you’ll set your
globalVolume’s volume to 0 before starting any other sounds. At that point, start your other audio (or FLV video, or whatever) and when the sound picks up — because, say, the user clicks a button — set the
globalVolume’s volume to 100. The audio will match the video (or your timeline, or whatever) because those other sounds will have been playing all along — it’s just that your “global volume knob” will have been turned down. Make sense?
August 5th, 2007 at 11:27 pm
David
I must be doing something wrong. I’ve got three layers.
1 layer is sound file;
2 layer has this code in frame 1:
var globalVolume:Sound = new Sound();
August 6th, 2007 at 7:06 am
Rick,
In a script layer in frame 1, use this:
Now your movie is prepped, and the “global volume knob” has been turned all the way down. As your timeline progresses — or as you otherwise start new sound (e.g. other
Soundinstances) — use this …
… to turn up the global volume.
August 13th, 2007 at 11:17 am
Hi, would like to reply an old post here
on 17 march 2007 Mikaela wrote
“…Yea, i was pretty surprised myself. And plus it didnt only stop the sound - it also paused the movie playing in YouTube :S”
This problem hits so many Flash developers. The solution we found here is, if you create a sound object like
my_sound = new Sound();
my_sound.attachSound(”bg_music”);
and you want to stop it without causing problem to your flv and other sound object, you have to do it the following way
my_sound.stop(”bg_music”); //This one works
my_sound.stop(); //This one stops everything, including flv
Hope this help
Regards,
GC
September 2nd, 2007 at 2:06 am
hi!
is there a way to toggle sound using your keyboard (for example, the s key) instead of using a button? it would be fantastic if someone could help with this! thanks
September 3rd, 2007 at 9:42 am
To GaryC …
I may have misunderstood Mikaela’s question, but I thought the issue in that post was that Mikaela’s code seemed to stop not only the audio in the desired SWF, but also in a completely different SWF in a separate Web page (a YouTube video). That’s what struck me as odd. Your comment about the optional parameter in Sound.stop() is helpful, in any case. Thanks!
To varty …
Sure thing. In order to accomplish that, you’ll handle the
Key.onKeyUpevent, rather than the
Button.onReleaseor
MovieClip.onReleaseevents. The syntax is a bit more wordy, but here’s a quick example:
In the above, the letters p (“play”) and s (“stop”) cause the volume to be set to 100 or 0, respectively. In this case, you need an “ambassador”
Objectinstance to act as your liaison, instead of assigning the function directly to a button object. That kind of makes sense here, because keystrokes aren’t really tangible objects like button or movie clip symbols.
The
listenerobject, then, stands in for the
Keyclass and has a function assigned to its
onKeyUpproperty. When a key is lifted (after it has been pressed), a series of
ifstatements test to see which key was the last to be pressed; this is afforded by the static
Key.getCode()method. The numbers 80 and 83 correspond to “p” and “s” (search “Keyboard Keys and Key Code Values” in the Help docs to see the full list).
September 11th, 2007 at 10:00 am
How would I automatically mute the sound when the animation gets to a certain keyframe and then when it exits that keyframe i would like it to unmute and continue playing
(this is for a site that has background music and on 1 page it has a video where i want to stop the background music until they go to the next page where the background music will start up again
September 15th, 2007 at 7:18 pm
Hardik,
For something like that, rather than invoke the
Sound.setVolume()method in response to button clicks, you’ll want to invoke that method from a keyframe. In frame one, for example, put this:
var globalVolume:Sound = new Sound();
Then in frame 250 (or whatever) reference that
globalVolumeobject and call its
setVolumemethod:
globalVolume.setVolume(0);
At a yet later frame (500, say), add another keyframe to your scripts layer and turn the volume back up:
globalVolume.setVolume(100);
But keep in mind: the technique shown in the original blog entry is a for setting volume globally. If you want to adjust the volume of the background music only, you’ll have to associate that Sound object with a unique timeline, because in ActionScript 2.0, timelines (movie clips) are effectively your sound channels. See “Understanding the Sound Constructor.”
October 8th, 2007 at 10:20 am
Ok.. this rocks!
Tnx David and all that camed with different solutions…
but i have a question.. i use these code for a banner. and the first time it plays evrething works incredible fine.. but when it plays again i can’t hear the music anymore
Any solutions pls.. these will help me right now…
Thx
October 8th, 2007 at 10:25 am
neah.. nevermind.. it was a silly thing.. i solve it…
)
so complety easy.. just a loop
tnx anyway
October 8th, 2007 at 2:07 pm
luce,
Glad you found the fix, and glad you liked the tutorial!
October 10th, 2007 at 11:38 am
Hi I use your script without any problem, the only problem I think so its when y play a FLV with the basic controller of flash 8 o 9 they mute too it’s correct this or maybe is something rong i did, the music it’s a mp3 file in the timeline with the option stream and loop. Thanks in advance.
October 10th, 2007 at 12:06 pm
rick,
The ActionScript suggested in the original article describes a way to toggle a SWF’s sound globally. Effectively, it allows you to “turn down the volume knob” on the whole movie, which would indeed mute any FLV content in that same SWF. If you want to toggle the MP3 itself, make sure to associate your
Soundconstructor with a timeline (a movie clip) that isn’t the main timeline. You can read more about this distinction in “Understanding the Sound Constructor.”
October 23rd, 2007 at 2:35 pm
Had a question regarding a specific project I’m trying to get some global sounds for. Essentially it’s 24 diff movies w/in a navigation system. There is a prev-play/pause-next set of buttons that will do what they say (like a dvd player).
I’m trying to get a global audio mute button to work and am not sure if the code suggestions above will apply to this situation. See each of these movies (1-24) have their own narration audio files embedded in the timeline.
There are also some audio controls associated with the prev-play/pause-next buttons:
PREVIOUS BUTTON:
on (release) {
stopAllSounds();
this._parent.prevFrame();
}
PLAY BUTTON:
on (release) {
//navigationStop();
//stopAllClips();
stopAllMovies(_root);
}
NEXT BUTTON:
on (release) {
stopAllSounds();
this._parent.nextFrame();
}
What do you guru’s suggest? I can of course supply more info if needed.
Project is here:
Thanks!
October 23rd, 2007 at 3:28 pm
Andy,
The code outlined in the article should have you covered.
It’s like a volume control on your main amp. Doesn’t matter how many instruments or microphones are plugged into it: when the main volume is turned down (or turned off), nothing is heard.
I’m not sure what your
stopAllMovies()function does … that’s got to be a custom function, because there isn’t a native
stopAllMovies()function or method in ActionScript. But I’m guessing that’s already taken care of?
October 23rd, 2007 at 4:41 pm
Nevermind! Got it taken care of. Many thanks gents!
October 23rd, 2007 at 7:00 pm
Thanks David. How’d you know I was a musician…more specifically a guitarist?
Your amp analogy makes perfect sense. I ended up getting it all squared away in the end. Feel free to delete the long entry I had.
October 23rd, 2007 at 8:16 pm
Andy,
Haha … lucky guess about the musician metaphor! I just bought a small amp myself for my new Moog theremin. Funny coincidence. Glad you solved it.
October 31st, 2007 at 9:07 pm
Just a quick note to say THANK YOU!!! I had been looking for 3-4 hours for a way to turn global sound on or off. You made my day!!!
November 1st, 2007 at 2:26 pm
john,
You’re welcome!
December 21st, 2007 at 12:46 pm
Hi everyone -
I’ve run into a roadblock and I’m hoping you can help.
My problem concerns: scoping variables across levels to start() playing sounds and setVolume().
Situation: I’m trying to use Dave Stiller’s solution to Uchitha’s problem back on September 19th, 2006 at 7:18 am. It worked great when the movie was standalone. But now that I’m using a loadMovieNum to place that file on _level2 - my buttons are no longer playing sounds.
PREVIOUS SOLUTION FOR UCHITHA:
// Instantiate Sound for sfx
var sfx:Sound = new Sound();
// Handle Button events
button1.onRollOver = function() {
sfx.attachSound(”UP-sound”);
sfx.start();
}
This did work - until I loaded the movie onto _level2. The buttons then stopped playing sounds all together.
*I have tried scoping the buttons back to _level2…. but no sound.
button1.onRollOver = function() {
_level2._root.sfx.attachSound(”UP-sound”);
_level2._root.sfx.start();
}
Any help would be greatly appreciated!
Very best!
Andy
December 21st, 2007 at 1:05 pm
Andy,
The success of your scoping is going to depend on where each of these objects resides. If you’re instantiating
Soundin the same SWF that gets loaded into
_level2of another SWF, then it looks to me as if your
Soundinstance (
sfx) is in the root of
_level2, along with your buttons. The buttons should be smart enough to find
sfxas shown in your first snippet.
In AS2, the reference to
sfxinside your function will look inside
button1first, hoping for a property named
sfx. When it doesn’t find that, it will step up to the object that contains
button1and look there (where it should find
sfxjust fine). If that’s not working, that baffles me a bit, but you could certainly try an explicit reference like this:
In any case, the expression
_level2._rootisn’t a valid one, because
_rootis the base of
_level2from the point of view of
_level2(in AS2, levels are a bit like multiple copies of a Word document open in Word: they’re all related, but each is its own document).
December 21st, 2007 at 2:28 pm
Hi David - thank you so much for the super fast reply!
Here’s where I’m at…. I tried your suggestion to explicitly reference ’sfx’ and it is working as a standalone file. But when loaded into _level2, I’m still getting no sound. I’ve pasted my code below. All buttons and code are on the main timeline of that movie.
var sfx:Sound = new Sound();
sfxbtn1int.onRollOver = function():Void {
this._parent.sfx.attachSound(”low”);
this._parent.sfx.start();
}
sfxbtn1int.onPress = function():Void {
this._parent.sfx.attachSound(”high”);
this._parent.sfx.start();
}
The button is named ’sfxbtn1int’ and sits right on the main timeline of the same .swf.
Any other ideas? I’m really at a loss right now. I made sure that there was no conflicting code or instance names in my _level0 movie before writing you back.
Thank you again for helping me work this out!
Andy
*sidebar: The reason I’m doing all of this is because setVolume isn’t working on my buttons with timeline sounds (which is how I came across his page). Just trying to get a simple mute button working.
December 26th, 2007 at 10:51 am
Hi David,
The code in this tutorial doesn’t seem to work with ActionScript 3.0. I get an error: “1120: Access of undefined property globalSound.
December 27th, 2007 at 6:54 pm
Brian,
Hey, thanks for bringing this up! I wrote this tutorial in May, 2006, before ActionScript 3.0 was officially available for Flash. The above sample code is indeed ActionScript 2.0, so you’re right — it won’t work in an AS3 document. (It does happen to work in AS1, provided you drop the post-colon suffixes [
:Soundand
:Void]).
Time keeps marching on, so I’ve updated the title of this article to reflect its basis in AS2.
Sound is handled quite differently in AS3, and I’ve been planning to update this how-to along with a number of the others that are often consulted. In the meantime, check out the
SoundTransformand
SoundMixerclasses in AS3: those are the ones you need to change volume globally.
In the above,
xfis an arbitrarily named variable set to an instance of the
SoundTransformclass. Rather than the usual expression
new SoundTransform(), this one gets its instance from the static
SoundMixer.soundTransformproperty. The
SoundTransforminstance (
xf), has a
volumeproperty, which is set to 0. The
SoundMixer.soundTransformproperty is then set back to the updated value of
xf. In AS3, a full volume is indicated by 1 rather than 100 (the range is 0 to 1 in AS3, so 50% volume is 0.5).
December 30th, 2007 at 8:23 pm
[Follow up on Andy …]
Since his post on Dec 21, 2007, Andy shared a few of his files with me at my request. We determined that his object references were all correct. Oddly (and very interestingly), the
Soundclass simply doesn’t seem to work — in the context of Andy’s project — when the SWF that contains the code is loaded into another level.
By using
MovieClip.loadMovie()(instead of the old
loadMovieNum()function), I was able to view Andy’s file as he expected and recommended that workaround.
January 11th, 2008 at 9:53 pm
Hello David
I am very new to ActionScript and I am trying to learn 3.0. That said, I have two concerns. First, I am building a site where I simply want a soundtrack to loop in the background at the start of the movie and I would like to use a single button so the user can toggle the soundtrack on or off. I am at a loss because I do not want it to be a global function that will affect other rollover sounds, for instance.
Second, where has the mailto ability gone? I am using this bit of script below to open an email window but it also opens a blank browser window!
function gotoLimnerMail(evt:Event):void {
var limnerUrl:URLRequest = new URLRequest(”mailto:limnerian@mac.com”);
navigateToURL(limnerUrl);
}
bConfabulate01.addEventListener(MouseEvent.CLICK, gotoLimnerMail);
Can you please give me a nudge?
At your convenience!
Thank you,
Fritz
January 21st, 2008 at 9:31 am
Fritz,
Your syntax is just fine for the
mailtoendeavor. I tested very similar code on my own machine, and the only thing that opens is a new message window for my email client. Have you tested this in a SWF that is a) embedded in an HTML page and b) located on a server? You may encounter different behavior when viewing the SWF locally versus online.
As for the audio issue, you’re in luck.
It’s entirely possible to toggle audio for specific
Soundinstances. In AS2, you associate your
Soundinstance with a particular movie clip in order to provide it a kind of separate “sound channel” (see “Understanding the Sound Constructor (AS2)“); in AS3, you need an additional two classes:
SoundChanneland
SoundTransform.
The
Soundinstance loads the file and plays it. The
Sound.play()method returns a
SoundChannelinstance. Finally, the
SoundChannel.soundTransformproperty returns a
SoundTransforminstance, which has a
volumeproperty. Update that property and re-assign it to the
soundTransformproperty of your
SoundChannelinstance.
It’s more convoluted, yes, but the chain of events is pretty straightforward. Thanks to the individualized sound channel, you have specific volume control over your music (or whatever else is loaded into a particular
Soundinstance).
January 25th, 2008 at 1:58 am
Hello… I’ve been trying to follow the instructions above that I think apply to me, but I don’t think I have read anything that exactly covers my situation, so I’ll ask. Also, please know that I am very new to Action Script and use only very basic stuff– mostly I’m good at cutting and pasting code, so the simplest solution is best for me. Here’s my situation. I have a single timeline with a music background track that plays throughout all pages. On a couple pages I have some flv files that play and when they are selected to view, I want the background music to turn off. I have accomplished this by using the stop all sounds command on the button to launch the flv videos. When the video is over, I want to background music to start up again. So I just added another instance of the same background music to the timeline where the play head leaves the frame with the flv video. I set the sound instance sync in the property inspector to Start so that I wouldn’t get 2 of the same music tracks playing should the play head encounter this second instance while still playijng the first. This works great for turning off and on the background music when a flv file is playing. Here’s the problem… There is also a Music On and Off button (actually two separate buttons that replace one another) so that those who do not like listening to music while on the site don’t have to. I’m not quite sure what all the code is that is govering the affects of the on/off buttons (there seems to be a lot of it), but there are 2 problems. First, when you turn the button off, the video sound gets turned off also– not just the music and sound effects. That’s not good. Second, if after turning the sound off you encounter the second instance of the music on the timeline, then the music starts playing again– even though you had turned the button off. Is there a relatively simple way to solve both problems? Bottom line is that I’d like the music and sound effects to stay off when using the off button (even though play head encounters instance of music on timeline),but the off button should not kill the flv video sound. I hope this was clear. Thank you for your help.
January 25th, 2008 at 8:41 am
Earl,
Your best bet is to remove your music soundtrack from the timeline altogether. Control it using ActionScript instead. I can empathize with your hesitance to venture into unfamiliar code — at some point, all of us were beginners! — but all the same, I encourage you to ease your way into this particular approach. Even if it’s new to you, instantiating a
Soundin ActionScript 2.0 still counts as relatively basic coding. You create the instance, load a sound into it, then tell it to start and stop as you please — at any time along the timeline.
It should help you considerably to read through “Understanding the Sound Constructor (AS2),” because that gives you the breakdown on what it means to separate your audio into distinct “sound channels,” which allows you to set the volume one one sound clip without affecting another (in AS2, this is done with movie clips, as you’ll see in the other article).
That will happen if you use a more global approach, like the one suggested in this article. If you route your instructions to just the video, or just the music, you’ll be fine (again, see the “Sound Constructor” piece).
That makes sense to me, because even after your button turned sounds off — using
stopAllSounds(), I think you said — the timeline overrides that and starts them up again. All
stopAllSounds()does is stop the sounds currently in play.
January 28th, 2008 at 10:41 am
Hi David,
I’ve been reading through many of your blogs and have learned quite a bit so far - so thanks for that…now on to the party:
I am using Red5 to stream video to a VideoObject in Flash, using ActionScript 2 in Flash CS3. I used your technique described above (globalSound) and it doesn’t quite accomplish what I’m looking for.
I have the following code in the main timeline:
var globalSound:Sound = new Sound();
_root.muteClip.onRelease = function(){
globalSound.setVolume(0);
}
The only thing that happens when the movieClip (which is just a set of two symbols that I can toggle to the visibility to switch the display for the user) is that the sound gets a little lower, but not off…does this have something to do with streaming and NetStream/NetConnection?
Any help would be much appreciated - thanks!
January 28th, 2008 at 10:52 am
Markito,
I haven’t used Red5, so that’s a good question. In theory, streaming shouldn’t have any effect on how the
Soundclass works, but if you find otherwise, I’d love to hear about it.
What I find interesting is that the sound seems to get lower, but not all the way silent. If you trace out the
globalSoundobject, do you get a valid object reference?
January 28th, 2008 at 11:33 am
David,
Thanks for the speedy reply! Well, there is a lot more to this that I find incredibly confusing. If I’m using the Flash IDE the volume controls don’t work at all, meaning the volume doesn’t even get lower when I click the button. If I publish it and put it on a server to play, it then sort of responds. The second thing is that Red5 seems to operate very similarly to the Flash Media Server, so I don’t think it’s to do with Red5 either.
I tried the code you asked me to and it does come back as a valid reference. So I did a little further investigating and added some more code to the block:
_root.muteClip.onRelease = function(){
trace(globalSound);
globalSound.setVolume(globalSound.getVolume()-10);
}
After 10 clicks on the movie clip the sound was off! Then of course, I changed the above code to “globalSound.setVolume(0)” and now it works…I have no idea why this just started working almost magically. Whatever the reason, thanks for reading my post and being a fresh perspective on it. I’m not sure why it started working all of a sudden, but I’ll chalk it up to user (me!) error.
January 29th, 2008 at 10:33 am
Markito,
Ha … there’s no saying, really. I’ve seen weird things like that happen, and sometimes all that matters is that it’s working now. Glad you nailed it!
February 13th, 2008 at 6:15 pm
Hi David….I found your tutorial very interesting, especially for a beginner as myself. I have the following problem. I inserted some video clips sequentially and also have a mp3 file running on the back, however, i would like the mute the sound for these video clips (its poor quality) and prefer to have my sound of the mp3 running all the way through. Is there a script code to mute only the video clip, and if so, where do i insert this script code? Sorry if this question sounds a bit stupid, im just totally new at flash and trying to get myself going with it.
February 13th, 2008 at 7:47 pm
Bart,
Your question doesn’t sound stupid at all.
This article should get you where you’re headed: “How to Adjust the Audio Portion of Flash Video“; if not, let me know.
February 27th, 2008 at 3:16 pm
David,
I am currently working with a very simple audio toggle. I used the code
var globalVolume:Sound = new Sound();
btnSoundOff.onRelease = function() {
globalVolume.setVolume((globalVolume.getVolume()+100) % 200);
}
which was posted a while ago. It seems to work fine. The only thing I would like to do is toggle the volume button itself. When the volume is off, I would like to swap out the button for another button image, and then swap it back when the volume is on. It should seem like a simple toggle, but I’m not sure how to incorporate it into the existing code. Any help you can give me would be greatly appreciated.
Thanks
March 5th, 2008 at 6:25 pm
Hi David,
This is a brilliant blog by the way, from reading through i don’t think there
is an for my question so far. I have 6 frames on my main timeline
on the 5th frame i have 5 buttons that load in 5 different external
swf files into a blank mc. In each of the external swfs is a sound
on the timeline with a image, this all works great. I am trying to
turn the sound on and off with two buttons (which are situated
on frame 5 of the main timeline. I have tried using:
On the main timeline:
var globalVolume:Sound = new Sound();
On the buttons:
//on button//
on(release) {
globalVolume.setVolume(100);
}
//Off button//
on(release) {
globalVolume.setVolume(0);
}
This didn’t seem to work, i’m not sure but i think
this is just controlling the sound in the main flash file
and not the external swfs (i think is because of the different levels?)
sorry if this is simple, its my first time trying to control sound
using ActionScript.
Thanks
March 17th, 2008 at 9:34 pm
To Ken …
There are a number of ways you might do this. Your might, for example, use a movie clip symbol to make your button (note that the
MovieClipclass provides all of the
Buttonclass events, plus more). In this case, you could nest a second movie clip inside the first and give that second movie clip two frames. Use a
stop()action to keep the inner movie clip stopped on frame 1 to begin with. Then, in your “button” event handler (actually a movie clip event handler), you could do this:
… meaning, that inner clip manages your two image states, and you send that clip to frame 1 or 2 of its own timeline in response to the toggle. Does that make sense? The only challenge there is that you lose the built-in visual states of a button symbol. But … this article may help you overcome that: “Easy Button States for Movie Clip Buttons.” You could put those visuals in the outer clip and user the inner one for the toggled state.
To Mike …
If your other SWFs are in different levels … that might just be the culprit here (but I can’t swear to that). In a sense, levels are like multiple documents in, say, Photoshop. Is there a reason you’re loading them in to levels and not movie clip instances? (Nothing at all wrong with levels, I hasten to add … they just never really clicked with me, back in the day, and I tended to prefer movie clip holders instead.)
You could certainly try creating multiple “global” volume controllers — one for each level — and set them all on/off across the board, as necessary. In that case, try …
March 30th, 2008 at 4:42 pm
Thanks so much! Very helpful.
April 3rd, 2008 at 9:37 pm
matt,
Sure thing! Glad to help.
July 25th, 2008 at 2:47 pm
Hi everyone! I’m glad to see a very nice bunch o’ folks here. Maybe you can get my mute button attempts to work? Because I’m stumped.
I’ve tried the method at the start of this tutorial. Although I think I get the concept, it won’t work in reality.
My movie doesn’t have a sound object. (I tried making one and it doesn’t work either…but that’s another story) My movie uses a sound on a layer…it’s a short sound and it loops, throughout the movie. Just FYI my movie has two scenes; once the first one is over, the second one loops.
I have been able to create a button. The button is named “Music” and it consists of the words “music on/off”. I gave it a rectangular “hit” area and an “over” and a “down” state that seem to work; it appears neatly on the movie–so far, so good. But its capability to mute the movie’s sound volume is totally nil.
Any ideas what’s happening?
Note–Given the info in the thread above, I used this:
var globalVolume:Sound = new Sound();
btnMusic.onRelease = function() {
globalVolume.setVolume(100-globalVolume.getVolume());
}
*Where* should I be putting that code? On the button itself or in the first frame of the movie? Or is something else what’s wrong?
Thanks in advance, smart Flashy people!
November 5th, 2008 at 11:17 am
HI DAVID! ARE YOU STILL HERE?
YOU WROTE:
———————
Conan,
You certainly could put the button code directly on your buttons …
As before, instantiate the Sound class first, in a frame of the main timeline.
var globalVolume:Sound = new Sound();
Then, on each of your buttons …
// on the “on” button
on(release) {
globalVolume.setVolume(100);
}
// on the “off” button
on(release) {
globalVolume.setVolume(0);
}
——————————–
IS THIS CORRECT? The layer version works fine, but my buttons do not work the way you explained to Conan.
AND WHAT HAPPENED TO THE PART: function():Void ? THIS DOES NOT SHOW UP IN THE BUTTONS CODE - AS IT DOES IN THE LAYER CODE VERSION.
I also have the problem, that the sound of a loaded swf (loaded onto an other level) should not start if the sound was silenced (setVolume(0)) before in the main swf. Otherwise I had to silence the sound twice. Is there a (simple) workaround for that?
Thanx in advance!
Robin (Designer, Non-Programmer)
November 5th, 2008 at 11:50 am
God…….n!
I just found out by myself how the buttons do work … One has to leave the WHOLE code as it is/was in the layer (not only putting: var globalVolume:Sound = new Sound(); there as explained to Conan). ADDITIONAL to that comes the button code part into the button, now it works fine!
But there is still my pre-detected sound problem of a loaded swf as mentioned above …
When the sound has already been silenced on the main level, before loading a new swf (on a new level) with sound, this loaded swf should not start its sound now. The whole movie has to stay quite.
Robin
December 1st, 2008 at 7:42 am
thank you very much! this is just what i needed
December 2nd, 2008 at 12:30 pm
You all are lifesavers.. thank you.
January 5th, 2009 at 1:05 pm
David, you da man!
I just started learning Flash, and for only 2 months in I feel pretty good about the whole affair, but I was having all sorts of issues with importing a video in swf mode, and not the flv version, and controlling the sound until I found this web site. Awesome. I put a small twist on your button call procedure and made 10 buttons and assigned a volume value for each like so:
var globalVolume:Sound = new Sound();
btnSoundOff.onRelease = function():Void {
globalVolume.setVolume(0);
}
btnSound10.onRelease = function():Void {
globalVolume.setVolume(10);
}
btnSound20.onRelease = function():Void {
globalVolume.setVolume(20);
}
//and on and on for as many buttons as needed………
This can be expanded to say 50 little buttons with 2% increases in sound value with an LED look, maybe with a little movie clip that glows on a fade up, and maybe shifting color tone as the scale increases. The current project I am working on has a few load external swf’s and when time permits I am going to experiment with just this idea.
I think I like this method better than a slider.
My question is, can the button state selected be made to “hang” in the over state until another click on another button releases it and the new selection “hangs”?
Again, wonderful source for us all, newbie and pro!
Roger Stephjenson
January 20th, 2009 at 6:46 pm
Hey, thanks this was very helpful
April 17th, 2009 at 5:30 pm
I know this post is a little old, but I ran across it on a search and it was exactly what I needed! And what’s more, I learned some about how ActionScript works by figuring out how to implement it. I’m just learning how to work with flash and AS for my job as webmaster (among other hats) at a small newspaper. This made my job a heap easier. Thanks a ton!
April 19th, 2009 at 11:21 am
To all …
Most of these replies are coming very late. Apologies! It’s been a busy couple years, mainly due to my recent work with friends of ED and O’Reilly.
To crittermonster …
You should still be okay, even without your other sounds being scripted. The technique in this article simply sets the volume for the whole SWF to 100 or 0. (Aside from this, I do encourage you to give scripted audio another shot! Your best bet is to set aside the project you have in front of you and make exploratory steps in a new FLA file — something that contains nothing at first but the minimum code required to get some audio playing.)
It’s possible that something about the way your timeline audio is set up is interfering with or overriding the ActionScript, but the first thing I’d check is whether or not your button’s
onReleasehandler is actually working. For example, I would add a
trace()statement inside the function to see if I could shoot a quick confirmation message to the Output panel:
This code should be attached to a timeline keyframe — not to the button. The keyframe should appear on the same frame number as the button itself. For example, if the button appears in frame 1 of the main timeline, then that’s also where the code should go. If the button doesn’t appear until frame 50, then that’s where the code should go.
To robin …
The code I showed does work, but it all depends on where you put it (which also depends on how you arrange your assets — buttons, and so on). More on this in just a minute, because your more recent reply touches on it.
When you see suffixes that begin with a colon, such as
:Void,
:Number,
:Sound, and the like, you’re seeing something called strong typing, which is an optional (but recommended) practice in AS2 and AS3 (it’s not supported in AS1). By strongly typing your variables and functions, you let Flash know what type of value you’re intending to use, which helps with code hinting and compiler warnings/errors in AS2 and the same for AS3, plus improved runtime errors and even performance increases, due to more efficient usage of memory (RAM).
Some people choose not to strongly type their code, even in AS2 and AS3, and I’m sure some people don’t realize they have the option (if, for example, they’re handy with AS1). When I refer to code samples from other people, I have to make the call whether or not to introduce elements like
:Void. Sometimes, I worry that making an addition like that might throw someone off. There are several articles on this blog, even with my own code, that omit strong typing. In this case, all the
:Voidmeans is that the function in question doesn’t provide a return value. That is, it simply does something, but doesn’t report back on that action. Contrast that with, say, the native
Math.round()method, whith both does something (rounds a number) and reports back (returns a number value). For that reason,
Math.round()could be described like this:
Math.round():Number.
That does add a layer of complexity, for sure. For that, you would have to get creative with your programming. You could add ActionScript inside the loaded SWF that checks the volume of your main SWF’s
globalVolumevariable. Alternatively, you could update the function that sets the global volume, rewriting it to account for external movie clips (SWFs). (See my reply to Mike on March 17, 2008.)
The most important part is that you find a solution that works. Good!
I’m curious what your final code structure was, because the code I suggested to Conan does work: a
Soundinstance is declared in the main timeline, and the buttons have access to that very instance by way of the variable named
globalVolume(or whatever you choose to name the instance). You should be able to do a bit of testing using the
trace()function in your button code:
If you try something like that, for example, you should see something in the Output panel of the authoring tool. If you see “undefined,” then your button’s aren’t “seeing” the
globalVolumeinstance, and that would explain why the code doesn’t work as currently arranged. You might have to actually target the path to
globalVolumewith the
MovieClip._parentprefix — once, or even a few times, depending on how deeply nested your buttons might be.
To martin and Neal …
Glad to hear it!
To Roger …
Yes, but to do that, you’ll have to make your buttons out of movie clip symbols. The reason for this is that buttons symbols have a very specialized timeline. If you check out the AS2
Buttonclass — in the Language Reference, not the Components Reference — you’ll find that buttons don’t have anything like the
MovieClipclass’s
gotoAndPlay()or
gotoAndStop()methods. If you want to stick with a particular the display state (aka a timeline frame), you’ll have to actually program your buttons to do so, and that means you need
MovieClipmethods.
To xTwIzZ …
You’re welcome!
To Joel …
I love to hear that! Programming is tough if you don’t know where to start — and the same is true, of course, for any new endeavor, programming or not — so I’m glad this gave you a leg up.
April 22nd, 2009 at 9:23 pm
Could you give me any tips on how to mute just some of the sounds on my page using as3? I have some buttons with sounds on the over frame (a rollover blip) which I would like to be able to silence without affecting the sound of other objects on the page.
I tried using and adapting this from one of your earlier posts but can only succeed in muting everything.
var xf:SoundTransform = SoundMixer.soundTransform;
xf.volume = 0;
SoundMixer.soundTransform = xf;
Thanks in advance!
Thanks
April 30th, 2009 at 9:18 pm
hi, actionscripting is completely over my head.
I have a question: I have this script
import flash.media.Sound;
import flash.media.SoundChannel;
var soundOn:Boolean = true; //music is ON when we start
var myMusic:sakura = new sakura();
var myChannel:SoundChannel = myMusic.play(0,1000); // endless loop, in effect
var myTransform:SoundTransform;
sound.addEventListener(MouseEvent.CLICK,toggleSound);
sound.buttonMode = true;
sound.mouseChildren = false;
function toggleSound(e:MouseEvent)
{
if(soundOn)
{
// turn sound off
myTransform = new SoundTransform();
myTransform.volume = 0; // silent
myChannel.soundTransform = myTransform;
soundOn = false;
sound.myButtonText.text = “sound”;
}
else // sound is off
{
// turn sound on
myTransform = new SoundTransform();
myTransform.volume = 1; // full volume
myChannel.soundTransform = myTransform;
soundOn = true;
sound.myButtonText.text = “sound”;
}
}
to play a sound and to stop it as well, there is one frame I need to have the “sakura” song to not play at all (basically to stop that sound so another sound on the one movie clip could be heard clearly). How would I do that?
|
http://www.quip.net/blog/2006/flash/how-to-toggle-sound-globally
|
crawl-002
|
refinedweb
| 10,603
| 71.95
|
Sequence and QNames (XQuery)
SQL Server
Azure SQL Database
Azure Synapse Analytics (SQL DW)
Parallel Data Warehouse
This topic describes the following fundamental concepts of XQuery:
Sequence
QNames and predefined namespaces
Sequence
In XQuery, the result of an expression is a sequence that is made up of a list of XML nodes and instances of XSD atomic types. An individual entry in a sequence is referred to as an item. An item in a sequence can be either of the following:
A node such as an element, attribute, text, processing instruction, comment, or document
An atomic value such as an instance of an XSD simple type
For example, the following query constructs a sequence of two element-node items:
SELECT Instructions.query(' <step1> Step 1 description goes here</step1>, <step2> Step 2 description goes here </step2> ') AS Result FROM Production.ProductModel WHERE ProductModelID=7;
This is the result:
<step1> Step 1 description goes here </step1> <step2> Step 2 description goes here </step2>
In the previous query, the comma (
,) at the end of the
<step1> construction is the sequence constructor and is required. The white spaces in the results are added for illustration only and are included in all the example results in this documentation.
Following is additional information that you should know about sequences:
If a query results in a sequence that contains another sequence, the contained sequence is flattened into the container sequence. For example, the sequence ((1,2, (3,4,5)),6) is flattened in the data model as (1, 2, 3, 4, 5, 6).
DECLARE @x xml; SET @x = ''; SELECT @x.query('(1,2, (3,4,5)),6');
An empty sequence is a sequence that does not contain any item. It is represented as "()".
A sequence with only one item can be treated as an atomic value, and vice versa. That is, (1) = 1.
In this implementation, the sequence must be homogeneous. That is, either you have a sequence of atomic values or a sequence of nodes. For example, the following are valid sequences:
DECLARE @x xml; SET @x = ''; -- Expression returns a sequence of 1 text node (singleton). SELECT @x.query('1'); -- Expression returns a sequence of 2 text nodes SELECT @x.query('"abc", "xyz"'); -- Expression returns a sequence of one atomic value. data() returns -- typed value of the node. SELECT @x.query('data(1)'); -- Expression returns a sequence of one element node. -- In the expression XML construction is used to construct an element. SELECT @x.query('<x> {1+2} </x>');
The following query returns an error, because heterogeneous sequences are not supported.
SELECT @x.query('<x>11</x>, 22');
QName
Every identifier in an XQuery is a QName. A QName is made up of a namespace prefix and a local name. In this implementation, the variable names in XQuery are QNames and they cannot have prefixes.
Consider the following example in which a query is specified against an untyped xml variable:
DECLARE @x xml; SET @x = '<Root><a>111</a></Root>'; SELECT @x.query('/Root/a');
In the expression (
/Root/a),
Root and
a are QNames.
In the following example, a query is specified against a typed xml column. The query iterates over all <step> elements at the first workcenter location.
SELECT Instructions.query(' declare namespace AWMI=""; for $Step in /AWMI:root/AWMI:Location[1]/AWMI:step return string($Step) ') AS Result FROM Production.ProductModel WHERE ProductModelID=7;
In the query expression, note the following:
AWMI root,
AWMI:Location,
AWMI:step, and
$Stepare all QNames.
AWMIis a prefix, and
root,
Location, and
Stepare all local names.
The
$stepvariable is a QName and does not have a prefix.
The following namespaces are predefined for use with XQuery support in SQL Server.
Every database you create has the sys XML schema collection. It reserves these schemas so they can be accessed from any user-created XML schema collection.
Note
This implementation does not support the
local prefix as described in the XQuery specification in.
|
https://docs.microsoft.com/en-us/sql/xquery/sequence-and-qnames-xquery?view=sql-server-ver15
|
CC-MAIN-2020-05
|
refinedweb
| 656
| 54.83
|
Search: Search took 0.04 seconds.
- 18 May 2009 12:28 AM
Yes that's a simpler solution, but you have to give up the control that ToolTip provides (display duration, mouse tracking, , etc.), and the cross-browser compatibility isn't guaranteed.
- 13 May 2009 5:01 AM
This is my latest and hopefully last version. It takes care of special cases, for example when some TreeItems don't have a tooltip, and includes workarounds for various oddities of GXT (as usual). If...
- 12 May 2009 4:45 AM
My previous solution seems to break sometimes in show() because targetXY is null... This doesn't happen in regular tooltips because you get a MOUSEMOVE event before showing the tooltip, but since...
- 12 May 2009 2:53 AM
This is how I did it:
-subclass TreeItemUI and override method onOverChange()
-set the "ui" field (protected) of TreeItem to my own subclass of TreeItemUI
public class MyTreeItemUI extends...
- 1 Mar 2009 3:05 PM
- Replies
- 12
- Views
- 57,204
Wonderful :)
That will simplify a lot of our code.
- 27 Feb 2009 5:13 AM
- Replies
- 12
- Views
- 57,204
I'm sorry and I don't mean to rude be but this is not a valid justification; nothing prevents you from firing a ChangeEvent in setValue() if the new value differs from the old one.
A valid...
- 27 Feb 2009 4:37 AM
- Replies
- 12
- Views
- 57,204
Could you point me to this thread please? Because I couldn't find it.
I'm curious to know the reasons behind this design choice that defeats the purpose of FieldBindings altogether. It seems...
- 27 Feb 2009 3:13 AM
- Replies
- 12
- Views
- 57,204
FieldBindings are great, but they do not always ensure what they should ensure, i.e. that the model properties and field values are always in sync.
Specifically:
calling clear() on the...
- 26 Jan 2009 1:31 AM
I'm sorry but you misunderstood. My suggestion doesn't remove anything, it just adds a second generic parameter to the MultiField class which would be used to specify the data type behind the...
- 23 Jan 2009 7:39 AM
Fine. Meanwhile I can live with my custom FieldBinding, but being able to use autobind would be better...
- 23 Jan 2009 1:55 AM
This is fine for you because you're not using FieldBindings, so you can call getChoiceSet() instead of getValue(). The default FieldBinding implementation uses getValue() and setValue(), which are...
- 22 Jan 2009 4:55 AM
Waiting for an official answer.. what's your opinion? Does anyone even use MultiField?
- 19 Jan 2009 7:35 AM
Moved to
Results 1 to 13 of 13
|
https://www.sencha.com/forum/search.php?s=91959233dec4ab3e4fa62723f6c6a283&searchid=10971496
|
CC-MAIN-2015-18
|
refinedweb
| 445
| 72.26
|
Launched.
Issue 1  June 2010
Curator
Lim Cheng Soon
Contributors
Printer
MagCloud
Curator's Note
I. —€”
By BRIAN SHUL
10 A Dismal Guide to Concurrency By CARLOS BUENO
PROGRAMMING
CAREER
14 2 Steps to Becoming a Great Developer
20 What Value do We Create Here?
By ERIC DAVIS
By CARTER CLEVELAND
16 iPhone Developer: "This is why I sell
22 7 Tips for Successful Self-Learning
beer"
By BRAFORD CROSS and HAMILTON ULMER
By JAMIE JAWINSKI
18 Top Three Motivators for Developers By DAVE RODENBAUGH
STARTUP 32 How I Took My Web-App to Market in 3
Days
By TAWHEED KADER
34 Organic Startup Ideas By PAUL GRAHAM
36 Not Disruptive, and Proud of It By JASON COHEN
38 Turning on Your Reality Distortion Field
SPECIAL 25 Adam?...is there a reason your laptop is
in the fridge?
By ADAM KEMPA
26 The Scariest Pricing Idea Ever By WALT KANIA
29 5 Actions that Made Me Happier By GARY HARAN
30 How Not to Run an A/B Test By EVAN MILLER
39 Best Writing Advice for Engineers
I ‘line. Scores of significant aircraft have been produced in the 100 years of flight, following the achievements of the Wright brothers, which we celebrate in December. ‘sled,’ as we called our aircraft. awestruck.. The.
5
»
». ne,
Photo credit: SR-71 Blackbird by Marcin Wichary (), Museum of Flight by Susie Gallaway (),
6 FEATURES newfoundtracking newfound
Lockheed SR-71 (Blackbird) front view by Keith (), SR-71 2 by Andrew Fogg (). Licensed under Creative Commons Attribution 2.0 Generic licence (creativecommons.org/licenses/by/2.0/deed.en).
7
»
» are quiet for the moment. I move my gloved finger. n Brian Shul was an Air Force fighter pilot for 20 years. Shot down in Vietnam, he spent one year in hospitals and was told he’d never fly again. He flew for another 15 years, including the world’s fastest jet, the SR-71. As an avid photographer Brian accumulated the world’s rarest collection of SR-71 photographs and used them to create the two most popular books ever done on that aircraft, Sled Driver, and The Untouchables. Brian today is an avid nature photographer and in high demand nationwide as a motivational speaker.
Reprinted with permission of the original author. First appeared on the book 'Sled Diver'. For more information, visit.
8 FEATURES
Reach to the Hackers, Founders and the people who are changing the web.
Advertise with Hacker Monthly Want to feature your product here? Email us at ads@hackermonthly.com. Oh, and don't forget to ask us about the trial advertising offer.
A Dismal Guide to Concurrency By CARLOS BUENO
T
paint a house faster than one can. Honeybees work independently but pass messages to each other about conditions in the field. Many forms of concurrency 0 , so obvious and natural in the real world, are actually pretty alien to the way we write programs today. It’s much easier to write a program assuming that there is one processor, one memory space, sequential execution and a God’s-eye view of the internal state. Language is a tool of thought as much as a means of expression, and the mindset embedded in the languages we use can get in the way.1 We’re going through an inversion of scale in computing which is making parallelism and concurrency much wo people can
more important. Single computers are no longer fast enough to handle the amounts of data we want to process. Even within one computer the relative speeds of processors, memory, storage, and network have diverged so much that they often spend more time waiting for data than doing things with it. The processor (and by extension, any program we write) is no longer a Wizard of Oz kind of character, sole arbiter of truth, at the center of everything. It’s only one of many tiny bugs crawling over mountains of data.
Many hands make light work
A few years ago Tim Bray decided to find out where things stood. He put a computer on the Internet, which contained over 200 million lines of text in
one very large file. Then he challenged programmers to write a program to do some simple things with this file, such as finding the ten most common lines, which matched certain patterns. To give you a feel for the simplicity of the task, Bray’s example program employed one sequential thread of execution and had 78 lines of code, something you could hack up over lunch. The computer was unusual for the time: it had 32 independent hardware threads, which could execute simultaneously. The twist of the WideFinder challenge was that your program had to use all of those threads at once to speed up the task, while adding as little code as possible. The purpose was to demonstrate how good or bad everyday
Photo credit: Tight Spin by Aaron Waagner (). Licensed under Creative Commons Attribution 2.0 Generic licence (creativecommons.org/licenses/by/2.0/deed.en).
10 FEATURES
programming is at splitting large jobs into parallel tracks. How hard could it be? I thought. Very hard, as it happened. I got up to 4 parallel processes before my program collapsed under its own weight. The crux of the problem was that the file was stored on a hard drive. If you’ve never peeked inside a hard drive, it’s like a record player with a metal disc and a magnetic head instead of a needle. Just like a record it works best when you “play” it in sequence, and not so well if you keep moving the needle around. And of course it can only play one thing at a time. So I couldn’t just split the file into 32 chunks and have each thread read a chunk simultaneously. One thread had to read from the file and then dole out parts of it to the others. It was like trying to get 31 housepainters to share the same bucket. When I looked at other people’s entries for hints I was struck by how almost all of them, good and bad, looked complicated and steampunky. Part of that was my unfamiliarity with the techniques, but another part was the lack of good support for parallelism, which forced people to roll their own abstractions. (Ask four programmers to create a new abstraction and you’ll get five and a half answers.) The pithiest entry was 130 lines of OCaml, a language with good support for “parallel I/O” but which is not widely used outside of academia. Most of the others were several hundred lines long. Many people like me were not able to complete the challenge at all. If it’s this difficult to parallelize a trivial stringcounting program, what makes us think we’re doing it right in complex ones? Ideally, concurrency shouldn’t leak into the logic of programs we’re trying to write. Some really smart people would figure out the right way to do it. They would write papers with lots of equations in them and fly around to conferences for a few years until some other smart people figured out what the hell they were saying. Those people would go develop libraries in our favorite programming languages. Then we could just put import concurrent; at the top of our programs and
be on our way. Concurrency would be another thing we no longer worry about unless we want to, like memory management. Unfortunately there is evidence that it won’t be this clean and simple. 2 A lot of things we take for granted may have to change. There are at least two concurrency problems to solve: how to get many components inside one computer to cooperate without stepping all over each other, and how to get many computers to cooperate without drowning in coordination overhead. These may be special cases of a more general problem and one solution will work for all. Or perhaps we’ll have one kind of programming for the large and another for the small, just as the mechanics of life are different inside and outside of the cell. At the far end of the spectrum are large distributed databases, such as those used by search engines, online retailers, and social networks. These things are enormous networks of computers that work together to handle thousands of writes and hundreds of thousands of reads every second. More machines in the system raise the odds that one of them will fail at any moment. There is also the chance that a link between groups of machines will fail, cutting the brain in half until it is repaired. There is a tricky balance between being able to read from such a system consistently and quickly and writing to it reliably. The situation is summed up by the CAP Theorem, which states that large systems have three desirable but conflicting properties: Consistency, Availability, and Partition-tolerance. You can only optimize for two at the expense of the third. A Consistent/Available system means that reading and writing always works the way you expect, but requires a majority or quorum of nodes to be running in order to function. Think of a parliment that must have more than half of members present in order to hold a vote. If too many can’t make it, say because a flood washes out the bridge, a quorum can’t be formed
and business can’t proceed. But when enough members are in communication the decision-making process is fast and unambiguous. Consistent/Partitionable means that the system can recover from failures, but requires so much extra coordination that it collapses under heavy use. Imagine having to send and receive a status report for every decision made at your company. You’ll always be current, and when you come back from vacation you will never miss a thing, but making actual progress would be very slow. Available/Partitionable means that you can always read and write values, but the values you read might be out of date. A classic example is gossip: at any point you might not know the latest on what Judy said to Bill but eventually word gets around. When you have new gossip to share you only have to tell one or two people and trust that in time it will reach everyone who cares. Spreading gossip among computers is a bit more reliable because they are endlessly patient and (usually) don’t garble messages.4 After lots of groping around with billions of dollars of revenue at stake, people who build these large systems are coming to the conclusion that it’s most important to always be able to write to a system quickly and read from it even in the face of temporary failures. Stale data is a consequence of looser coupling and greater autonomy needed to make that possible. It’s uncomfortable to accept the idea that as the computing power of an Available/Partitionable system scales up, the fog of war descends on consistency, but in practice it’s not the end of the world. This was not a whimsical nor easy choice. Imagine Ebenezer Scrooge is making so much money that Bob Cratchit can’t keep up. Scrooge needs more than one employee to receive
11
»
»
and count it. To find out the grand total of his money at any point, he has to ask each of them for a subtotal. By the time Scrooge gets all the answers and adds them up, his employees have counted more money, and his total is already out of date. So he tells them to stop counting while he gathers subtotals. But this wastes valuable working time. And what if Scrooge adds another counting-house down the street? He’ll have to pay a street boy, little Sammy Locke, to a) run to the other house and tell them to stop counting, b) gather their subtotals, c) deliver them to Scrooge, then d) run back to the other house to tell them to resume counting. What’s worse, his customers can’t pay him while this is happening. As his operation gets bigger Scrooge is faced with a growing tradeoff between stale information and halting everything
import concurrent;
to wait on Locke. If there’s anything Scrooge likes less than old numbers, it’s paying people to do nothing. Scrooge’s dilemma is forced upon him by basic physics. You can’t avoid it by using electrons instead of street urchins. It’s impossible for an event happening in one place (eg data changing inside one computer or process) to affect any other place (eg other computers or processes) until the information has had time to travel between them. Where those delays are small relative to performance requirements, Scrooge can get away with various forms of locking and enjoy the illusion of a shared, consistent memory space. But as programs spread out over more and more independent workers, the complexity needed to maintain that illusion begins to overwhelm everything else.3
want without the overhead of locking. In essence, transactional memory allows threads to ask for forgiveness instead of permission. As you might have guessed from those jolly hints about conflict and rollback, STM has its own special problems, like how to perform those commit/abort/retry cycles efficiently on thousands of threads. It’s fun to imagine pathological conflict scenarios in which long chains of transactions unravel like a cheap sweater.5 STM is also not able to handle actions that aren’t undoable. You can’t retry most kinds of I/O for the same reason you can’t rewind a live concert. This is handled by queueing up any non-reversible actions, performing them outside of the transaction, caching the result in a buffer, and replaying as necessary. Read that sentence again. Undeniably awesome and clever as STM threads are, I’m not convinced that shared memory makes sense outside of the “cell membrane” of a single computer. Throughput and latency
Shared memory can be pushed fairly far, however. Instead of explicit locks, Clojure and many newer languages use an interesting technique called software transactional memory. STM simulates a sort of post-hoc, fine-grained, implicit locking. Under this scheme semi-independent workers, called threads, read and write to a shared memory space as though they were alone. The system keeps a log of what they have read and written. When a thread is finished the system verifies that no data it read was changed by any other. If so the changes are committed. If there is a conflict the transaction is aborted, changes are rolled back and the thread’s job is retried. While threads operate on nonoverlapping parts of memory, or even non-overlapping parts of the same data structures, they can do whatever they
always have the last laugh. A concurrent system is fundamentally limited by how often processes have to coordinate and the time it takes them to do so. As of this writing computer memory can be accessed in about 100 nanoseconds. Local network’s latency is measured in microseconds to milliseconds. Schemes that work well at local memory speeds don’t fly over a channel one thousand times slower. Throughput is a problem too: memory can have one hundred times the throughput of network, and is shared among at most a few dozen threads. A large distributed database can have tens of thousands of independent threads contending for the same bandwidth. If we can’t carry the shared-memory model outside of the computer, is there some other model we can bring inside? Are threads, ie semi-indepen-
essence, transactional memory allows threads “Into ask for forgiveness instead of permission.”
12 FEATURES
dent workers that play inside a shared memory space, absolutely necessary? In his “standard lecture” on threads Xavier Leroy details three reasons people use them: • Shared-memory parallelism using locks or transactions. This is explicitly disowned in both Erlang and Leroy’s OCaml in favor of messagepassing. His argument is that it’s too complex, especially in garbage-collected languages, and doesn’t scale. • Overlapping I/O and computation, ie while thread A is waiting for data to be sent or received, threads B-Z can continue their work. Overlapping (aka non-blocking I/O) is needed to solve problems like WideFinder efficiently. This is often thwarted by low-level facilities inside the operating system that were written without regard to parallelism. Leroy thinks this should be fixed at the OS level instead of making every program solve it again and again.
• Coroutines, which allow different functions to call each other repeatedly without generating an infinitely long stack of references back to the first call. This looks suspiciously like message-passing. Message-passing, which first appeared in Smalltalk, is the core abstraction of Joe Armstrong’s programming language Erlang. Erlang programs do things that make programmers take notice, like run some of the busiest telephone switches for years without fail 6. It approaches concurrency with three iron rules: no shared memory even between processes on the same computer, a standard format for messages passed between processes, and a guarantee that messages are read in the order in which they were received. The first rule is meant to avoid the heartaches described above and embraces local knowledge over global state. The second and third keep programmers from endlessly reinventing schemes for passing messages between processes. Every Erlang process has sovereign control over its own memory space and can only affect others by sending well-formed messages. It’s an elegant model and happens to be a cleaned-up version of the way the Internet itself is constructed. Message-passing is already one of the axioms of concurrent distributed computation, and may well be universal. There are probably more axioms to discover. Languages become more powerful as abstractions are made explicit and standardized. Messagepassing says nothing about optimizing for locality, ie making sure that processes talk with other processes that are located nearby instead of at random. It might be cool to have a standard way to measure the locality of a function call. Languages become even more powerful when abstractions are made firstclass entities. For example, languages that can pass functions as arguments to other functions can generate new types of higher-order functions without the programmer having to code them by hand. A big part of distributed
computing is designing good protocols. I know of no language that allows protocols as first-class entities that can be passed around and manipulated like functions and objects are. I’m not even sure what that would look like but it might be interesting to try out. There is a lot of sound and fury around parallelism and concurrency. I don’t know what the answer will be. I personally suspect that a relaxed, shared-memory model will work well enough within the confines of one computer, in the way that Newtonian physics works well enough at certain scales. A more austere model will be needed for a small network of computers, and so on as you grow. Or perhaps there’s something out there that will make all this lockwork moot. n
Notes
0. Parallelism is the act of taking a large job, splitting it up into smaller ones, and doing them at once. People often use “parallel” and “concurrent” interchangably, but there is a subtle difference. Concurrency is necessary for parallelism but not the other way around. If I alternate between cooking eggs and pancakes I’m doing both concurrently. If I’m cooking eggs while you are cooking pancakes, we are cooking concurrently and in parallel. Technically if I’m cooking eggs and you are mowing the lawn we are also working in parallel, but since no coordination is needed in that case there’s nothing to talk about. 1. “The slovenliness of our language makes it easier for us to have foolish thoughts. The point is that the process is reversible.” -- George Orwell, Politics and the English Language “That language is an instrument of human reason, and not merely a medium for the expression of thought, is a truth generally admitted.” - George Boole, The Laws of Thought 2. Neither was the switch to memory management, come to think of it. 3. This is not about speed-of-light effects or anything like that. I’m only talking about reference frames in the
sense of “old news”, such as when you find out your cousin had gotten married last year. Her wedding and your unawareness are both “true” relative to your reference frames until you receive news to the contrary. 4. The categories are not rigidly exclusive. The parliment problem is mitigated in real parliments with quorum rules: say if a majority of members are in one place, or some minimum number is present in chambers, they can act as though they were the full body. The status report problem is usually handled by having heirarchies of supervisors and employees aka “reports”. The gossip consistency problem can be helped by tagging data with timestamps or version numbers so you can reconcile conflicting values. 5. There is a recent paper about an interesting variation on this theme called HyTM, which appears to do a copy-on-write instead of performing writes to shared memory. 6. A lot of writeups repeat a “nine nines”, ie 99.9999999% reliability claim for Erlang-based Ericsson telephone switches owned by British Telecoms. This works out to 31 milliseconds of downtime per year, which hovers near the edge of measurability, not to say plausibility. I was present at a talk Armstrong gave in early 2010 during which he was asked about this. There was a little foot shuffling as he qualified it: it was actually 6 or so seconds of downtime in one device during a code update. Since BT had X devices over Y years, they calculated it as 31ms of average downtime per device per year. Or something like that. Either way it’s an impressive feat. Carlos Bueno is an engineer at Facebook. He writes occasionally about general programming topics, performance, security, and internationalization. His long-term project is to “save the web”: to build a network of independent, redundant, Internet archives.
Reprinted with permission of the original author. First appeared in.
13
PROGRAMMING
iPhone Developer: “T By JAMIE ZAWINSKI
D
Clock 2.31 is out now,-codecompatible with NextStep than the iPhone is with MacOS. It’s full of all kinds of idiocy like this -- Here’s how it goes on the desktop: ali
NSColor fg = [NSColor colorWithCalibratedHue:h saturation:s brightness:v alpha:a]; [fg getRed:&r green:&g blue:&b alpha:&a]; [fg getHue:&h saturation:&s brightness:&v alpha:&a];
But on the phone: UIColor fg = [UIColor colorWithHue:h saturation:s brightness:v alpha:a];
Reprinted with permission of the original author. First appeared in jwz.livejournal.com/1224702.html.
14 PROGRAMMING
This is why I sell beer”. n.
15
2 Steps to Becoming a Great Developer By ERIC DAVIS
I
the two steps that I’m using to walk the path to becoming a great developer. Becoming a great developer is a constant work in progress, but it’s a pattern that I’ve seen many other great developers follow. want to share
Step One: Write More Code
This might sound easy but trust me - it’s not easy.. You’re afraid of something. Afraid of wasting time, afraid of being embarrassed publicly, afraid of making a mistake, afraid of being afraid. Let me share two stories with you about my fears: I’ve been a contributor to Redmine for a couple of years now, but I haven’t been very active in the code base. Why? Redmine is a large complex code base and I didn’t know how everything worked. So I stayed in my corner and only committed minor changes. Yet I still found a way to break those sections. Self-fulfilling prophecy? With my product, SeeProjectRun,
16 PROGRAMMING
I have to charge users’ credit cards. Taking actual money is scary. After hearing all of the horror stories about companies screwing this up, I became deathly afraid of this and put off writing any billing code. Yes, me a developer who has written four credit card interfaces for active_merchant was afraid of writing code to bill his users. WTF is going on here? Fear is a mistress that will steal your life if you let her. So how do you get over your fear of writing more code?
two days. Throwing two hundred test cases at it proved to me that it would work good enough to get over my fear. Don’t let fear hold you back from writing code.
Write more code
• 1 great developer (them)
As odd as it sounds, the only way I found to get through my fear of writing code was to crank it out like it was going out of style. The easiest way to do this? Start new side projects and contribute simple patches to Open Source. Every time you write code, you will learn something about the code, your tools, or yourself. Did you really think my 57 plus daily refactoring posts were only about fixing bad code? Nope, they are my sledgehammers against coder’s block. Oh and the ending to my stories about fear: I just spent last night rewriting a core component of Redmine and committed it to the project this morning. It if breaks, I’ll fix it. If it’s really crap code, I’ll revert it. No one will care and no one will remember the mistake. And for the billing code I strapped myself down and finished the credit card billing code for SeeProjectRun in
Step Two: Work With Great Developers
Now that you’re creating code, you need to work with great developers so you can see how to they write great code. Just take: • 1 passionate developer (you) • a dash of code Mix well daily and after a short rise in the over, you’ll have two great developers. Feel free to add a few nuts (other great developers) and bake again. You don’t need to search for the greatest developers of all time, you just need developers smarter and further along in their skills than yourself. This can be easy if you work in a company that has hired great developers. But what do you do if your company doesn’t hire any great developers or you are a solo freelancer like me?
Start reading great developers’ code
I’m making it a habit to start reading great developer’s code. They put out so much code, you will find yourself reading so much of it that you start to dream about code1.
Getting Started
Now here’s the call to action, because you will never become a great developer without taking action.
Write At Least One Line Of Code In A New Code ➊ Base Every Day For A Week. Switch Code Bases After Each Week.
This can be a new feature, a bugfix, a refactoring, or just monkeying around with an idea. It doesn’t matter, the act of thinking through the code and writing is what you are after. Don’t know one a good code base to start on? Do a refactoring on Redmine and tell me about it in the comments below.
➋
Find A Way To Learn From A Great Developer Every Week.
If you are working solo: • download some popular projects and read through a single class every week • get some API documentation that shows the method’s source code inline and read the source each time you look up a method, or • find a mentor and work with them on some real code So whatever you do, take action today. Unless you’re afraid of becoming a great developer...But there is plenty of room at the top. n
Notes
1. Notice that the smart developers are always producing new code.... they are following step #1.
If you are working with a great developer:
• do an informal code review their last commit • ask to pair program with them, or
Eric Davis runs Little Stream Software, where he builds custom software for businesses using Redmine.
• buy them lunch and ask them about their favorite hack
Reprinted with permission of the original author. First appeared in theadmin.org/articles/2010/04/16/two-steps-to-becoming-a-great-developer/.
17
Top Three Motivators for Developers By DAVE RODENBAUGH
S? Is it your fat salary, great perks, and end-of-year bonuses? Unless you’ve been working on Mars for the past two years, I think Computerworld1 would disagree with you. We’ve been getting kicked in the nads just as hard as everyone else. Between budget cutbacks, layoffs and reductions in benefits or increases in hours, clearly our paychecks are not our primary source of satisfaction. If money were. oftware has long
18 PROGRAMMING
The assumption
People perform better when given a tangible, and even substantial, reward for completing a task. Think bonuses, stock options, and huge booze-driven parties.
The reality
In a narrow2 band of actual cases, this is true. By and large, the reward-based incentive actually creates poorer performance in any group of workers for cognitive tasks, regardless of economic background or complexity of the task involved3. I’m not making this up, nor am I just drawing on anecdotal experience. Watch this 18-minute video from TED4: •. •. • In doing so, our weird becomes the new normal. Witness the output of the Dot Com era: Aside from the economic meltdown, how many
out, we’re kidding ourselves if we think that “Turns [money] is our real motive as developers.”. n
Notes
1. article/347538/The_Big_Squeeze 2. Anything that isn’t a cognitive task, simple or complex, according to the research I quote below. 3. Sorry, outsourcers…dangling the reward under your workers noses doesn’t help even when your home country is considerably poorer on average than Western economies. Yet another surprising finding of their research. 4. rrkrvAUbU9Y Dave Rodenbaugh is an independent software contractor with nearly 2 decades of enterprise project experience in a variety of companies and industries. Although he loves Java, he sometimes drinks a good black tea when the mood strikes. He’s still waiting for his first business trip to the Caribbean.
Reprinted with permission of the original author. First appeared in.
19
CAREER
What Value
O
I thought I had the ultimate dream job. During the day I created software that accessed some of the world’s largest financial databases and provided traders with real-time data and analysis for trade ideas. At night I worked with the CTO on a side project that analyzed huge amounts of transaction data to identify arbitrage opportunities. We figured that if we could start finding enough of these opportunities, we could present them as trade ideas to the bosses. So we wrote scripts, and at night, after everyone else left the office, we installed them on their computers and ran the scripts in parallel to try and crunch through the massive amount of data we had access to. This was fun. Really fun. And even better, the CTO was an awesome guy who taught me a lot about programming. They also paid well. Really well. Even more than my friends received working 100 hour weeks at I-Banking jobs. In retrospect, no college student should ever have been paid that much (on the bright side, the savings were enough for Art.sy’s initial funding). But that summer it meant I could go out to nice dinners with my girlfriend, and never worry about paying for drinks at expensive clubs. It meant I could afford fancy clothes, an iPhone, and plane flights to Asia. Having always worked in labs prior to that job, it redefined how I thought about money. ne summer
Photo credit: Self by Jason Filsinger (). Licensed under Creative Commons Attribution 2.0 Generic licence (creativecommons.org/licenses/by/2.0/deed.en).
20 CAREER
e do We Create Here? By CARTER CLEVELAND
So what is wrong with this picture? I had an extremely fun and challenging job, working with awesome people, that let me afford an incredible lifestyle. It was a dream comes true. But at the end of the summer, the CTO brought me into the corner office and closed the door. I had worked with him all summer and this was my last day, so I was expecting a performance evaluation. Instead, after some chit chatting, he asked me a question: “Have you ever wondered what value we create here?” Value? This wasn’t what I was expecting at all. “Not really.” “I’ll tell you. We increase the liquidity of the secondary bond market. We shave basis points off of spreads.” I’ll never forget that question. It turns out that our CTO was saving every penny and had plans of leaving as soon as he had enough cash to pursue his dream. He didn’t care about the fancy clothes, the clubs, or being a master of the universe. All he cared about was how he would add value to the world. At this point, my story starts to sound cliché, but it was a cliché I needed to experience in person because it radically changed my perspective.
“How am I creating value?” I realized that the programs I had spent all summer writing were great, if they could make people money and save them time. But if all it resulted in at the end of the day was slightly more efficient markets, well, what was the point of that? I was so caught up in the fun and camaraderie of my job, so high with the rush of money, I never considered such a simple question. This probably won’t change the minds of people who have already chosen career paths. But to any students who are thinking about their futures, I hope my story illustrates how easy it is to get swept up by short-term pleasures, and how important it is to always ask this question when making important decisions. n Carter Cleveland is the founder of Art.sy, a platform for connecting artists and galleries with collectors of original fine art. He is also the NYC Curator of The Startup Digest.
Reprinted with permission of the original author. First appeared in.
21
7 Tips for Successful Self-Learning By BRADFORD CROSS and HAMILTON ULMER
S
elf-learning is hard.
Regardless of where, when or how you learn - being a good self-learner will maximize your potential. In this post, Hamilton Ulmer (an almost-done Stanford stats masters student) and I, will explore seven ways to become a great self-learner.
The longest path is the ➊ shortest and the shortest path is the longest
The shortest route to learning the craft of a field is the one that, at first glance, appears the longest. To really learn something, you must understand the basic concepts of your field. If you try to skip, you may end up spending
22 CAREER
more time figuring out concepts than if you had started with learning basics. Have you ever wanted to take up a new subject, bought a book, only to make a failed attempt at the first few chapters before submitting to a lack of foundation for the material? Starting at the beginning might seem daunting, but trying to skip to the goal directly is likely to fail. If you are studying and unsure that you have the background for something, just stop when you don’t understand something and go back to acquire that background.
➋ Avoid isolation
In school you have many effective feedback loops. If you are confused, you can ask the lecturer for a clarification. Your homework assignments and exams motivate you to internalize the content of the class, whether you want to or not. Peers can help you smooth over small rough spots in your understanding. A decent self-learner must find others who are familiar with the material. Naturally one prefers to find an expert, but discussing the material with a peer can also go a long way. Having a community is vital. Often, a byproduct of finding or building a community is finding a mentor. The
“
No matter what, you’re going to have to learn most everything on your own anyway.” one element of graduate school that is hardest to replicate is the advisor-advisee relationship. They help guide you, smoothing out the uncertainties you have about certain topics, and help you make your own learning more efficient. As a self-learner, you do not have the convenience of scheduled class time and required problem sets. You must be aggressive about finding people to help you.
➌ Avoid multitasking
in a classroom or library to study, but notice the relative isolation and focus those environments afford over reading a book with your laptop on while writing emails and checking facebook or twitter with the TV on. Remove the distractions and allocate large blocks of time. You might find that for more difficult material, you need larger blocks of time to study because it takes longer to shift into the context of harder problems.
Another reason school is great for learning is that you plan your day around your classes. There are distractions, of course, but if you’re concerned with learning at school, you prioritize your classes over other things. You don’t have to be
You don’t read textbooks, you ➍ work through them
Imagine taking a 12-hour flight with two books, Machiavelli’s “The Prince” and Shilov’s “Elementary Functional Analysis.” It would be typical to finish the 100 pages of Machiavelli in two hours or so, and spent the rest of the time working through 10 pages of a Shilov’s “Elementary Functional Analysis,” minus some breaks for napping and eating undesirable airplane food. Reading a technical book is nothing like reading a novel. You have to slow down and work carefully if you want to understand the material. Have you ever found yourself 10 pages further in a book and having forgotten what you’ve just read? Successful self-learners don’t read, they toil. If there are proofs, walk them through, and try proving results on your own. Work through exercises, and make up your own examples. Draw various diagrams and invent visualisations to help you develop an intuition. If there is a realworld application for the work, try it out. If there are algorithms, implement them with your favorite programming language. If something remains unclear, hunt down someone who’s smarter than you and get them to explain. Sometimes you just need to put the material down, step away, relax, and think deeply to develop an intuition. Figure 1. The "I'm stuck" decision tree.
1
23
»
“
In theory, there is no difference between theory and practice. But, in practice, there is.”
- Jan L. A. van de Snepscheut
➎ Build Eigencourses
Great self-learners spend a lot of time to find the best resources for learning. You can find all the textbooks, papers and other resources you need on the Internet. Many of the course materials from among the world’s best universities are available for free online2. Check out the great lists of links to video courses on this Data Wrangling post3. You can pick and choose the best “eigencourse” with lecture slides, video lectures, textbooks, and other materials. The best way to find these materials is on Google. You will often only need to pay for the book, and sometimes even the book is free at the course website in pdf form. Take the time to triangulate on the right material. Find the greats in the field, see what they use and recommend. Find other students and read the reviews on Amazon. Google is your friend.
➏
What to do when you don’t understand
Learning is all about abstractions. We build up abstractions on top of other abstractions. If you do not know the abstractions you are reading about that are being composed into new higherlevel abstractions, then you aren’t going to understand the new abstraction. If you get stuck, the way to get un-stuck is to follow the I’m stuck decision tree4.
is nothing so practical ➐ There as a good theory. -Kurt Lewin
Sometimes you are several hops away from something you can code up and apply to a problem directly. Not all textbooks can be read with application in mind, despite that they serve as the theoretical foundation for applied work. This is why you must have a deep sense of patience and commitment - which is why a prolonged curiosity and passion for a topic are so valuable. Understanding analysis (particularly sets, measures, and spaces) will serve as your foundation for a deep understanding of probability theory, and both will then serve as your foundation for understating inference, and a deep understanding of inference is a mainstay of achieving high quality results on applied problems. Avoid the dualistic mistakes of technical execution without intuition, and intuition without technical execution.n
Notes
1. Keep in mind that you often just need to build a general foundation in the field, or mastery of some subset of a field - you don’t have to master the entire field. 2. Top_10_Universities_With_Free_ Courses_Online.php 3. hidden-video-courses-in-math-scienceand-engineering 4. Figure. Hamilton Ulmer is a Master’s student in Statistics at Stanford. He has a great deal of experience as a data engineer, having helped startups of various sizes and shapes get on their feet with processing and visualizing their data, as well as helping them make data-driven decisions. In August he will join the Mozilla analytics team.
Reprinted with permission of the original author. First appeared in measuringmeasures.com/blog/2010/4/19/7-tips-for-successful-self-learning.html.
24 CAREER
Adam? …is there a reason your laptop is in the fridge? By ADAM KEMPA
I
.n Adam Kempa works as a web developer in Ann Arbor, Michigan (Yes, people still live in Michigan). His nerdy musings intermittently appear at kempa.com.
Reprinted with permission of the original author. First appeared in adam-is-there-a-reason-your-laptop-is-in-the-fridge/.
25
SPECIAL
The Scariest Pricing Idea Ever By WALT KANIA
H
ere’s a pricing
technique that sounds, at first, like the dumbest newbie move of
all time. Call it ‘fill-in-the-blank’ invoicing. Or ‘pay what you want’ pricing. The notion is, you do the work first, then let the client decide how much to pay for it. I know, that sounds like a sure way to end up working for nickels and peanuts. I once thought that way, too. But it’s actually an ingenious tactic
26 SPECIAL
that should be in every freelancer’s arsenal, ready to wheel out when the wind is right. (Notice I said when the wind is right. We’ll come back to that.). I had dabbled with this tactic before, but only on those small, oddball projects a client would send me now and then.
me just concentrate on “Let getting this done for you, and
we’ll settle up later. I trust you to be fair.” As an added bonus, you will most likely do the best work of your life, and deliver obscenely wonderful service to your clients at the same time. (Mainly because you’ll be too scared not to.)
Making it pay. More.
“I have no idea what to bill for this,” I’d say. “Just send me whatever seems right to you.” Sometimes they would send a hundred or two more than I anticipated, sometimes less. But it was always intriguing to see how the client perceived what I had done. And a little humbling, too, on occasion. But over the past year or so I finally got the guts to try this on large projects for big clients. (Partly because, while developing “Talking Money,” I was thinking/obsessing about pricing issues pretty much all day long. I was itching to see how this worked.) I can tell you this: the ‘pay what you want’ idea can be surprisingly and dumbfoundingly profitable. Better still, I can guarantee you that it will shake up your thinking about fees and pricing. It will un-stick some old notions. And heaven knows we need that; most of us are way too myopic, constipated and chickenshit about fees.
Naturally, the sole reason for using fillin-the-blank invoicing is to net more from a project than you could with “traditional” pricing. The idea is to get paid for the value the client derives from the work, rather than for the number of hours it took. Or how hard it was. Or how many shots you had to take. Or what somebody else charged some other client somewhere. And by value, I don’t mean only hard economic value, like sales or savings or new business. (Which in most cases is hard to quantify anyway.) As I’ve discovered, clients are also willing to pay lavishly to get a nosebleed project done and off the desk, to look like geniuses in front of their bosses, to have presentations that their sales people rave about. To finally get the bosses sold on videos for user training. To untangle a project that somebody else screwed up. That kind of value has no relation to how long it took you to do the job. It’s irrelevant, immaterial. And it is difficult to guess what that value might be from our side of the glass. So it can pay to let the client set that value.
Example. A client of mine was knee-deep in redoing all her company’s web site content. She was getting raw material from the various divisions that was ugly, undecipherable and unusable. The go-live date was looming. She called me in to figure out how to fix it all. But she had no idea how many sections we’d be doing, how many pages, nor how bad the raw material would be, so it was impossible to estimate any sort of fee..” Now, lest you think I’m just handing you rosy stories, here’s another.
27
»
try this with one-time clients...Been there, “Don’t done that, lost shirt.” »
A designer friend is working on a web site for a financial firm, two partners. He refers them to me for the writing. We have a few phone conversations. Seems simple enough. Not a ton of content, straightforward mission. The clients don’t know much about marketing or web stuff. I say, “Tell you what. I’ll write everything for you, and when you’re happy with it, send me a check for what you think is reasonable.” Ordinarily, I would have quoted about $2500 for the project, although I don’t say that. I do some drafts. There are some comments, some revisions. Slam-dunk. Site goes live. Time to settle up. And I’m thinking the Wall Street guys are seeing a fee with a lot of zeros. They send a check for $1200. And say, ‘Thanks for the great work.” Ouch and a half.
What works, what doesn’t
After a few painful scorchings, and several delightfully lucrative wins, here is the bottom line. This technique works only when: • You have a long-term relationship with the client. You’ve done work for them before, at your usual rates. They trust you. They know your work. And mostly likely they need to work with you again. • Don’t try this with one-time clients, clients who don’t use this work often, or clients who didn’t seek you out. Been there, done that, lost shirt.
• The client has a big personal stake in the project. They have skin in the game. They stand to look grand if all goes well, score some points, be a hero, win some kudos. This does not work for low-level backburner projects that no one cares about. (Like my Wall Street clients; to them, their website was just some bullshit thing they needed to have. They didn’t perceive it as critical.) • The project looks hard, impossible, and indecipherable. (My Wall Street clients thought it was a cinch to bang out a few pages of drivel, and therefore paid accordingly. My technology client tried untangling her web content herself, and got scared. To her, it seemed insurmountable.) How do clients react? Do clients like this idea? A few will balk. They don’t want the responsibility of figuring out a fee. They don’t want the anguish. That’s okay. Give them a quote. Most will be astonished that you offer the option. It shows you trust them. That you value their judgment. That you even thought to ask. Huge karma points translate to more dollars. Sometimes (as one client confessed to me) they’ll reflexively crank up the fee when filling in the blank. Sort of like the way we reflexively and fearfully crank down the price when the client says ‘How much will it cost?”
J
know I’m not the only crackpot using this idea, Matt Homann of LexThink, a consultant who works with law firms, offers this ‘you decide’ option to all of his clients. His experience with the technique mirrors mine exactly. There’s more about his approach here too, in The NonBillable Hour. (It’s for lawyers, but the ideas apply to us, I think.) Oh, and see the classic Little Rascals episode from 1936, “Pay as You Exit.” As the story goes, the gang was putting on a show in the barn, but the neighborhood kids were reluctant to pay the penny admission, fearing that the show might be lame. Over Spanky’s objections, Alfalfa decided to let everyone in for free, and allow them to pay on the way out if they liked the show. As it turned out, the gang botched the show horribly, but the result was so hilarious that the kids filed out laughing. Leaving Alfalfa with cigar box full of pennies. n ust so you
Walt Kania is a freelance writer who runs The Freelancery site (thefreelancery.com), and develops marketing content (waltkania. com) for B2B and technology companies. He has plied his trade independently his entire adult life, due to a congenital inability to tolerate conventional employment for more than three to five days.
Reprinted with permission of the original author. First appeared in thefreelancery.com/2010/04/the-scariest-pricing-idea-ever-that-works/.
28 SPECIAL
5 Actions that Made Me Happier By GARY HARAN
H
universally quantifiable but money is. At some point in my life I raced towards money because I could measure it. When I noticed it wasn’t making me happier I set out to make happiness my main goal. Here is a list of actions I took. appiness is not
➊ Reduced Commute Time
Commuting is a side effect of many jobs and sadly the higher the salary the more commute time we’re willing to do. Finding ways to shave off commute time has a proven benefit as measured by this study1. When changing jobs wasn’t a possibility I used public transportation and got an Internet capable cell phone so I could deal with paperwork related annoyances during the commute. Instead of trying to find time at home I’d deal with them while in traffic. I also borrowed and bought a few books. Today my job allows me to work from home and my commute takes about 38 seconds. I still need to commute a few days a week but I can choose to take the car and avoid rush hour traffic.
➋ Removed Small Frustrations
I start every day by making some tea. I had this cheap kettle that would randomly turn off on me. One day after pouring cold water over tealeaves I decided to drive to the store. Now every morning I look at the testament of a foregone frustration with a smile from ear to ear. Removing frustrations can be as simple as moving the furniture or spending a few bucks.
➌ Played Sports
A Harvard University study started in 1937 that spanned 72 years determined that healthy play could relieve daily frustrations making us happier overall. A few years ago I joined a volleyball team and now I play a minimum of once a week.
➍ Attended Regular Meetups
Would doubling your income make you happier? Well it turns out that seeing a group of people that meets just once a month provided the same benefit as doubling your salary. Once I started digging I found out that Montreal was vibrant and full of user groups and programming language enthusiasts that meet regularly. I’ve met some really interesting people through these groups and some of the contacts even helped me professionally.
➎ Drank Socially With Co-Workers
When work sucks your life sucks. A good team feels comfortable cracking a joke to the CEO. Imagine how many valid concerns are not expressed if a team has to worry about everything they say. Good communication is perhaps the reason why those who occasionally have a single drink after work with colleagues make significantly more money on average than those who do not drink at all. Team members who do drink are probably made aware of problems and can resolve situation before they occur. It’s a different setting and we all know that a little alcohol can make shyness go away. So it’s perhaps a stretch to make this point but seriously having a drink has some beneficial effect on the time you spend at work and that can’t all be bad since you’re there a good portion of your day. n
Notes
1. 09_panel_mobility_Stutzer.pdf Gary is a programmer and entrepreneur in Montreal, Canada. He is a father and entrepreneur currently working at SocialGrapes.com. You can follow him on twitter @xutopia.
Reprinted with permission of the original author. First appeared in.
29
How Not to Run an A/B Test By EVAN MILLER
I
f you run A/B tests on your website and regularly check
Example
ongoing experiments for significant results, you might Suppose you analyze an experiment after 200 and 500 be falling prey to what statisticians call repeated signifi- observations. There are four things that could happen: cance testing errors. As a result, even Scenario 1 Scenario 2 Scenario 3 Scenario 4 though your dashboard says a result is statistically significant, there’s a After 200 observations Insignificant Insignificant Significant! Significant! good chance that it’s actually insigAfter 500 observations Insignificant Significant! trial stopped trial stopped nificant. This note explains why. End of experiment Insignificant Significant! Significant! Significant!
Background
Assuming treatments A and B are the same and the When an A/B testing dashboard says there is a “95% chance significance level is 5%, then at the end of the experiment, of beating original” or “90% probability of statistical signifiwe’ll have a significant result 5% of the time. cance,” it’s asking the following question: Assuming there is But suppose we stop the experiment as soon as there is no underlying difference between A and B, how often will a significant result. Now look at the four things that could we see a difference like we do in the data just by chance? happen: The answer to that question is called the significance level, and “statistically significant results” Scenario 1 Scenario 2 Scenario 3 Scenario 4 mean that the significance level is After 200 observations Insignificant Insignificant Significant! Significant! low, e.g. 5% or 1%. Dashboards usuAfter 500 observations Insignificant Significant! Insignificant Significant! ally take the complement of this End of experiment Insignificant Significant! Insignificant Significant! (e.g. 95% or 99%) and report it as a “chance of beating the original” or something like that. The first row is the same as before, and the reported However, the significance calculation makes a critical significance levels after 200 observations are perfectly fine. assumption that you have probably violated without even But now look at the third row. At the end of the experiment, realizing it: that the sample size was fixed in advance. If assuming A and B are actually the same, we’ve increased the instead of deciding ahead of time, “this experiment will ratio of significant relative to insignificant results. Therefore, collect exactly 1,000 observations,” you say, “we’ll run it the reported significance level – the “percent of the time the until we see a significant difference,” all the reported signifi- observed difference is due to chance” – will be wrong. cance levels become meaningless.?
30 SPECIAL
Try 26.1% – more than five times what you probably thought the significance level was. This is sort of a worst-case scenario, since we’re running a significance test after every observation, but it’s not unheard-of. At least one A/B testing framework out there actually provides code for automatically stopping experiments after there is a significant result. That sounds like a neat trick until you realize it’s a statistical abomination. Repeated significance testing always increases the rate of false positives, that is, you’ll think many insignificant results are significant (but not the other way around). The problem will be present if you ever find yourself “peeking” at the data and stopping an experiment that seems to be giving a significant result. The more you peek, the more your significance levels will be off. For example, if you peek at an ongoing experiment ten times, then what you think is 1% significance is actually just 5% significance. Here are other reported significance values you need to see just to get an actual significance of 5%: You peeked... 1 time 2 times 3 times 5 times 10 times
To get 5% actual significance you need... 2.9% reported significance 2.2% reported significance 1.8% reported significance 1.4% reported significance 1.0% reported significance
Decide for yourself how big a problem you have, but if you run your business by constantly checking the results of ongoing A/B tests and making quick decisions, then this table should give you goosebumps.
What can be done?. “Peeking” at the data is OK as long as you can restrain yourself from stopping an experiment before it has run its course. I know this goes against something in human nature, so perhaps the best advice is: no peeking! Since you are going to fix the sample size in advance, what sample size should you use? This formula is a good rule of thumb: Where δ is the minimum effect you wish to detect and σ2 is the sample variance you expect. Of course you might not know the variance, but if it’s just a binomial proportion you’re calculating (e.g. a percent conversion rate) the
variance is given by: Committing to a sample size completely mitigates the problem described here.. That can be calculated with:
Where the two t’s are the t-statistics for a given significance level α/2 and power (1-β). Painful as it sounds, you may even consider excluding the “current estimate” of the treatment effect until the experiment is over. If that information is used to stop experiments, then your reported significance levels are garbage. If you really want to do this stuff right: Fixing a sample size in advance can be frustrating. What if your change is a runaway hit, shouldn’t you deploy it immediately? This problem has haunted the medical world for a long time, since medical researchers often want to stop clinical trials as soon as a new treatment looks effective, but they also need to make valid statistical inferences on their data. Here are a couple of approaches used in medical experiment design that someone really ought to adapt to the web: • Sequential experiment design: Sequential experiment design lets you set up checkpoints in advance where you will decide whether or not to continue the experiment, and it gives you the correct significance levels. • Bayesian experiment design: With Bayesian experiment design you can stop your experiment at any time and make perfectly valid inferences. Given the real-time nature of web experiments, Bayesian design seems like the way forward.
Conclusion. n Evan Miller is a graduate student in Economics at the University of Chicago, and the author of the Chicago Boss web framework.
Reprinted with permission of the original author. First appeared in.
31
STARTUP
How I Took My Web-App to Market in 3 Days By TAWHEED KADER
I
’m a huge fan of the 37Signals mantra of “scratch your own itch.” Inspired by their book for “Getting Real” which I’ve read at least twice, and “Rework” which I’m reading now, I decided to write a small web application to scratch an itch around customer development emails. Do note though, 37Signals mantra here probably roots back to a saying my Dad, also an entrepreneur, has always said to me: “Necessity is the mother of invention”. Either way, here’s the problem I solved with Tout: as I’ve been ramping up customer development for Braintrust, I realized that typing, copying, pasting, re-typing all these emails was becoming a huge pain. Even worse, it became even harder to keep track of all these emails. “There had to be a better way!” — and while there are tons of CRMs out there, the simple “get in, get out” type of solution didn’t exist. So, I decided to create one. Introducing Tout – the simplest way to templatize and track (like you do for websites) your customer development emails. It helps me create e-mail templates, send emails quickly, and track when someone’s viewed my email, and whether they clicked on my link. It also let me track whether my overall email was a “success” or not. It took me about 1 day to get the
app working to fit my own need. After realizing this could probably help other people, it took me another 2 days to get it production ready. WOW! I think we’re at amazing times right now. With all the different “common services” startups cropping up, building, releasing and opening up shop for a web application has never been easier. Here are the common services/technologies I leveraged to take Tout to market in 3 days:
Heroku
All of my development is on Rails, and Heroku puts Rails on steroids. Thanks to their amazing cloud infrastructure, I had to do ZERO sysadmin stuff and was able to get my app online in literally 3 commands. More importantly, setting up DNS, E-Mailing, and SSl was all done through the web UI as well. I highly recommend them for starter applications, especially ones that are still testing out the market. The only downside for Heroku is that they have no way to support realtime applications (i.e. run an XMPP or NodeJS server to push out real-time updates) — can you guys start working on this?
Sendgrid
Even though the biggest “feature” of my web-app is sending emails, I had to write next to no code for actually
sending out emails or even configuring e-mail servers. All of this got taken care of by Sendgrid. They were also very diligent about validating my site and making sure I was compliant with CAN-SPAM laws and ensuring this doesn’t turn into another spamming machine.
Chargify
Tout has a premium feature, and charges credit cards, handles recurring billing and even sends out invoices. However, I didn’t have to write more than about 50 lines of billing code. Chargify takes care of all of this — all I have to do is build out hooks to keep the subscription level of the customer up to date. The reality is, it has become so ridiculous easy to take web applications to market now that I don’t have to spend time working on plumbing — instead, all of my time and energy goes toward the creative aspect of the product — which is the way it should be. n TK is the Founder and CEO of Braintrust (), a webapp that helps organize your team's conversations. He also blogs bout his journey as a single founder for a bootstrapped company at. Prior to Braintrust, TK co-founded HipCal,which was sold to Plaxo in 2006.
Reprinted with permission of the original author. First appeared in.
32 STARTUP
Forget Servers. Forget Deployment. Build Apps. heroku.com   33
Organic Startup Ideas By PAUL GRAHAM
T
to come up with startup ideas is to ask yourself the question: what do you wish someone would make he best
34 STARTUP
fix things that seem broken, regardless of “Just whether it seems like the problem is important enough to build a company on.”.
S. 3. n
Notes
1. This suggests a way to predict areas where Apple will be weak: things Steve Jobs doesn’t use. E.g. I doubt he is much into gaming. 2. In retrospect, we should have become direct marketers. If I were doing Viaweb again, I’d open our own online store. If we had, we’d have understood users a lot better. I’d encourage anyone starting a startup to become one of its users, however unnatural it seems. 3. Possible exception: It’s hard to compete directly with open source software. You can build things for programmers, but there has to be some part you can charge for..
Reprinted with permission of the original author. First appeared in.
35
Not Disruptive, and Proud of It By JASON COHEN
I
36 STARTUP
problem with a known market and just doing it better or with a fresh perspective or with a modern approach? Do you have you create a new market and turn everyone’s assumptions upside down to be successful? Should you? I’m not so sure. Here’s my argument:
hard to explain the ➊ It.
It’s hard to sell disruption, ➋.
Most technology we now ➌ were.
disruptors often don’t ➍.
Simple, modest goals are ➎ most likely to succeed, and most likely to make us happy. It’s not “aiming low” to attempt modest success. It’s not failure if you “just” make a nice living for yourself. Changing the world is noble, but you’re more likely
“), midsized could. n Jason is the founder of three companies, all profitable and two exits. He blogs on startups and marketing at. ASmartBear.com.
Reprinted with permission of the original author. First appeared in blog.asmartbear.com/not-disruptive.html.
37
Turning On Your Reality Distortion Field By STEVE BLANK
I.
30-seconds
Our product is really complicated
H
was catching up ow do you
Photo credit: Campfire Blackhole by Aaron Wagner (). Licensed under Creative Commons Attribution 2.0 Generic licence (creativecommons.org/licenses/by/2.0/deed.en).
38 STARTUP
how the world will be different “Envision five years after people started using your product.”.”. Steve Blank is a retired serial entrepreneur and the author of Customer Development model for startups. Today he teaches entrepreneurship to both undergraduate and graduate students at U.C. Berkeley, Stanford University and the Columbia University/Berkeley Joint Executive MBA program.
Reprinted with permission of the original author. First appeared in steveblank.com/2010/04/22/turning-on-your-reality-distortion-field/.
Best Writing Advice for Engineers By WILLIAM A. WOOD
H ow to make
contexts. Write a paragraph or two for each such phrase. That is the body of your report. Identify each sentence in the body that needs clarification and write a paragraph or two in the appendix. Include your contact information for readers who require further detail. n William A. Wood works for NASA at Langley Research Center. He has a Ph.D. in Aerospace Engineering from Virginia Tech, and he has published in IEEE Software (Digital Object Identifier: 10.1109/MS.2003.1196317).
Reprinted with permission of the original author. First appeared in.
39
Hacker Monthly is an independent project by Netizens Media and not affiliated with Y Combinator in any way.
Tell us what you think
It's our first try, so we might did something wrong, or right. Please tell us about it so we could only get better in the coming issue.
hackermonthly.com/feedback/
|
https://issuu.com/babo/docs/hackermonthly-issue1
|
CC-MAIN-2017-43
|
refinedweb
| 11,458
| 63.8
|
Are averages different
Posted February 18, 2013 at 09:00 AM | categories: data analysis, statistics | tags: | View Comments
Updated February 27, 2013 at 02:35 PM
Adapted from \(\mu_1 - \mu_2 = 0\) (this is often called the null hypothesis). we use a two-tailed test because we do not care if the difference is positive or negative, either way means the averages are not the same.
import numpy as np n1 = 30 # students in class A x1 = 78.0 # average grade in class A s1 = 10.0 # std dev of exam grade in class A n2 = 25 # students in class B x2 = 85.0 # average grade in class B s2 = 15.0 # std dev of exam grade in class B # the standard error of the difference between the two averages. SE = np.sqrt(s1**2 / n1 + s2**2 / n2) # compute DOF DF = (n1 - 1) + (n2 - 1)
see the discussion at for a more complex definition of degrees of freedom. Here we simply subtract one from each sample size to account for the estimation of the average of each sample. = np.abs(((x1 - x2) - 0) / SE) print tscore
1.99323179108.
Let us compute the t-value that corresponds to a 95% confidence level for a mean of zero with the degrees of freedom computed earlier. This means that 95% of the t-scores we expect to get will fall within \(\pm\) t95.
from scipy.stats.distributions import t ci = 0.95; alpha = 1 - ci; t95 = t.ppf(1.0 - alpha/2.0, DF) print t95
>>> >>> >>> >>> >>> 2.00574599354
since tscore < t95, we conclude that at the 95% confidence level we cannot say these averages are statistically different because our computed t-score falls in the expected range of deviations. Note that our t-score is very close to the 95% limit. Let us consider a smaller confidence interval.
ci = 0.94 alpha = 1 - ci; t95 = t.ppf(1.0 - alpha/2.0, DF) print t95
>>> >>> >>> 1.92191364181 = t.cdf(tscore, DF) - t.cdf(-tscore, DF) print f
0.948605075732
Copyright (C) 2013 by John Kitchin. See the License for information about copying.
|
http://kitchingroup.cheme.cmu.edu/blog/2013/02/18/Are-averages-different/
|
CC-MAIN-2020-05
|
refinedweb
| 349
| 75.3
|
I have often read a common question in forum posts of how to create a User Control in ASP.NET but no one has provided the proper solution so by considering the preceding requirements I have decided to write this article to provide the step-by-step solution to create the User Control. So let us start creating an application so beginners can also understand.
So let us learn practically about User Controls in depth.
Step 2: Create the User Control
In the preceding code, whenever the user enters text into the preceding text boxes, after clicking on the save button it is displayed on the label. Now we are ready with the User Control, let us try to run it in a browser as it is showing in the following error:
After clicking on Pick URL the following window is shown, browse to the file location of the User Control then select it and click on the OK button as in the following:
What a User Control is
A User Control is a reusable page or control with an extension of .ascx and created similar to an .aspx page but the difference is that a User Control does not render on its own, it requires an .aspx page to be rendered.
User Controls are very useful to avoid repetition of code for similar requirements. Suppose I need a calendar control in my application with some custom requirements in multiple pages, then instead of creating the control repetitively you can create it once and use it on multiple pages.
Key points
- The User Control page structure is similar to the .aspx page but a User Control does not need to add an entire HTML structure such as body, head and form.
- A User Control has an .ascx extension.
- A User Control is derived from the UserControl class whereas an .aspx page is derived from the Page class.
- A User Control does not render on its own, it needs an .aspx page.
- To use a User Control in an .aspx page you need to register the control in the .aspx page.
Step 1: Create Web Application
Now let us create the sample web application as follows:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
- Provide the web site a name such as "CreatingUsercontrol" or another as you wish and specify the location.
- Then right-click on the project in the Solution Explorer then select "Add New Item" then select Web User Control template as in the following:
Now click on Add then User Control will be added into the solution of the application. Now open the design mode and add the two textboxes, one label, one button and after adding the studentcontrol.ascx the source code will look as follows:
<%@ Control</asp:Label>
In the preceding code you have noticed that there is no whole HTML code in User Control such as head, body and form even then it will create the server control. Now switch to design mode then the control will look such as follows:
Now double-click on the save button and write the following code in the studentusercontrol.ascx.cs file as:
protected void txtSave_Click(object sender, EventArgs e) { Label1.Text="Your Name is "+txtName.Text+" and you are from "+txtcity.Text; }
/>
As already discussed in the preceding, a User Control does not run directly on its own. To render a User Control you must use it in an .aspx page, now let us add the User Control in the .aspx page.
Step 3: Adding User Control into .aspx page
Now we need to add the User Control into an .aspx page to use it so let us add the Default.aspx page by right-clicking on the projct in the Solution Explorer. After adding the .aspx page then the Solution Explorer will look such as follows:
/>
Step 4: Register the User Control on .aspx page
To use a User Control in an .aspx we need to register it using the Register page directive, the register page directive has the following properties as:
- Assembly: This is an optional property used to register the assembly, for example Ajax control toolkit.
- Namespace: This property is used to specify the namespace.
- Src: Used to set the source of User Control.
- TagName: Used to provide the name for the User Control used on a page similar to a TextBox or label, you can define any name.
- TagPrefix: This is used to specify the prefix name of User Control which is similar to ASP. You can define any prefix name.
Now that we are familiar with the properties, let us register the User Control in an .aspx page. Go to the default.aspx source code, go to the top of the source code and the Register property and select it or if the User Control is not shown here click on or pick the URL as:
/>
After clicking the OK button, the User Control file path will be added to the register directive. Now after defining the tagname and tagprefix the Register directive will look as in the following:
/>
Now let us enter the TagPrefix into the form section then the control will be shown as follows:
/>
Now select the control and define the properties such as runat and Id. After defining it the User Control will look as in the following:
<uc:Student
Now the whole code of the default .aspx code will look as in the following:
<%@ Page <%@ Register </div> </form> </body> </html>
Now run the application, the UI will look as in the following:
/>
Now enter the name and city into the preceding two text boxes and click on the save button. The output will be shown as follows:
/>
Now you have seen that, we do not have any code on the .aspx page but still the output is shown because all the logic is written in the User Control, we can use the same User Control at N numbers of times by defining unique Ids on the same page or on multiple pages.
Summary
From all the preceding examples you have learned how to create a User Control. I hope this article is useful for all readers, if you have a suggestion then please contact me.
|
http://www.compilemode.com/2015/05/creating-user-control-in-Asp-Net.html
|
CC-MAIN-2017-09
|
refinedweb
| 1,049
| 60.95
|
+1 to choose another name. we had a terrible time with "Apache SOAP" :)
-- dims
On Wed, 8 Dec 2004 08:29:30 -0500, Brian McCallister
<brianm@chariotsolutions.com> wrote:
> As there are no JDO lists (yet, just asked for them), I'll bring one
> concern I have up here, which is the name.
>
> Are we allowed to call the project "JDO" ? This would be like naming
> the big servlet container project in Jakarta "Servlet" I think. I
> imagine it is technically Apache JDO, which is probably fine. Figure it
> is worth bringing up, particular as the project will play host to the
> official javax.jdo.* namespace, an confusing people is not generally
> ideal.
>
> -Brian
>
> ---------------------------------------------------------------------
>
|
https://mail-archives.eu.apache.org/mod_mbox/incubator-general/200412.mbox/%3C19e0530f041208055169c7417f@mail.gmail.com%3E
|
CC-MAIN-2021-39
|
refinedweb
| 114
| 74.69
|
source:
Overview
In this article we will dive into machine learning. We will begin by understanding the concept, then look at some of the use cases, requirements and finally explore a real world scenario using a demo application. Machine learning has the potential to dramatically change our lives, jobs and influence decision making on a scale that has never been seen before. It is one of the most exciting and also scary technological advancements to ever come around. It is the future but is also happening right now which is why there couldn’t be a better time to get started than today.
Understanding Machine Learning
In order to properly understand machine learning we need to consider artificial intelligence. The goal of AI is to create machines, built from computer programs that have cognitive capabilities, are able to analyze their environment and make decisions like a human would. AI is a huge field and there is a lot of topics within it but ultimately it is about making decisions cognitively. Machine learning as such is the foundation or building block of AI. Machine learning primarily is concerned with making the right decision based on learning. Deep learning is a subset of machine learning and often confused with the latter. Deep learning applications are basically the same, where they differs is around how they learn. Deep learning is predicative, understands accuracy and when given metrics or guidelines is able to learn on it’s own without supervision from humans. The below diagram shows how machine learning and deep learning fit into artificial intelligence.
The capability of deep learning being able to learn on it’s own is made possible by neural networks. A neural network is composed of many layers and weighted connections, that when given an input attempts to find the best possible output. The algorithms are within the layers and responsible for determining the output. This is done by weighting, prediction and measuring accuracy against metrics. A training set of data is then used to run a training cycle and build the neural network connections. The end result is a trained model with it’s own learned rule-set, that would be used by an application to create a business value. I like to refer to the phase of using a trained model as the professional phase.
The below diagram shows a basic workflow for machine learning with both the training and professional phases.
The goal is always to improve the accuracy of the model and it’s ability to match an input with the best possible output. As such, models will likely be continually improved over time and there will be a continuous improvement cycle between the training and professional phases. However a trained model is expected to handle future problems or even unknowns. It is thought that a model would not be updated multiple times a day or every few days but should last weeks or maybe even months. Nevertheless there is a need to continue to learn just like humans.
Machine Learning Use Cases
Today there are a lot of use cases for machine learning, in the future there will be even more, as new patterns or frameworks become available and understood. Some of the more common use cases I consider valid for today are shown below.
The important thing to remember is that machine learning will be replacing and greatly optimizing tasks not replacing humans themselves. The key as already stated about machine learning is to find the best output given an input, in order to make a decision. This probably also answers why search was one of the first use cases for machine learning. Regardless if we are talking about smart cars, analyzing medical imagery, stock market, providing personalized recommendations or even protecting security, the process or workflow is the same. The only thing that changes are the inputs/outputs, data labels or categorization, and sometimes the algorithms. As hinted creating new algorithms or defining new patters is really hard work and a really highly specialized field. However once the patterns or algorithms are known, they can be re-used and this is what everyone can leverage. For example if we take imagery, those patterns are well known and established. Depending on what you are doing you may only need to label your data and adapt what has already been done. If you are dealing with new types of imagery then it is still just a matter of adapting the frameworks that exist and tailoring it to your needs. An example of this is TenzorFlow (no affiliation to myself) which is a machine or deep learning framework that already has a lot of algorithms. TenzorFlow provides a abstraction and a workflow for handling the details of hitching input functions to output functions (neural connections). The whole point of machine learning is to analyze a very large data-set, train itself on all the patterns and connections to build a neural network and then based on a single input find the best possible output. Machine learning can do this better, faster and with more predictably than humans.
Machine Learning Requirements
Now that we have established a basic understanding for what machine learning is and where it can be used, let’s get into some of the requirements. Below is a list of some of the more important things to take into consideration.
- Requires GPUs, not CPUs for best performance
- High memory requirements as trained models are loaded in memory
- Large data-set for training
- Trained models are very large, many, many GBs
- Complex, diverse software stack (python, modules, compilers, hardware drivers, integration layers)
- Multi-cloud being able to leverage software stacks and data-sets across cloud platforms, including the existing enterprise environments
If you add up all the requirements you end up with needing a very dynamic and flexible environment that cannot only scale but meet the challenges around diversity and integration. Machine learning needs data and as such it likely won’t be some one-off, but rather integrated into the various sources of data in your enterprise environments. Containers and specifically a kubernetes based container platform is the only solution that can effectively meet the demands of machine learning workloads.
Containers provide process isolation while also providing an easy mechanism to package and transport such a complex software stacks across multi-cloud environments. A container platform enables ability to do many releases and fast rollouts of new capabilities without downtime. Models can be compiled and stored on persistent volumes so they don’t reside in the containers themselves. Machine learning workloads can easily be isolated to compute nodes with GPUs and large amounts of memory, typically running on baremetal from other workloads that may be better suited for VMs or other hardware. Finally it is key that a container platform can run in the enterprise environment as well as public cloud. In addition must be open, allow necessary control and leverage the best capabilities in order to harness the true power machine learning offers.
Machine Learning Demo Application
As we have discussed there are two parts to machine learning: building a trained model and using it. Most people will be more interested with the latter as that is where you see business value. As such the demo focuses on using an already trained model. The demo application is a voice recognition system. It will take an audio file, decode audio into text and then translate that text to the language of our choice. The application is broken into three parts: frontend, backend and the trained model.
The front-end is written in nodejs while the back-end is python. Currently the container image has both but that could be broken apart with an additional API or middleware layer. The trained model is downloaded but stored on a persistent volume that is simply mounted in the container image. This allows us to make changes to front-end or back-end and quickly rebuild without having to download model again. It also allows for a separate CI/CD process for delivering the model. Trained models will also likely be continually improved in the goal to get better outputs and intelligence from the algorithms.
The back-end is using Mozilla Deepspeech to do the voice recognition. Mozilla DeepSpeech is a TenzorFlow implementation of Baidu’s DeepSpeech architecture. We are using a basic trained English model (provided by DeepSpeech project) so accuracy is not nearly as good as it could if we trained the model to for example, with our voice, dialect or even other language characteristics. It is just intended for demo purposes not a real-world scenario. Once we have text we run the text through spell and accuracy correction and finally translate the text in to another language using Google Translate.
Deploy Machine Learning Demo Application
A Dockerfile is provided to build and deploy the application. Here we will deploy the application to OpenShift which is Red Hat’s Enterprise Kubernetes platform. As I mentioned a container platform is critical and OpenShift provides an independent, open platform for machine learning workloads. If you don’t have OpenShift I would recommend getting the community upstream version called OKD. If that isn’t an option you can use plain-old boring Docker and do a docker build of the Dockerfile on your workstation.
Clone GitHub Repository
Clone the GitHub repository to your laptop or workstation.
$ git clone
Login to OpenShift and create new project
A project in OpenShift is a namespace or workspace for applications.
Add Template into OpenShift
Templates in OpenShift provide pre-determined automation for how to build and deploy an application. The template we have provided takes care of building and deploying the demo application as well as configuring a persistent volume for storage and a URL or route.
Next you can choose to process and save the template so it is available in the project or service catalog for later use. We will do both.
Update Template Parameters
Templates are parameterized by their creators. In this case we will leave the defaults.
Build Demo Application
After all the objects defined in the template are created, the build will start. In this step we will build a container image with the necessary software stack and python development environment to run the application.
Deploy Demo Application
The deployment is started after the build completes and the build artifact, which is a container image is saved in the OpenShift registry. The deployment schedules the application to run and the scheduler determines the most appropriate node. The images is then pulled from the OpenShift registry to the node. The pod will show a grey border while the image is being pulled to a node.
Once the image is pulled to the node it will be started on that node.
The first time the application starts it will download the trained model. You can follow this by looking in the pods and containers logs. Once the trained model is downloaded the nodejs server will be started and the application made available.
You can also access the pod and container and look at the downloaded models under the /deepspeech directory. This is of course a persistent model.
You can view the persistent volume used under storage in OpenShift.
Using Demo Application
To access application simply click the URL or route configured by the template.
Note: if it is still downloading the model (can take a while), application will not start or be available, so check the logs in the container and be patient the first time.
Click choose file to select an audio file. There is a demo.wav file in the GitHub repository provided for convenience. You can of course record your own audio just follow the requirements mentioned in the application.
Once you click submit the audio file is downloaded into the container image and run through the translate.py program which loads DeepSpeech and performs audio-to-text as well as translation to language chosen. Click the Results button to see the results.
Note: it may take a minute or two to see any results and the translation will be done step-by-step so you can see how DeepSpeech model is making decisions. You will notice it makes several mistakes that later are corrected. This really illustrates the power of machine learning and also the complexity of understanding voice in a compute program.
The last audio-to-text sentence and translation is displayed before end of translation message. As you can see it got everything almost perfect.
Once the model runs you will notice quite a bit of memory and some CPU usage. The model is loaded into memory so you can imagine the usage for a much larger model, this one is only around 2GB. CPU/GPU usage will vary depending on size of the audio file and data-set.
Video
Below is a video recording of the demo.
Summary
In this article we gained a broader understanding for machine learning. By exploring use cases we saw just how wide reaching machine learning has become today and garnered new appreciation for it’s potential in the future. Looking into the requirements of machine learning workloads we were able to see the value of containers and a container platform. I am convinced given the diversity of the software stack, the integration required into multiple clouds as well as data-sets and the flexibility needed that a container platform, is the only option we should be considering for machine learning workloads. Finally a demo was provided to put more context around machine learning, show that it is actually simple to utilize and allow us to understand better what running machine learning workloads actually means.
Happy Machine Learning!
(c) 2018 Keith Tenzer
|
https://keithtenzer.com/2018/12/14/getting-started-with-machine-learning/
|
CC-MAIN-2019-30
|
refinedweb
| 2,296
| 52.7
|
remove bullets in Mail
- leroydouglas PacificNWCurrently Being ModeratedApr 18, 2012 9:31 AM (in response to Edward)
Highlite and delete.
Command-Z will also undo last command.MacBook Pro, Mac OS X (10.7.3), 2.4GHz IntelCorei5 320GB HD 8GB RAM
- Currently Being ModeratedApr 18, 2012 10:13 AM (in response to leroydouglas)
Hi Leroy,
Thanks for the tip but I only want to remove the bullets - not the whole text!
Command-z doesn't remove the bullets - it'll merely undo the last bit of typing...
There are work-arounds - I can cut the text in each bullet and then paste it outside the bulletted area... then go back and delete the bullets. However that seems like a crazy thing to need to do. What I'm asking is this: is there a way to remove the bullets entirely whilst retaining the text.
The same question/need arrises if you want to remove a bullet from only one of the list (say, the last one). If you forget to double-return (to exit the list) and you end up with one too many in the list, it's not possible (unless you cut/paste and then delete) to remove the bullet.
Thoughts gratefully received!
Edward
- Currently Being ModeratedApr 18, 2012 10:34 AM (in response to Edward)
Good question!
There has to be an easier/better way... But you can select the list, convert it to Plain Text (Format menu) and then eliminate the bullets by your favorite method (just delete them, search and destroy, etc.). Then convert back to Rich Text.
charlie
- Currently Being ModeratedMay 22, 2012 11:36 AM (in response to Edward)
This has been a longstanding pain and asked elswhere in various forms.
I've found no simple resolution to it other than:
- to select and cut the text
- click to a non-bulleted line
- then cmd+shift+v OR "Edit > Paste and Match Style" in the menu
This will paste the text with that loctions style. (you will lose any specific style you had in the originally selected text)
I cannot for the life of me understand whay Apple wouldn't allow the 'Decrease List Level' function to apply toward 'decreasing' the list to 'nothing'. It seems like an elegant solution to a trade-off problem (you might want only one bullet for some reason)
- Currently Being ModeratedDec 6, 2012 10:14 AM (in response to Edward)
Is that it? - no help from Apple on this?
It is somewhat ridiculous that if you create a bullet, you can't get rid of it. This is really basic text editing stuff.
Sometimes I do wonder what is going on in Cupertino.
Can someone please advise on how to resolve this issue effectively and why with successive updates to the OS certain basic things don't get any better?
- Currently Being ModeratedDec 27, 2012 11:02 PM (in response to davewhughes)
I'm having exactly the same issue, what a stupid option and can't be undone. What the **** is Apple doing??
Why would they put an option that isn't undoable?
BUT
I did find a work-around, copy your email message into "TextEdit" then click on same drop down that created the bullets in the email and you will see an option of "none" remove the bullets and then re-copy the message back to the email.
Why Apple did it this way is anyones guess, Apple thinks it doesn't have to answer to anyone, kinda like Microsoft
. APPLE START PAYING ATTENTION TO THE FOLKS THAT BUY YOUR PRODUCTS!
If I have to dig around to resolve stupid things then I may as well switch to Linux and not have to pay for software.
- Currently Being ModeratedDec 28, 2012 1:02 AM (in response to Akitaguy)
You clearly encapsulate the frustration that I feel too. A useful
tip, thanks, but it's absurd when you have to go to these lengths to work around quirks in the software implementation.
Why would Apple do it this way and why would they keep doing it and are they listening?
Personally I do not find these quirks endearing, just a pain. Apple do really need to iron this stuff out now, there are many examples e.g. no arrows in edit, no drag and drop in iTunes etc.
- Currently Being ModeratedDec 28, 2012 1:06 AM (in response to davewhughes)
When you make 100 billion you don't need to listen until that 100 billion disappears, by then its to late.....Microsoft...
- Currently Being ModeratedJan 11, 2013 4:32 AM (in response to Edward)
Try "Control + Enter" instead of "Enter" at the end of the line. This does not bring the bullet over to the next line.
- Currently Being ModeratedJan 11, 2013 4:51 AM (in response to elvines)
Hi Elvines, thanks for the tip, however, all this does is removes the bullet but retains the indent. To remove the bullet on the next line, you can also simply hit return twice. The issue I have is removing *all* the bullets i.e. I've made a bulletted list and have decided I no longer want it... how do I delete the bullets but retain the list? All thoughts gratefully received!
Edward
- Currently Being ModeratedJan 11, 2013 4:52 AM (in response to elvines)
This does work but it does not solve the basic issue of when you create a piece of text with a bullet you just cant get rid of the bullet. All I want to do is to de-bullet a line - it seems next to impossible without lots of cutting and pasting
- Currently Being ModeratedJan 11, 2013 5:08 AM (in response to Edward)
I am just sharing and learning along the way. Hope what I can think of helps.
How about copying the content with bullets, remove the last undesired bullet. Then do a "shift+option+command+v". Then "command+f", paste "• ", tick Replace, click "All".
- Currently Being ModeratedJan 11, 2013 5:16 AM (in response to davewhughes)
Hope this give the result you are looking for. Go to the previous line of the line we hope to de-bullet and "Control + Enter". Then "Delete" once.
- Currently Being ModeratedJan 11, 2013 5:37 AM (in response to elvines)
Elvines,
I really appreciate your efforts - but nothing you're doing is removing bullets from all the bullet points - it's either removing finishing a list (this can be achieved by double-return) or adding a non-bulleted but indented line. If you're able to take, for example, a bulleted list of 5 bullets and then suddenly to have *no* bullets on the list, then please reply - that's what we're all after and nobody has a solution *within* Mail.
Edwardd
|
https://discussions.apple.com/message/18161081
|
CC-MAIN-2014-15
|
refinedweb
| 1,131
| 69.72
|
Hide Forgot
Description of problem:
Guest as Netserver , and do netperf on Host , It will lost 100% packet in UDP_STREAM protocol
Version-Release number of selected component (if applicable):
Host kernel: 3.10.0-234.el7.ppc64
Guest kernel: 3.10.0-229.el7.ppc64
qemu-kvm-rhev-2.2.0-8.el7
Netperf version 2.6.0
How reproducible:
100%
Steps to Reproduce:
1.Start up Guest with spapr-vlan device.
#usr/libexec/qemu-kvm -name liuzt-RHEL-7.1-20150219.1 -machine pseries-rhel7.1.0,accel=kvm,usb=off -m 32768 -realtime mlock=off -smp 64,sockets=1,cores=16,threads=4 \
-uuid 95346a10-1828-403a-a610-ac5a52a29483 \
-monitor stdio \
-rtc base=localtime,clock=host \
-no-shutdown \
-boot strict=on \
-device usb-ehci,id=usb,bus=pci.0,addr=0x2 \
-device pci-ohci,id=usb1,bus=pci.0,addr=0x1 \
-device spapr-vscsi,id=scsi0,reg=0x1000 \
-drive file=/var/lib/libvirt/images/liuzt-RHEL-7.1-20150219.1-Server-ppc64 \
-serial pty \
-device usb-kbd,id=input0 \
-device usb-mouse,id=input1 \
-device usb-tablet,id=input2 \
-vnc 0:19 -device VGA,id=video0,vgamem_mb=16,bus=pci.0,addr=0x4 \
-device virtio-balloon-pci,id=balloon0,bus=pci.0,addr=0x3 \
-msg timestamp=on \
-netdev tap,id=hostnet0,script=/etc/qemu-liuzt-ifup,downscript=/etc/qemu-liuzt-ifdown \
-device spapr-vlan,netdev=hostnet0,id=net0,mac=52:54:00:c4:e7:83,reg=0x2000 \
2.start netserver in Guest. 192.168.200.100 is the Guest ip
# netserver -p 44444 -L 192.168.200.100 -f -D -4 &
3.start netperf in Host , and got the performance.
#netperf -p 44444 -L 192.168.200.1 -H 192.168.200.100 -t UDP_STREAM -l 60 -- -m 16384
Actual results:
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 16384 60.00 1569894 0 3429.47
229376 60.00 24 0.05
Expected results:
packet loss shouldn't be ~100%, At a pure Host/Guest network environment, the packet loss should be less than 5%
Additional info:
Sorry, I'm not very familiar with netperf. What part of the output is showing the packet loss?
Also, where can I get netperf to try to reproduce this?
(In reply to David Gibson from comment #3)
> Also, where can I get netperf to try to reproduce this?
Hi David,
You can get netperf from here.
""
To clarify the packet loss, here is a example without issues tested on two X86 host:
Server: [root@dhcp-10-201 ~]# netserver -L 10.66.9.95 -f -D -4 &
Client: [root@localhost liuzt]# netperf -H 10.66.9.95 -t UDP_STREAM -l 45 -- -m 16384
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
212992 16384 45.00 326513 0 951.03
212992 45.00 326510 951.02
Here , 951.03Mb/s is the client sending data bandwidth, and 951.02 is the server receiving data bandwidth, they are nearly the same, means nearly no packet loss.
Comparing with this, In our scenario, client sending data bandwith is 3429.47Mb/s and server receiving data bandwidth is 0.05Mb/s , So the data loss is almost 100%.
I can reproduce the bug.
But I have to stop firewalld service to allow the server and the client to connect.
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 16384 60.00 2013685 0 4398.93
229376 60.00 10 0.02
Packets seem lost between ibmveth driver and the application.
All packets are received by the driver and sent to the NAPI framework via napi_gro_receive() but are never received by recvfrom().
it seems packets are received while there are available buffers at hypervisor level, and then stops...
The hypervisor stops because it doesn't have any buffer valid.
static ssize_t spapr_vlan_receive()
...
if (!(bd & VLAN_BD_VALID) || (VLAN_BD_LEN(bd) < (size + 8))) {
/* Failed to find a suitable buffer */
...
What I understand of the spapr-vlan protocol is that the driver doesn't issue often enough the H_ADD_LOGICAL_LAN_BUFFER command.
To be able to determine the maximum bandwith I use iperf3 instead of netperf.
server side on guest: iperf3 -s
client side on host: iperf3 --udp -c 192.168.122.117 -l 16384 -b 4G
'-b' is the bandwith in b/s, 4G means "4Gb/s" and in this case we have the same result as with netperf.
Bandwidth Jitter Lost/Total Datagrams
996 Kbits/sec 7113.980 ms 0/76 (0%)
1.99 Mbits/sec 64.239 ms 3/152 (2%)
2.98 Mbits/sec 1.287 ms 16/227 (7%)
3.97 Mbits/sec 0.181 ms 57/302 (19%)
4.95 Mbits/sec 0.084 ms 92/378 (24%)
9.91 Mbits/sec 0.615 ms 365/750 (49%)
99.0 Mbits/sec 0.196 ms 7167/7481 (96%)
992 Mbits/sec 25.710 ms 72112/72665 (99%)
1.99 Gbits/sec 79.970 ms 150088/150288 (100%)
3.00 Gbits/sec 50.301 ms 222135/222310 (100%)
3.99 Gbits/sec 17588.700 ms 213767/213829 (100%)
The last bandwith with less than 5% packet lost is 2Mb/s.
More information:
The driver, after a while fails to give back some buffers to the QEMU with h_add_logical_lan_buffer(), the error is H_RESOURCE.
At the QEMU level, it can't take back the buffers because the rx_buffers is full (dev->rx_bufs >= VLAN_MAX_BUFS (509)) -> H_RESOURCE.
The only way to decrease dev->rx_bufs is to receive a packet from the network (QEMU takes a buffer from there). But the receive function can't take a buffer because all (509) buffers are invalid. So, QEMU can't take buffers to receive, but it can't have new buffers.
The question is: who marks the buffers as VALID ?
Ok, here's what I can figure out from a combination of memory and reading the code.
* The interface uses this concept of a "buffer descriptor" which is a 64-bit quantity including the buffer address, length and some flags (including VALID)
* IIUC, buffer descriptors handed in via h_add_logical_lan_buffer should be VALID.
* When a buffer is consumed by the Rx path, it's descriptor is cleared which also clears VALID. This is the:
vio_stq(sdev, dev->buf_list + dev->use_buf_ptr, 0);
in spapr_vlan_receive().
* dev->rx_bufs is *supposed* to be the number of VALID buffers in the pool. Since you're getting a situation with no valid buffers but rx_bufs too large to allow h_add_logical_lan_buffer() it looks like these are getting out of sync somehow.
I'd add a check in h_add_logical_lan_buffer() to make sure that the guest is not passing in invalid buffer descriptors - that would certainly cause those to get out of sync. I'm guessing that when I wrote it, I thought check_bd() would ensure that, but it looks like it doesn't.
Although if we're leaking buffers like this, I would have expected it to come to a complete halt and not let any data through. You could check if the guest is getting timeouts and resetting the device though, which would fix it temporarily.
What happens:
1- the buf_list is only 509 entries long, and under high pressure it is quickly empty, and QEMU must wait the driver fills it again with h_add_logical_lan_buffer(), but during this waiting period all incoming packets are canceled. Moreover once the 509 entries are filled the driver must wait next incoming packets to try to add remaining available buffers,
2- the size of incoming packets is ~1500 bytes, so after a while the buf_list is filled by 512 bytes long buffers as they are not used. This is why buf_list is not empy but we can't use the buffers it has: their size is too small to receive the incoming packets. This can drive to two consequences: in the worst case, no bigger buffer is available and the packets are discarded, in the better case, "some" (= "a lot" under high pressure) packets are discarded because the receive function becomes "slow" as the receive function has to scan the buf_list to find a well sized buffer and at least the half of buf_list is filled by 512 bytes buffers.
We can solve (1) by adding a "cache" in QEMU spapr-vlan to store released buffers while the buf_list is full (I think we can't increase the size of buf_list).
To solve (2) we can either modify the driver to not use buffer smaller than 2048 bytes or modify the previous "cache" to always add bigger buffers first (but this will not solve the slowness of the receive function when the buf_list is half filled by 512 bytes buffers).
But the root problem seems to be in the way spapr-vlan works, the good solution could be to use virtio-net instead...
Adding an extra queue of packets in qemu is a bad idea. a) it allows guest activity to cause qemu to allocate memory without a clear bound and b) it's likely to mess up application level flow control algorithms (flow control works best when intermediate queues are kept to a minimum).
Remember that blasting UDP packets with no flow control can be an interesting benchmark but every real application must include some kinnd flow control to be usable..
* Changing the driver not to allocate the 512 byte buffers might help - you should be able to experiment without recompiling: it looks like the driver lets you set the numbers of buffers in each pool size from sysfs
*.
* The complex buffer pool stuff in the guest driver seems real overkill - I suspect it's there mostly for the benefit of guests running under PowerVM and may not be well tested with the qemu implementation.
*.
(In reply to David Gibson from comment #12)
...
> * Changing the driver not to allocate the 512 byte buffers might help - you
> should be able to experiment without recompiling: it looks like the driver
> lets you set the numbers of buffers in each pool size from sysfs
I've been able to disable pool0 (512 bytes long) and add buffers in pool1 (2048), there is no more loop to find well sized buffers, but as the internal buffer of spapr-vlan is always 509 entries long it is really often empty. So many packets are discarded at QEMU level (spapr_vlan_can_receive() is false because rx_bufs is 0).
> *.
Perhaps a useless work if we can manage the issue by disabling 512 bytes buffers ?
> *.
IBMVETH_MAX_POOL_COUNT is for the driver internal pools (pool0, pool1, ...).
I think the driver don't know the size of the rx_buffs, as it tries to add buffers until it receives a H_RESOURCE error.
(In reply to Thomas Huth from comment #13)
> .
More bugs on PPC64LE:
- gprof is broken (ib glibc). I have filled a BZ.
- valgrind is broken too:
qemu-system-ppc64: cannot set up guest memory 'ppc_spapr.ram': Invalid argument
The bug seems to be in QEMU, I'll fill a BZ if needed.
- oprofile seems broken too. I'm not able to use "operf --pid", only
"operf --system-wide" and the "--callgraph" parameter doesn't work.
It is not usable. I'll check if a BZ is needed...
Right, but did changing the packet pool sizes change the maximum effective throughput at all? What I'm trying to determine here is whether looping through the buffers in qemu is a cause of the slowness, or if it's simply that the guest is unable to keep up supplying buffers.
Another thing to check: KVM exits are very expensive on Power - even more than on x86. Is the qemu IO thread running on the same host CPU as the guest vcpu threads?
(In reply to David Gibson from comment #16)
For a 100Mb/s iperf3 UDP traffic, with threads on distinct CPUs.
If we change the pool size, the number of packet lost decrease and the jitter is lower.
In the 512 byte packet size case, most of the time, 98%, is used to find a suitable buffer (>= 1504 bytes), 98% of the packets are lost and 75% of the CPU time is for the QEMU main loop (I/O).
In the 2048 byte packet size case, the function spapr_vlan_can_receive() is called 10x more than in the previous case and only 12% is for the buffer loop. We can guess QEMU is waiting for some space in the buffer to send new packets. 88% of the packets are lost and 16% is for the QEMU main loop.
Details:
-----------------------------------------------------------------------------
512 byte packet size:
[ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams
[ 4] 0.00-120.00 sec 1.40 GBytes 99.9 Mbits/sec 0.152 ms 88918/91405 (97%)
[ 4] Sent 91405 datagrams
2,967,183 hw/net/spapr_llan.c:spapr_vlan_can_receive
800,885 {
320,354 VIOsPAPRVLANDevice *dev = qemu_get_nic_opaque(nc);
1,281,416 => net/net.c:qemu_get_nic_opaque (160177x)
.
1,205,236 return (dev->isopen && dev->rx_bufs > 0);
640,708 }
244,552,891 hw/net/spapr_llan.c:spapr_vlan_receive
...
. do {
35,167,012 buf_ptr += 8;
52,750,518 if (buf_ptr >= (VLAN_RX_BDS_LEN + VLAN_RX_BDS_OFF)) {
34,545 buf_ptr = VLAN_RX_BDS_OFF;
. }
.
52,785,063 bd = vio_ldq(sdev, dev->buf_list + buf_ptr);
. DPRINTF("use_buf_ptr=%d bd=0x%016llx\n",
. buf_ptr, (unsigned long long)bd);
11,570,334 } while ((!(bd & VLAN_BD_VALID) || (VLAN_BD_LEN(bd) < (size + 8)))
87,865,114 && (buf_ptr != dev->use_buf_ptr));
...
240,172,586 TOTAL LOOP = 98% of the time of the function
CPU%
75% main_loop
10% kvm_cpu_exec
-------------------------------------------------------------------------------
2048 byte packet size:
[ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams
[ 4] 0.00-120.00 sec 1.40 GBytes 99.9 Mbits/sec 0.082 ms 80648/91411 (88%)
[ 4] Sent 91411 datagrams
25,116,799 hw/net/spapr_llan.c:spapr_vlan_can_receive
6,629,865 {
2,651,946 VIOsPAPRVLANDevice *dev = qemu_get_nic_opaque(nc);
10,607,784 => net/net.c:qemu_get_nic_opaque (1325973x)
.
10,531,096 return (dev->isopen && dev->rx_bufs > 0);
5,303,892 }
45,377,776 hw/net/spapr_llan.c:spapr_vlan_receive
. do {
725,944 buf_ptr += 8;
1,088,916 if (buf_ptr >= (VLAN_RX_BDS_LEN + VLAN_RX_BDS_OFF)) {
712 buf_ptr = VLAN_RX_BDS_OFF;
. }
.
1,089,628 bd = vio_ldq(sdev, dev->buf_list + buf_ptr);
. DPRINTF("use_buf_ptr=%d bd=0x%016llx\n",
. buf_ptr, (unsigned long long)bd);
1,814,860 } while ((!(bd & VLAN_BD_VALID) || (VLAN_BD_LEN(bd) < (size + 8)))
725,944 && (buf_ptr != dev->use_buf_ptr));
5,446,004 TOTAL LOOP = 12% of the time of the function
CPU%
16% main_loop
16% kvm_cpu_exec
Hmm, does limited performance on a non-recommended NIC really warrant high priority?
By the way, it could be that bug 1271496 ("Guest loses packets with 65507 packet size ...") contributes to the bad performance. It's a different bug, but it also causes packets to be dropped (but this time the problem is in the ibmveth driver of the guest). So it might be worth a try to do a "echo 0 > /sys/devices/vio/30000004/pool4/active" or so to see whether this increases the performance at least a little bit.
I think it's unlikely that bug 1271496 is relevant. AFAICT in the case tested here the message size is 16384 bytes. Even with various header overheads that will be much less than the 65507 packet size which triggers the other bug.
(In reply to David Gibson from comment #21)
> I think it's unlikely that bug 1271496 is relevant. AFAICT in the case
> tested here the message size is 16384 bytes. Even with various header
> overheads that will be much less than the 65507 packet size which triggers
> the other bug.
The MTU size in bug 1271496 is still 1500, so the big ICMP packets are fragmented into smaller IP packets there - QEMU still steps through all RX buffer types anyway since it does not distinguish different RX buffer pools as PowerVM is doing it. So assuming that QEMU also uses the big RX buffers here, it's likely that some packets are lost due to bug 1271496 here, too.
(In reply to David Gibson from comment #19)
> Hmm, does limited performance on a non-recommended NIC really warrant high
> priority?
No, looks like a mistake. sorry about that.
This bug might be related to BZ 1210221, so I'll take a look at this here, too, while working on that other bug.
(In reply to Thomas Huth from comment #24)
> This bug might be related to BZ 1210221
I meant BZ 1271496 ("Guest loses packets with 65507 packet size for spapr-vlan emulated NIC card"), of course.
Another interesting observation: The values look very different when running netserver on the KVM host instead of running the netserver in the guest:
MIGRATED UDP STREAM TEST from 192.168.122.214 () port 0 AF_INET to 192.168.122.1 () port 0 AF_INET
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 16384 10.00 54534 0 714.77
229376 10.00 54534 714.77
Not sure yet, but this could maybe be an indication that the bad values that Zhengtong reported could be due to the big QEMU I/O lock, i.e. the spapr-vlan device in QEMU can not send and receive packets simultaneously due to the I/O lock. The receiving I/O thread in QEMU is then busy with the huge amount of received packets and rarely drops the lock, so the sending thread in the guest hardly can send out any packets.
Ok, forget about my conclusion in my last comment, I had just wrong assumptions about what that netperf test is doing.
So some more observations:
1) When running the test between two guests instead of host-to-guest, then the numbers get a little bit better, but still far from being good:
MIGRATED UDP STREAM TEST from 192.168.122.39 () port 0 AF_INET to 192.168.122.170 () port 0 AF_INET
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 16384 20.00 89326 0 585.39
229376 20.00 443 2.90
2) When checking the "RX packets" counters via ifconfig in the guest, I can see that the driver in the guest apparently recorded ~660 MiBs in the 20 seconds while the test was running ... that should give a throughput of 33 MB/s = 264 Mbits/s theoretically - but the netserver only saw less than 1 Mbit/s. Hmmm, I just saw that Laurent already mentioned that in comment 6 ... we might need to find out why the IP layer discards so many packets here...
BTW, problem also occurs on little endian, so I'm setting the hardware field to ppc64le now (since we're only supporting ppc64le on the host officially).
For the record: When using the "e1000" NIC instead of "spapr-vlan", I get values like this:
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 1440 60.00 10852664 0 2083.71
229376 60.00 345587 66.35
So ideally, the spapr-vlan should get similar results as the e1000.
Oops, that test in comment 30 was already with a different block size ... but with block size = 16384, I get similar or even better results with the e1000 NIC:
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 16384 60.00 1765430 0 3856.64
229376 60.00 45784 100.02
When using smaller block sizes (less than the MTU), the results also look much better with the spapr-vlan NIC:
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 1450 60.00 11124413 0 2150.72
229376 60.00 137636 26.61
I think I now basically understood what is going wrong here with the spapr-vlan NIC: Since you're using a packet size of 16384 bytes, which is much bigger than the MTU of 1500 bytes, the netperf tool is sending fragmented UDP packets to the netserver. Since the spapr-vlan interface is really not a high-performance interface, the receiver side in the guest regularly runs out of RX buffers sooner or later, so some of the packets are dropped. Since the test is using fragmented IP packets, all other parts of the UDP packet also have to be dropped by the receiver side if one of the fragments got lost. And apparently for almost all UDP packets, at least one fragment is lost, so that almost all UDP packets are discarded in the guest kernel IP layer. That's why the RX counters of "ifconfig" in the guest show still quite a lot of received data (see comment 28), while the netserver application hardly sees any packets at all - the most part of the data is dropped during fragments reassembly in the IP layer.
So the question is: Why is for example the e1000 NIC showing much better results with the packet size of 16384 bytes than the spapr-vlan NIC? ... I think I also got an answer for that one: The problem is the way the receive buffers are supplied by the guest to QEMU.
The e1000 driver in the guest can supply multiple receive buffers to the emulated NIC in the host at once, by writing an appropriate value to the RDT register (Receive Descriptor Tail). Once QEMU detected the write to the RDT register in the set_rdt() of hw/net/e1000.c, it calls qemu_flush_queued_packets() - and this flushes the receive queue. So if the receiver ran out of packets and the receive queue got stalled, the guest can add multiple new receive buffers at once, and QEMU then immediately tries to flush the queued, received packets into these new buffers. If there are fragmented IP packets waiting, the guest likely added enough receive buffers at once so that all parts of the fragmented packet can be passed to the guest, and the IP layer in the guest kernel then can reassemble the fragmented UDP packet successfully.
Now the interface in the spapr-vlan driver works slightly differently: The guest can only supply one receive buffer at a time with the H_ADD_LOGICAL_LAN_BUFFER hypercall. QEMU then tries to flush the queued packets with the qemu_flush_queued_packets() after each added single buffer. So if the receive buffer queue ran empty at one point in time, QEMU tries to signal single packets to the guest once the guests adds a single buffer with the H_ADD_LOGICAL_LAN_BUFFER hypercall. This of course requires quite a bit of processing overhead, and chances are high that one packet of the fragmented UDP packet is lost or arrives too late in the guest, so that the whole UDP packet is dropped by the UDP layer in the guest.
One possible solution could be that we do not try to flush the RX queue after each RX buffer that has been submitted by the guest, but to wait a little bit 'till there are enough buffers available to hold a whole fragmented UDP packet.
Here is a quick-n-dirty proof-of-concept patch that waits for 200 packets in the RX queue before trying to flush the received packets to the guest:
diff --git a/hw/net/spapr_llan.c b/hw/net/spapr_llan.c
index 9359f37..ce63b0f 100644
--- a/hw/net/spapr_llan.c
+++ b/hw/net/spapr_llan.c
@@ -203,7 +203,7 @@ static ssize_t spapr_vlan_receive(NetClientState *nc, const uint8_t *buf,
}
if (!dev->rx_bufs) {
- return -1;
+ return 0;
}
if (dev->compat_flags & SPAPRVLAN_FLAG_RX_BUF_POOLS) {
@@ -212,7 +212,7 @@ static ssize_t spapr_vlan_receive(NetClientState *nc, const uint8_t *buf,
bd = spapr_vlan_get_rx_bd_from_page(dev, size);
}
if (!bd) {
- return -1;
+ return 0;
}
dev->rx_bufs--;
@@ -554,6 +554,9 @@ static target_long spapr_vlan_add_rxbuf_to_pool(VIOsPAPRVLANDevice *dev,
dev->rx_pool[pool]->bds[dev->rx_pool[pool]->count++] = buf;
+ if (dev->rx_pool[pool]->count > 200)
+ qemu_flush_queued_packets(qemu_get_queue(dev->nic));
+
return 0;
}
@@ -627,7 +630,7 @@ static target_ulong h_add_logical_lan_buffer(PowerPCCPU *cpu,
dev->rx_bufs++;
- qemu_flush_queued_packets(qemu_get_queue(dev->nic));
+ //qemu_flush_queued_packets(qemu_get_queue(dev->nic));
return H_SUCCESS;
}
With this patch applied, I get much better results with netperf:
MIGRATED UDP STREAM TEST from 192.168.122.1 () port 0 AF_INET to 192.168.122.214 () port 0 AF_INET
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 16384 60.00 1835897 0 4010.57
229376 60.00 20615 45.03
The final solution would require some kind of timer for flushing the queue, of course, in case the guest never tries to add 200 packets to the guest.
Suggested patch upstream:
Fix included in qemu-kvm-rhev-2.6.0-5.el7
I do test again with the fixed version : qemu-kvm-rhev-2.6.0-5.el7
in Guest:
# netserver -p 44444 -L 192.168.122.32 -f -D -4 &
in Host:
#netperf -p 44444 -L 192.168.122.1 -H 192.168.122.32 -t UDP_STREAM -l 20 -- -m 16384
and the result is :
Socket Message Elapsed Messages
Size Size Time Okay Errors Throughput
bytes bytes secs # # 10^6bits/sec
229376 16384 20.00 583811 0 3826.05
229376 20.00 25627 167.95
The performance is much better than before, obviously. but not good enough as in comment #4.
Hi, Thomas,
Does this performance is as expected for spapr-vlan ?
Yes, performance is expected to be much worse than for virtio-net with vhost enabled, so IMHO you can mark this bug as verified.
Rationale: virtio-net with vhost can do much faster networking since it bypasses the bottlenecks in QEMU with the vhost kernel module. So if you need something to compare spapr-vlan with, you should rather compare it to the performance of an emulated e1000 card or virtion-net *without* vhost acceleration here. (And even then the performance of spapr-vlan will likely be worse, since the interface of this NIC is really defined in a bad way - the guest can only supply one buffer at a time via a hypercall, so this will always be a bottleneck).
Thanks, Thomas..
|
https://bugzilla.redhat.com/show_bug.cgi?id=1210221
|
CC-MAIN-2020-34
|
refinedweb
| 4,295
| 73.37
|
Google Cloud Functions can be written in Node.js, Python, and Go, and are executed in language-specific runtimes. The Cloud Functions execution environment varies by your chosen runtime. The runtime overview pages provide further details about each runtime environment:
Types of Cloud Functions
There are two distinct types of Cloud Functions: HTTP functions and background functions.))
Go
//)) }
Background functions
You can use background functions to handle events from your Cloud infrastructure, such as messages on a Cloud Pub/Sub topic, or changes in a Cloud Storage bucket.
For details, see Writing Background Functions.
Example:
Node.js 8/10
/** * Background Cloud Function. * * @param {object} data The event payload. * @param {object} context The event metadata. */ exports.helloBackground = (data, context) => { return `Hello ${data.name || 'World'}!`; };
Node.js 6 (Deprecated)
/** * Background Cloud Function. * * @param {object} event The Cloud Functions event. * @param {function} callback The callback function. */ exports.helloBackground = (event, callback) => { callback(null, `Hello ${event.data.name || 'World'}!`); };
Python
def hello_background(data, context): """Background Cloud Function. Args: data (dict): The dictionary with data specific to the given event. context (google.cloud.functions.Context): The Cloud Functions event metadata. """ if data and 'name' in data: name = data['name'] else: name = 'World' return }
Structuring source code
In order for Cloud Functions to find your function's definition, each runtime has structuring requirements for your source code:
Node.js
For the Node.js runtimes, your function's source code must be exported from a
Node.js module, which Cloud Functions loads using a
require() call.
In order to determine which module to load, Cloud Functions uses the
main field in your
package.json file. If the
main field is not specified,
Cloud Functions loads code from
index.js.
For example, the following configurations of source code are valid:
A single
index.jsfile at the root of your project that exports one or more functions:
. └── index.js
An
index.jsfile that imports code from a
foo.jsfile and then exports one or more functions:
. ├── index.js └── foo.js
An
app.jsfile that exports one or more functions, with a
package.jsonfile that contains
"main": "app.js":
. ├── app.js └── package.json
Python
For the Python runtime, your function's entrypoint must be defined in a Python
source file at the root of your project named
main.py.
For example, the following configurations of source code are valid:
A single
main.pyfile at the root of your project that defines one or more functions:
. └── main.py
A
main.pyfile with a
requirements.txtfile that specifies dependencies:
. ├── main.py └── requirements.txt
A
main.pyfile that imports code from a local dependency:
. ├── main.py └── mylocalpackage/ ├── __init__.py └── myscript.py
Go
For the Go runtime, your function must be in a Go package at the root of your
project. Your function cannot be in
package main. Sub-packages are only
supported when using Go modules.
For example, the following configurations of source code are valid:
A package at the root of your project that exports one or more functions:
. └── function.go
A package at the root of your project that imports code from a sub-package and exports one or more functions:
. ├── function.go ├── go.mod └── shared/ └── shared.go
A package at the root of your project with a sub-directory that defines a
package main:
. ├── cmd/ | └── main.go └── function.go
Specifying dependencies
You specify your function's dependencies idiomatically based on the runtime you are using. For more details, see the appropriate page:
Naming Cloud Functions
Cloud Functions have a "name" property that is set at deploy time, and once set,
it cannot be changed. The name of a function is used as its identifier and it
must be unique within a region. By default, the name of a function is also used
as the entry point into your source code. For example, a function named
foo will, by default, execute the
foo() function in the source code you
deploy. If you want to have a different function executed, you can use the
--entry-point flag at deploy time. For details, see the
Deploying Cloud Functions documentation.
|
https://cloud.google.com/functions/docs/writing/?hl=it
|
CC-MAIN-2019-26
|
refinedweb
| 675
| 59.9
|
October 13, 2011 at 12:00 PM
Decaptcher is a website that offers automated CAPTCHA image solving for the price of a fraction of a penny per image. They offer round the clock CAPTCHA solving, which they claim is all done by humans over on their end, which leads me to believe that there is some massive sweatshop somewhere in India wherein there are several hundred small children being forced to solve CAPTCHAs all day. Oh well, it makes for a great tool for writing bots.
Decaptcher doesn't have an official Python API, so I cooked up my very own based off of their terrible documentation, enjoy!
Usage Example
import decaptcher d = decaptcher("username", "password") print "You have $%.2f left on your Decaptcher balance." % d.get_balance() print "CAPTCHA image answer is: %s" % d.solve_image(path_to_image_file)
This module requires Requests
Download: decaptcher.py
|
http://teh-1337.studiobebop.net/posts/189
|
CC-MAIN-2018-22
|
refinedweb
| 143
| 62.68
|
lizard-map 5.2
Basic map setup for lizard web siteslizard-map
==========
Lizard-map provides basic map interaction for `Django
<http:"">`_ applications that use a `lizard-ui
<http: pypi.python.`_ user interface. We designed it at
`Nelen & Schuurmans <http:"">`_.
.. image::
:target:
Translation status:
.. image::
:target: <http: pypi.python.`_'
Credits
=======
- Main coders: Jack Ha and `Reinout van Rees
<http: reinout.vanrees.`_ (`Nelen & Schuurmans
<http:"">`_).
- Core workspace interaction concept: Jan-Maarten Verbree and
Bastiaan Roos (`Nelen & Schuurmans <http:"">`_).
Changelog of lizard-map
=======================
5.2 (2015-01-15)
----------------
- Remove defaults from JSONFields in old migrations. The default
default (dict) is fine, and incorrect defaults caused some
migrations to fail.
5.1 (2014-12-15)
----------------
- Upped lizard-ui requirement.
5.0 (2014-12-15)
----------------
- You can now save the dashboard just like you could already save the
workspace. They're not shown on the homepage, though. If needed you
can add an app icon for that.
- You can add a ``disclaimer_text`` setting in the admin now. This is copied
verbatim to the first window of the on-screen tour. So don't put html tags
in here.
- Removed pan-to-click-location, it is simply to obtrusive.
- The display-name-while-hovering-over-the-map functionality now only searches
in the first layer (=workspace item), not in all of them. This way, it is
more predictable which results you get.
- Removed 'week' from the period selection. 'Week+1' is now called 'week', but
retained the week+1 functionality. Added 'halfyear' option.
- Using 'orangered'instead of yellow in the graphs as HHNK wants that.
- Added lizard-security to WorkspaceStorage: this allows you to effectively
filter the start page.
- Set workspace on default as private.
- Fix grammatical mistakes in info-tour.
- Move to Lizard 5.
- Add `private` flag to WorkspaceStorage model. If a WorkspaceStorage
instance is labelled private, it is not shown to anonymous users.
- Migrated to mapnik 2.2.0.
- Added action for elevationprofile
- Update translations.
- Removed console.log statements. IE hangs with them.
- Make two untranslated strings translatable.
- Update source language (english) django.po
- Add Box awesome.
- Add support for correct getFeatureInfo for lizard wms.
- Reintroduced workspace save icon (admin only).
- Remove animatable.
- Add WMS filter on the page.
- Fix bug where IE9 couldn't use the search bar; we should use JSONP
for cross-site requests.
- Re-added collage screen (called "Dashboard" now), mostly by re-enabling old
functionality. Bigger change is the layout of the actual main collage page:
the labels and so are now next to the graphs as there's no separate sidebar
anymore.
- Fix timezones once more.
- Fix text, layout and z-iondex positions of info tour wizard.
- Hiding rainapp's period summary on the collage screen.
- Opening dashboard/collage in new tab.
- UI updates for the dashboard page.
- Remove coordinates.DEFAULT_MAP_SETTINGS (unused since 2011), move default
map code from views.py and coordinates.py into models.BackgroundMap.
- Move settings and their defaults to conf.py (using django-appconf).
- The Setting model's .get() and .extent() functions now don't take a
default anymore, rather if a Setting isn't found they get their
defaults from normal Django settings -- a setting called "mysetting"
uses the LIZARD_MAP_DEFAULT_MYSETTING_SETTING setting. Setting
setting setting.
- Several defaults were updated to what lizard5-site sets in its
base.py, so the settings can be removed there. No other settings
were actually set in lizard5-site, so how configurable do these
things need to be?
- Added reloading of graphs upon flot pan/zoom. The
according-to-the-manual-zoom start/end date is passed in the normal way to
the backend: no changes necesseary. This is expensive, though, so the
backend *must* add an extra ``.dynamic-graph-zoomable`` class in addition to
the current ``.dynamic-graph`` class.
- Made the interaction with graphs that fail to load nicer.
- View state persists also on the dashboard page now.
- Added 'please log in' hint when there are no visible workspace storages.
- The 'default_range_type' Setting can now be set to override the
default date range. Possible values are 'today', '2_day', 'week',
'week_plus_one' (default), 'month' and 'year'.
- Use the function values_multiple_timeseries() to export timeseries from
lizard-fancylayers adapter.
- Add LanguageView to setup a different language per site.
- Create LocaleFromSettingMiddleware to use language_code from Setting models.
4.28 (2013-05-06)
-----------------
- Added a completely transparant icon, ghost.png, for layers that
shouldn't be shown but for which the popup should still work.
- Some changes to be iPad friendly were made.
- The small layerswitcher is moved to the upper bar for easier use.
- The left hand zoom in and out buttons are not shown on iPad.
- 'Zoom to start location' is now just an icon.
4.27 (2013-04-03)
-----------------
- Fixed tab_titles being undefined when a popup of collage items is
opened.
- Merged functionality from the deltaportaal lizard-map branch:
- Showing metadata at the bottom of the regular description popup. The popup
is now an 'i' you should click instead of an on-hover dialog. Works better
with an ipad. Note that there's now a ``lizard_map.css`` again.
- CQL filtering is possible on featureinfo items on wms layers.
- Popups opened from the sidebar now disappear when the sidebar scrolls. No
more zombie popups.
4.26 (2013-03-20)
-----------------
- Tabs in the popup now, by default, get the name of the first workspace item
whose result is shown. This is waaaaay nicer than "tab 1, tab 2, tab 3".
4.25.6 (2013-03-13)
-------------------
- Fixed IE7 error caused by extraneous comma in animations.js.
4.25.5 (2013-02-27)
-------------------
- Haastige spoed...
4.25.4 (2013-02-27)
-------------------
- Default number of frames in animation set to 720.
4.25.3 (2013-02-27)
-------------------
- Changed animation speed from 500ms to 1000ms per frame.
4.25.2 (2013-02-27)
-------------------
- Moved animations.js import again.
4.25.1 (2013-02-27)
-------------------
- Changed animations.js import order (caused error).
4.25 (2013-02-26)
-----------------
- The change described in 4.24 didn't really work well, because the
session object wasn't created yet when the default workspace was
copied. This is fixed.
- Removed hour / day clamping (rounding) in the daterangepicker. Values for
dt_start and dt_end are now simply a relative period based on the current
time.
4.24 (2013-02-25)
-----------------
- It is now possible to use some stored workspace as a "default
workspace" for users who get a newly created workspace.
If the Setting 'default_workspace_anonymous_user' exists and is the
secret slug of some existing stored workspace, then the items in it
will be copied to any anonymous user's workspace when it is first
created.
The same holds for 'default_workspace_user' and logged in users,
although it is probably less useful for them since their workspace
is only initially created once, after that they keep using their
existing one.
4.23 (2013-02-19)
-----------------
- Add vietnamese translations for month names via google translate.
- Remove zc.buildout >= 2.0.1 from setup.py since it is not a dependency.
4.22 (2013-02-19)
-----------------
- Added animation support for wms urls that have 'time' in them. Includes
backbone 0.9.10, underscore 1.4.4.
4.21 (2013-02-19)
-----------------
- Manage translation strings with Transifex. Update en (source) and nl
translations. Use nens/translations package for this.
- Add vietnamese django.po file from Transifex.
- Upgrade to zc.buildout 2.0.1.
4.20 (2013-01-22)
-----------------
- Fix context instance instantiation in html_default method.
4.19 (2013-01-21)
-----------------
- Add RequestContext instance when rendering a template in html_default
method. This way request-related tags and context variables can be
used when rendering the template.
4.18 (2013-01-17)
-----------------
- Adjust FlotGraphAxes to enable threshold lines.
- PEP8 fixes.
4.17 (2013-01-10)
-----------------
- Fix timezone handling for Flot graphs.
The leading principle is that Javascript should do no timezone
manipulation on time data from the past, because that would mean
that the timezone of events recorded in the past depends on things
like the _current_ summer / winter time setting. A graph of the same
data should show the same information regardless of when it is
viewed.
In Lizard we internally work with UTC datetimes as much as possible,
and convert these times to the site's timezone (usually
Europe/Amsterdam) right before handing them to Javascript.
4.16 (2012-12-19)
-----------------
- Fixed urls.py, so it won't recusively include other lizard-* URLs when
running as part of a site.
4.15 (2012-12-20)
-----------------
- Removed animationsettings for now. They're used in a tiny number of older
projects and probably have to be re-instated later on. But the daterange
implementation used by animationsettings has changed anyway. Perhaps
implement it in the projects that need it?
- We're depending on the 2.x version of Django REST framework now. This means
updating other projects that use Django REST framework. For a starting
point, see
- Removed all daterange tests as none of them work. ``daterange.py`` itself
has not been removed as it is used in quite a lot of views.
- Added configchecker test (``bin/django check_config``) whether ``USE_TZ =
True`` is set in your setttings file.
- Added an "add_percentiles" function to FlotGraph, that allows
plotting filled-in "percentile areas" around graphs. Will be
implemented for Matplotlib too, but that's not done yet.
- Added a workaround in ViewStateService, because Forms seem no longer
supported by rest_framework.
4.14 (2012-12-04)
-----------------
- Changed some text and changed location_list to always load initial results
on opening.
4.13 (2012-12-03)
-----------------
- Fixing automatic migration step ``0009`` by deleting/adding the
``identifier`` column on ``CollageEditItem`` instead of altering it. The old
``JSONField``'s implementation is incomplete and wreaks the migration.
- Store current extent when saving a workspace, and load it back again
when loading a workspace which has an extent set.
4.12 (2012-11-27)
-----------------
- Nothing big.
4.11 (2012-11-29)
-----------------
- Slightly refactored the 'workspace_item_toggle' view so that its
main functionality is now in the WorkspaceEdit model, so that it can
be called from other functions as well.
As a result, WorkspaceEdit now has methods 'toggle_workspace_item'
and 'add_workspace_item'.
4.10 (2012-11-22)
-----------------
- Support mixed flot/matplotlib (IE8) graphs.
- Fixed some IE8 issues.
- Added some more zoomLevels for WMS background layers.
- Graphs now reload on a date change.
- Removed some obsolete code regarding animation.
- Changed hover popup to one built with jQuery, as the previously used
OpenLayers one causes an unnecessary redraw on IE8.
- Moved all graph code to lizard-map, which should be a more suitable place
for it.
- Fixed usage of naive datetime objects.
- Added zoom/pan linked graphs.
- Added support for a singleTile WMS background layer.
- Location list now shows some initial results.
- Fixed various small bugs.
4.9 (2012-10-18)
----------------
- Fixed some styling issues.
- Fix test build config, travis & pep8.
4.8 (2012-10-05)
----------------
- Fix a missing css and made some javascript code optional.
4.7 (2012-10-04)
----------------
- Relicensed from GPL to LGPL.
- Added MAP_SHOW_MULTISELECT, MAP_SHOW_DATE_RANGE and MAP_SHOW_DEFAULT_ZOOM
optional settings to make it possible to hide the three default lizard-map
content actions. They're True by default.
- Added popup with subtabs.
- Merged and cleaned various JavaScript files.
- Link to Pillow instead of PIL.
- Move most CSS styling to lizard-ui.
- Fix some styling issues, typo's.
- Revived the collage page.
- Switch to a Twitter Bootstrap based date-range selector.
- Fix legend order.
- Disable obsolete OpenLayers reprojection.
- Changed default graph colours.
- Popup is shown directly after click on map.
- Add some iPad exceptions and add graph navigation.
- Add support for location search.
- Add more resolutions for Rijksdriehoek.
- Started a simple JavaScript view state holder on the client.
In the future this will hold map extent, map layers etc. as well.
- Tables now have borders, as requested.
4.6 (2012-08-23)
----------------
- Fix graphs and popups: switch from jquery-tools tabs to superior jquery-ui tabs.
- Properly resize graphs instead of reloading them.
4.5 (2012-08-14)
----------------
- Fix OpenStreetMap pink tiles at Firefox.
4.4 (2012-08-14)
----------------
- Flot graphs: fallback to .axes label if one is available, because flot only supports a single ylabel.
- Flot graphs: pass x and y limits so we can determine tick size.
- Multiple select: don't show animation when nothing is found.
- Mapnik WMS rendering: reduce memory usage because of buffers being copied multiple times.
- Changed lots of core stuff: no longer combine workspace layers into a single WMS layer.
- Added multi-url legend support.
- Fix some bad hover_popup code.
- OpenLayers: fix iPad.
4.3 (2012-07-10)
----------------
- If a legend_image url is empty, we don't show the legend anymore.
4.2 (2012-07-10)
----------------
- In a map view, you can now provide ``.extra_wms_layers()`` to add extra
WMS to the map. Handy for layers that are really part of a specific content
item. The list of dictionaries that this method has to return is really an
unfriendly API: this needs refactoring later on.
- Internal refactoring. Renamed ``.maps()`` to ``.backgrounds()`` in the
views. This (hopefully) isn't used externally.
4.1.1 (2012-06-29)
------------------
- Importing JSONField in fields.py as otherwise the migrations fail.
4.1 (2012-06-28)
----------------
- Requiring newer django-jsonfield version (which works with django's multi-db
functionality). Removed our custom JSONField in favour of
django-jsonfield's one.
4.0 (2012-06-19)
----------------
- Added flot graph axis label support.
- Some table styling.
- Fix date range popup.
- Readded the option to save a workspace.
- Readded the nothingFoundPopup.
- Support EPSG:3857 alias for google coordinates.
- Added feature to load stored workspace in editable workspace.
- Add moving box on collage-add and multiple select.
- Fix my-collage popups.
- Reinstated multi-select functionality.
4.0b6 (2012-06-01)
------------------
- Add support for bar graphs (Flot).
- Remove an obsolete console.log call.
4.0b5 (2012-05-31)
------------------
- Removed OpenLayers.ImgPath of theme 'Dark'.
- Minor styling fix for workspaces.
- Add the new FlotGraph.
4.0b4 (2012-05-29)
------------------
- Fixed Javascript not finding href attributes during click events.
4.0b3 (2012-05-29)
------------------
- Collage and workspace are now styled using tables.
4.0b1 (2012-05-29)
------------------
- Added missing dependency lizard_security.
- Fixed popup and popup contents styling.
- Collage and workspace UI working again.
4.0a1 (2012-05-18)
------------------
- Requiring lizard-ui 4.0 alpha: the new twitter bootstrap layout.
- Using compiled css instead of less.
- Removed old HomepageView and renamed the MapIconView.
- Using new twitter-bootstrap layout. Using the MapView class based view is
now really mandatory to get everything to work.
- Renamed /media to /static. That's django-staticfile's new standard.
- Timeseries can now be localized in Graph object.
- Fixed syntax error in jquery.workspace.js.
- Adds STATIC_URL to application icons.
- Making the normal AppView the main cbv instead of the temporary MapView name.
3.31 (2012-05-15)
-----------------
- Changed map click popup to jQuery ui dialog: it is now movable and
resizable.
- The maximum number of tabs in popups has been made configurable.
- If an item is removed from the workspace while rendering (for instance because an Exception
was raised), the page loads without giving an internal server error caused by trying to
create a Legend.
3.30 (2012-04-26)
-----------------
- Added one icon.
3.29 (2012-04-25)
-----------------
- Added two icons.
3.28 (2012-04-13)
-----------------
- Re-enabling hover functionality on saved workspaces.
3.27.1 (2012-04-13)
-------------------
- Also removed references to touch.js and lizard_touch.js from the templates...
3.27 (2012-04-13)
-----------------
- Required lizard-ui 3.14 (new Openlayers).
- Removed touch.js, necessary with the new Openlayers version.
- Uncommented extent() in WorkspaceItemAdapter. It should be there
because it is one of the methods that can be overridden by
implementing adapters.
3.26 (2012-04-06)
-----------------
- Changed collage detail template so that apps can configure it a bit more.
Collage items (that are put in groups on the collage page) have properties
that control the header shown over the group (data_description), which edit
dialog to show for a collage item edit button (collage_detail_edit_action),
whether to show the whole Edit block at all (collage_detail_show_edit_block),
and whether to show the statistics block (collage_detail_show_statistics_block).
These functions in turn call functions in their adapters, with an identifier
as argument (because one adapter can have items in different groups, with different
settings. This way it gets the identifier of the first item in each group):
def collage_detail_data_description(self, identifier, *args, **kwargs):
default 'Grafiek'
def collage_detail_edit_action(self, identifier, *args, **kwargs):
default 'graph'
def collage_detail_show_edit_block(self, identifier, *args, **kwargs):
default True
def collage_detail_show_statistics_block(self, identifier, *args, **kwargs):
default True
*args and **kwargs are meaningless but present in case the functions' signatures
change in the future. These functions can be overridden in your adapter.
3.25 (2012-04-04)
-----------------
- Improved docstrings at a few places (mainly location() in
WorkspaceItemAdapter)
- Added method 'adapter_layer_json' to WorkspaceItemAdapter, helpful
to generate this bit of json when it's needed.
- Added 'adapter': self to html_default's template context variables.
This gives templates access to adapter's methods and attributes,
like adapter.adapter_class and adapter.adapter_layer_json.
3.24 (2012-03-05)
-----------------
- It's now possible to not use a popup_click_handler.
3.23 (2012-02-16)
-----------------
- Added grouping_hint option to the result of adapter.search(), to make it
possible for a single workspace layer to open a popup with multiple tabs.
3.22 (2012-01-27)
-----------------
- Translation fixes, added breadcrumb to the workspace storage
page. Last fixes before "Lizard 3.0" release?
3.21 (2012-01-26)
-----------------
- Make sure graphs never zoom in so far that they show Y-axis values
with more than 2 decimals.
3.20 (2012-01-26)
-----------------
- Changed waterstand icon from triangle pointing up to triangle
pointing down.
- Changed workspace save/load functionality. Now workspaces can only
be saved, which gives them a "secret slug" (a string with random
characters), and the workspace detail page is opened in a new page.
The URL to this page includes the secret slug and can be shared with
others. The workspace shown on the page can't be changed. The
"workspace load" button is gone until we have a nice user interface
that can show many saved workspaces, and a way to deal with user
privileges.
This is minimal functionality that will be improved in later
versions.
3.19 (2012-01-23)
-----------------
- Removed Download button because we don't have working background maps
- Added a nice calendar to the period selection dialog
- Fixed bug with opacity slider and WMS layers
- Added some functions for the collage detail page, so that different apps
can show different titles and/or hide the Edit button.
3.18 (2012-01-17)
-----------------
- Breadcrumbs for application screens, first
page of applications
- Possibility for apps to add their own breadcrumbs
3.17 (2012-01-13)
-----------------
- Fixed bug where items on the collage page didn't have access to the
request (and therefore not to start- and end dates).
3.16 (2012-01-10)
-----------------
- Fix bug with editing collages.
3.15 (2012-01-05)
-----------------
- Fix bug where X-label of graph wasn't visible.
3.14.1 (2012-01-05)
-------------------
- Nothing changed yet.
3.14 (2012-01-05)
-----------------
- Hack to prevent error when a dictionary key doesn't exist.
3.13 (2012-01-04)
-----------------
- Skip map layers without params in downloaded image. (internal server
error fix)
3.12.1 (2012-01-02)
-------------------
- Fix bug: not every adapter has an extent
3.12 (2012-01-02)
-----------------
- The workspace item zoom button is back and works.
- Changed "jouw" in some tooltip strings to "uw".
3.11 (2011-12-21)
-----------------
- Added functions in collage_edit and workspace_edit to check whether
certain items already exist in them.
- Fixed bug where items could be added to a collage several times.
3.10 (2011-12-21)
-----------------
- New template tag 'if_in_workspace_edit' that can return a string
if a given item's name is present in the workspace.
3.9 (2011-12-21)
----------------
- Removed some max_lengths in forms.py, because it caused valid forms
to fail. There is no reason JSON fields should have a hard limit,
and other fields should have the same limit as in the model.
3.8 (2011-12-20)
----------------
- Added 'transform_point' utility function that can use the site's
projection Setting to transform points to a desired projection.
3.7 (2011-12-20)
----------------
- Made it possible to scale y-axis of graphs manually (it used to be
possible, except then the y-axis would be recalculated afterwards)
3.6 (2011-12-19)
----------------
- WorkspaceItemAdapter's html_default() can use the
extra_render_kwargs kwarg again. Subclasses can use it to send
variables to the template and still use the html_default method for
most of the work.
- Added a block popup_title to html_default.html so that the title
can be changed in extending templates.
- Downloads (All Versions):
- 43 downloads in the last day
- 752 downloads in the last week
- 3571 downloads in the last month
- Author: Reinout van Rees
- License: LGPL
- Categories
- Package Index Owner: reinout, jackha, alexandr.seleznev, nens, rvanlaar
- Package Index Maintainer: alexandr.seleznev, remcogerlich
- DOAP record: lizard-map-5.2.xml
|
https://pypi.python.org/pypi/lizard-map
|
CC-MAIN-2015-22
|
refinedweb
| 3,478
| 69.58
|
Say I have:
class errorManager{ private: vector<string> n1; vector<string>n2; std::string name; public: errorManager() { name = test.txt; } void addtext(std::string first,std::string second){ ofstream file; file.open (name, ios::out | ios::app); file << error << endl; file << endl; file << error_desc; file << endl; n1.push_back(first); n2.push_back(second); file.close(); } };
and I have another class that just has a member of one of the above types.That class contains a function,that simply calls addtext("t","t")
Both classes are placed in a dll and have ALL their functions __declspec(dllexport)
STILL if I create a project,include only the errorManager dll,create an object of that type and call addtext("t","t") i get NO error!
This is where the error redirects me:
if (_Inside(_Ptr)) return (assign(*this, _Ptr - _Myptr(), _Count)); // substring if (_Grow(_Count)) { // make room and assign new stuff _Traits::copy(_Myptr(), _Ptr, _Count); _Eos(_Count); } return (*this); }
The error: Microsoft Visual Studio C Runtime Library has detected a fatal error ...
Edited by noatom, 03 August 2013 - 11:22 AM.
|
http://www.gamedev.net/topic/646202-help-finding-bug-in-code/
|
CC-MAIN-2014-23
|
refinedweb
| 178
| 50.46
|
Simulating color vision deficiencies in the Blink Renderer
Published on
This article describes why and how we implemented color vision deficiency simulation in DevTools and the Blink Renderer.
Note: If you prefer watching a presentation over reading articles, then enjoy the video below! If not, skip the video and read on.
Background: bad color contrast #
Low-contrast text is the most common automatically-detectable accessibility issue on the web.
According to WebAIM’s accessibility analysis of the top 1-million websites, over 86% of home pages have low contrast. On average, each home page has 36 distinct instances of low-contrast text.
Using DevTools to find, understand, and fix contrast issues #
Chrome DevTools can help developers and designers to improve contrast and to pick more accessible color schemes for web apps:
- The Inspect Mode tooltip that appears on top of the web page shows the contrast ratio for text elements.
- The DevTools color picker calls out bad contrast ratios for text elements, shows the recommended contrast line to help manually select better colors, and can even suggest accessible colors.
- Both the CSS Overview panel and the Lighthouse Accessibility audit report lists low-contrast text elements as found on your page.
We’ve recently added a new tool to this list, and it’s a bit different from the others. The above tools mainly focus on surfacing contrast ratio information and giving you options to fix it. We realized that DevTools was still missing a way for developers to get a deeper understanding of this problem space. To address this, we implemented vision deficiency simulation in the DevTools Rendering tab.
In Puppeteer, the new
page.emulateVisionDeficiency(type) API lets you programmatically enable these simulations.
Color vision deficiencies #
Roughly 1 in 20 people suffer from a color vision deficiency (also known as the less accurate term "color blindness"). Such impairments make it harder to tell different colors apart, which can amplify contrast issues.
As a developer with regular vision, you might see DevTools display a bad contrast ratio for color pairs that visually look okay to you. This happens because the contrast ratio formulas take into account these color vision deficiencies! You might still be able to read low-contrast text in some cases, but people with vision impairments don’t have that privilege.
By letting designers and developers simulate the effect of these vision deficiencies on their own web apps, we aim to provide the missing piece: not only can DevTools help you find and fix contrast issues, now you can also understand them!
Simulating color vision deficiencies with HTML, CSS, SVG, and C++ #
Before we dive into the Blink Renderer implementation of our feature, it helps to understand how you’d implement equivalent functionality using web technology.
You can think of each of these color vision deficiency simulations as an overlay covering the entire page. The Web Platform has a way to do that: CSS filters! With the CSS
filter property, you can use some predefined filter functions, such as
blur,
contrast,
grayscale,
hue-rotate, and many more. For even more control, the
filter property also accepts a URL which can point to a custom SVG filter definition:
<style>
:root {
filter: url(#deuteranopia);
}
</style>
>
The above example uses a custom filter definition based on a color matrix. Conceptually, every pixel’s
[Red, Green, Blue, Alpha] color value is matrix-multiplied to create a new color
[R′, G′, B′, A′].
Each row in the matrix contains 5 values: a multiplier for (from left to right) R, G, B, and A, as well as a fifth value for a constant shift value. There are 4 rows: the first row of the matrix is used to compute the new Red value, the second row Green, the third row Blue, and the last row Alpha.
You might be wondering where the exact numbers in our example come from. What makes this color matrix a good approximation of deuteranopia? The answer is: science! The values are based on a physiologically accurate color vision deficiency simulation model by Machado, Oliveira, and Fernandes.
Anyway, we have this SVG filter, and we can now apply it to arbitrary elements on the page using CSS. We can repeat the same pattern for other vision deficiencies. Here's a demo of what that looks like:
If we wanted to, we could build our DevTools feature as follows: when the user emulates a vision deficiency in the DevTools UI, we inject the SVG filter into the inspected document, and then we apply the filter style on the root element. However, there are several problems with that approach:
- The page might already have a filter on its root element, which our code might then override.
- The page might already have an element with
id="deuteranopia", clashing with our filter definition.
- The page might rely on a certain DOM structure, and by inserting the
<svg>into the DOM we might violate these assumptions.
Edge cases aside, the main problem with this approach is that we’d be making programmatically observable changes to the page. If a DevTools user inspects the DOM, they might suddenly see an
<svg> element they never added, or a CSS
filter they never wrote. That would be confusing! To implement this functionality in DevTools, we need a solution that doesn’t have these drawbacks.
Let’s see how we can make this less intrusive. There’s two parts to this solution that we need to hide: 1) the CSS style with the
filter property, and 2) the SVG filter definition, which is currently part of the DOM.
<!-- Part 1: the CSS style with the filter property -->
<style>
:root {
filter: url(#deuteranopia);
}
</style>
<!-- Part 2: the SVG filter definition -->
>
Avoiding the in-document SVG dependency #
Let’s start with part 2: how can we avoid adding the SVG to the DOM? One idea is to move it to a separate SVG file. We can copy the
<svg>…</svg> from the above HTML and save it as
filter.svg—but we need to make some changes first! Inline SVG in HTML follows the HTML parsing rules. That means you can get away with things like omitting quotes around attribute values in some cases. However, SVG in separate files is supposed to be valid XML—and XML parsing is way more strict than HTML. Here’s our SVG-in-HTML snippet again:
>
To make this valid standalone SVG (and thus XML), we need to make some changes. Can you guess which?
first change is the XML namespace declaration at the top. The second addition is the so-called “solidus” — the slash that indicates the
<feColorMatrix> tag both opens and closes the element. This last change is not actually necessary (we could just stick to the explicit
</feColorMatrix> closing tag instead), but since both XML and SVG-in-HTML support this
/> shorthand, we might as well make use of it.
Anyway, with those changes, we can finally save this as a valid SVG file, and point to it from the CSS
filter property value in our HTML document:
<style>
:root {
filter: url(filters.svg#deuteranopia);
}
</style>
Hurrah, we no longer have to inject SVG into the document! That’s already a lot better. But… we now depend on a separate file. That’s still a dependency. Can we somehow get rid of it?
As it turns out, we don’t actually need a file. We can encode the entire file within a URL by using a data URL. To make this happen, we literally take the contents of the SVG file we had before, add the
data: prefix, configure the proper MIME type, and we’ve got ourselves a valid data URL that represents the very same SVG file: benefit is that now, we no longer need to store the file anywhere, or load it from disk or over the network just to use it in our HTML document. So instead of referring to the filename like we did before, we can now point to the data URL:
<style>
:root {
filter: url(>#deuteranopia');
}
</style>
At the end of the URL, we still specify the ID of the filter we want to use, just like before. Note that there’s no need to Base64-encode the SVG document in the URL—doing so would only hurt readability and increase file size. We added backslashes at the end of each line to ensure the newline characters in the data URL don’t terminate the CSS string literal.
So far, we’ve only talked about how to simulate vision deficiencies using web technology. Interestingly, our final implementation in the Blink Renderer is actually quite similar. Here’s a C++ helper utility we’ve added to create a data URL with a given filter definition, based on the same technique:
AtomicString CreateFilterDataUrl(const char* piece) {
AtomicString url =
"data:image/svg+xml,"
"<svg xmlns=\"\">"
"<filter id=\"f\">" +
StringView(piece) +
"</filter>"
"</svg>"
"#f";
return url;
}
And here’s how we’re using it to create all the filters we need:
AtomicString CreateVisionDeficiencyFilterUrl(VisionDeficiency vision_deficiency) {
switch (vision_deficiency) {
case VisionDeficiency::kAchromatopsia:
return CreateFilterDataUrl("…");
case VisionDeficiency::kBlurredVision:
return CreateFilterDataUrl("<feGaussianBlur stdDeviation=\"2\"/>");
case VisionDeficiency::kDeuteranopia:
return CreateFilterDataUrl(
" "
"\"/>");
case VisionDeficiency::kProtanopia:
return CreateFilterDataUrl("…");
case VisionDeficiency::kTritanopia:
return CreateFilterDataUrl("…");
case VisionDeficiency::kNoVisionDeficiency:
NOTREACHED();
return "";
}
}
Note that this technique gives us access to the full power of SVG filters without having to re-implement anything or re-invent any wheels. We’re implementing a Blink Renderer feature, but we’re doing so by leveraging the Web Platform.
Okay, so we’ve figured out how to construct SVG filters and turn them into data URLs that we can use within our CSS
filter property value. Can you think of a problem with this technique? It turns out, we can’t actually rely on the data URL being loaded in all cases, since the target page might have a
Content-Security-Policy that blocks data URLs. Our final Blink-level implementation takes special care to bypass CSP for these “internal” data URLs during loading.
Edge cases aside, we’ve made some good progress. Because we no longer depend on inline
<svg> being present in the same document, we’ve effectively reduced our solution to just a single self-contained CSS
filter property definition. Great! Now let’s get rid of that too.
Avoiding the in-document CSS dependency #
Just to recap, this is where we’re at so far:
<style>
:root {
filter: url('data:…');
}
</style>
We still depend on this CSS
filter property, which might override a
filter in the real document and break things. It would also show up when inspecting the computed styles in DevTools, which would be confusing. How can we avoid these issues? We need to find a way to add a filter to the document without it being programmatically observable to developers.
One idea that came up was to create a new Chrome-internal CSS property that behaves like
filter, but has a different name, like
--internal-devtools-filter. We could then add special logic to ensure this property never shows up in DevTools or in the computed styles in the DOM. We could even make sure it only works on the one element we need it for: the root element. However, this solution wouldn’t be ideal: we’d be duplicating functionality that already exists with
filter, and even if we try hard to hide this non-standard property, web developers could still find out about it and start using it, which would be bad for the Web Platform. We need some other way of applying a CSS style without it being observable in the DOM. Any ideas?
The CSS spec has a section introducing the visual formatting model it uses, and one of the key concepts there is the viewport. This is the visual view through which users consult the web page. A closely related concept is the initial containing block, which is kind of like a styleable viewport
<div> that only exists at the spec level. The spec refers to this “viewport” concept all over the place. For example, you know how the browser shows scrollbars when the content doesn’t fit? This is all defined in the CSS spec, based on this “viewport”.
This
viewport exists within the Blink Renderer as well, as an implementation detail. Here’s the code that applies the default viewport styles according to the spec:
scoped_refptr<ComputedStyle> StyleResolver::StyleForViewport() {
scoped_refptr<ComputedStyle> viewport_style =
InitialStyleForElement(GetDocument());
viewport_style->SetZIndex(0);
viewport_style->SetIsStackingContextWithoutContainment(true);
viewport_style->SetDisplay(EDisplay::kBlock);
viewport_style->SetPosition(EPosition::kAbsolute);
viewport_style->SetOverflowX(EOverflow::kAuto);
viewport_style->SetOverflowY(EOverflow::kAuto);
// …
return viewport_style;
}
You don’t need to understand C++ or the intricacies of Blink’s Style engine to see that this code handles the viewport’s (or more accurately: the initial containing block’s)
z-index,
display,
position, and
overflow. Those are all concepts you might be familiar with from CSS! There’s some other magic related to stacking contexts, which doesn’t directly translate to a CSS property, but overall you could think of this
viewport object as something that can be styled using CSS from within Blink, just like a DOM element—except it’s not part of the DOM.
This gives us exactly what we want! We can apply our
filter styles to the
viewport object, which visually affects the rendering, without interfering with the observable page styles or the DOM in any way.
Conclusion #
To recap our little journey here, we started out by building a prototype using web technology instead of C++, and then started working on moving parts of it to the Blink Renderer.
- We first made our prototype more self-contained by inlining data URLs.
- We then made those internal data URLs CSP-friendly, by special-casing their loading.
- We made our implementation DOM-agnostic and programmatically unobservable by moving styles to the Blink-internal
viewport.
What’s unique about this implementation is that our HTML/CSS/SVG prototype ended up influencing the final technical design. We found a way to use the Web Platform, even within the Blink Renderer!
For more background, check out our design proposal or the Chromium tracking bug which references all related patches.
Last updated: • Improve article
|
https://developer.chrome.com/blog/cvd/
|
CC-MAIN-2021-21
|
refinedweb
| 2,362
| 50.87
|
iPass.com
Table of contents
Created
17 October 2011
Prerequisite knowledge
Extensive knowledge of Flex 3 or Flex 4.5. But if you intend to incorporate aspects of the Flex Dashboard application into your own projects, then having a good understanding of Flex 3, and at least a basic understanding of what’s new in Flex 4.5, is essential.
User level
Beginning
Required products
Flash Builder 4.7 Premium (Download trial):
- Differences in namespaces between Flex 3 and Flex 4.5
- Significant differences in the Flex 4.5 Spark layout scheme
- Significant differences in the Flex 4.5 Spark skinning model
- Creating and editing custom component skins, including states in skins
- Moving CSS styles into custom skins
- Adapting Flex 3 applications to use Flex 4.5 containers and controls:
- Visit the Dashboard source page.
- Click the Download Source link in the lower-left corner of the page. You do not need to download the Flex 3 SDK..
Figure 1. Importing from a project archive file.
Follow these steps to import from the ZIP file:
- Choose File > Import in Flash Builder 4.5.
- Select Flash Builder > Flash Builder Project for the import source, then click Next.
- In the Import Flash Builder Project dialog box, select File and click the Browse button.
- Navigate to the folder containing the Dashboard.zip file.
- Select the file and click Open.
- Back in the Import Flex Project dialog box, click Finish.
- If you import from the ZIP project archive file and you see a message that says the project will be upgraded (see Figure 2), just click OK.
Figure 2. The project upgrade warning..
- If you installed a more recent version of the Flex SDK for this tutorial, you'll need to click the Configure Flex SDKs link to add it as an option.
- If your default SDK is not Flex 4.5, select Use A Specific SDK and select the Flex 4.5 SDK.
- Ensure the Use Flex 3 Compatibility Mode option is not selected, because you will be migrating the Dashboard application to Flex 4.5.
- Click OK.
Figure 3. Choosing the Flex 4.5 SDK.
- After the import process completes, expand the Dashboard project and its src folder in the Package Explorer view (see Figure 4) to see the imported folders and files.
Figure 4. The project source file tree after importing.).
Figure 5. The error in the Problems view indicates the libs folder is missing.
The libs folder is created automatically by Flash Builder for new projects, but for imported projects that do not contain a libs folder, the folder must be created manually:
- Right-click the project's top-level folder Dashboard in the Package Explorer view and select New > Folder.
- Type libs as the folder name.
- Click Finish.
The folder can remain empty (see Figure 6) but it must exist to remove the error.
Figure 6. The new folder in the Package Explorer view..
Figure 7. One new error and several warnings appear in the Problems view.
To fix the error:
- Double-click the error to open main.mxml and position the cursor at the line causing the error.
- Remove the
backgroundSizestyle property from the
<mx:Application>tag.
- Rebuild the project.
You will now see two new errors (see Figure 8), which you will fix before you address the warnings.
Figure 8. Two new errors in the Problems view.:
- Double-click the first error to open RollOverBoxItemRenderer.as and position the cursor at the line causing the error:
-:
- Replace the line
f.begin(g,rc);with
f.begin(g,rc, new Point(rc.left,rc.top));to resolve the error.
- Save your changes and rebuild the project. You will now see one new error (see Figure 9).
Figure 9. The themeColor error in the Problems view.
The
themeColorstyle was removed in the Spark skins, so you'll need to remove it as you migrate to Spark and Flex 4.5.
- Double-click the error to open src/com/esria/samples/dashboard/view/ListContent.mxml and position the cursor at the line causing the error.
- Remove the
themeColorstyle property from the
<mx:List>tag.
- Save your changes and rebuild the project. You now see an error related to the project HTML wrapper (see Figure 10).
Figure 10. The HTML wrapper error in the Problems view.:
- Right-click the error message and select Recreate HTML Templates.
- Rebuild the project.
- Verify that no errors are reported in the Problems view.
To eliminate most of the warnings, follow these steps:
- Open the main application file, main.mxml.
- Remove the
<mx:Style>tag (near line 14):
<mx:Style
- Save your changes and rebuild the project.).
-, replace the following line at the top of PodLayoutManager.as near the other import statements:
- replace this:).
Figure 11. The Dashboard application built with the Flex 4.5 SDK..
|
https://www.adobe.com/devnet/flex/articles/migrating-flex-apps-part1.html
|
CC-MAIN-2019-09
|
refinedweb
| 800
| 67.55
|
Hi there, i would like to find out what the hell is wrong here
/// <summary> /// Get a single integer value /// </summary> /// <param name="sql">The sql query used to retreive a result set</param> /// <returns>The value of the first column in the first row of the result set as an integer</returns> public virtual int GetSimpleInteger( string sql ) { SqlCommand comm = new SqlCommand( sql, GetConnectionObject() ); try { // Reset the error object ClearError(); return (Int32)comm.ExecuteScalar(); <------- Error here } catch( SqlException ex ) { SetError( ex ); return -1; } }
now the funny thing is this worked perfectly until today, i just switched my PC on and built the project straight, now also i cannot connect to SQL either...
I get this error
ExecuteScalar requires an open and available Connection. The connection's current state is closed. PLEASEEEEEEEEEEEEE HELP, this is very urgent, im on deadline
Thanks
|
https://www.daniweb.com/programming/web-development/threads/173178/executescalar-requires-an-open-and-available-connection
|
CC-MAIN-2018-43
|
refinedweb
| 141
| 52.94
|
I am trying to teach myself java and I have a book but it doesnt have how to parse an int into a string. So are there any ways of either doing this or getting round it so I can display my answer? I put in bold the place where the difficulty is. Once I have got this done I can put it on JPanels etc. I am trying to have a goal achieve it and then have another goal with the same programme. Also if you have any tips of teaching yourself java I would be interested to know.
import javax.swing.*; class percentbible { public static void Main (String[]args) { String a; //enter in number for a string a=JOptionPane.showInputDialog(null,"enter chapters of bible read","",JOptionPane.INFORMATION_MESSAGE); //turn string into number int num = Integer.parseInt(a); int chapno = 1189; int calc= num/chapno*100; String show; //convert integer into string [B] show = String.parseString(calc);[/B] //display calculation show= JOptionPane.showMessageDialog(null,"percentage of chapters read","",JOptionPane.INFORMATION_MESSAGE); } }
|
https://www.daniweb.com/programming/software-development/threads/90933/an-individual-project
|
CC-MAIN-2018-30
|
refinedweb
| 171
| 58.69
|
On Thu, Jun 10, 2010 at 3:52 AM, Arnaud Bailly <arnaud.oqube at gmail.com>wrote: > Hello, > I studied (a bit) Pi-calculus and other mobile agents calculus during > my PhD, and I have always been fascinated by the beauty of this idea. > Your implementation is strikingly simple and beautiful. > > I have a question though: Why is the fixpoint type > > > newtype Nu f = Nu { nu :: f (Nu f) } > > needed? And BTW, why generally use fixpoint on types? I read some > papers using/presenting such constructions (most notable a paper by > R.Lammel, I think, on expression trees transformation) but never quite > get it. > You need the Nu type because you need channels that can only send channels of channels of channels of channels of ... You could equivalently use the formulation newtype NuChan = NuChan (Chan NuChan) but then I couldn't recycle the wrapper for other types if I wanted. Without it the code below it would be untype because of the "occurs check". If you look in category-extras under Control.Morphism.* you'll find a lot of other uses of the types Mu/Nu though there the type is called FixF. -Edward Kmett > On Wed, Jun 9, 2010 at 6:20 PM, Edward Kmett <ekmett at gmail.com> wrote: > > Keegan McAllister gave a very nice talk at Boston Haskell last night > about > > "First Class Concurrency". His slides are available online at > > > > > > > > His final few slides covered the Pi calculus: > > > > > > > > I took a few minutes over lunch to dash out a finally tagless version of > the > > pi calculus interpreter presented by Keegan, since the topic of how much > > nicer it would look in HOAS came up during the meeting. > > > > For more information on finally tagless encodings, see: > > > > > > > > Of course, Keegan went farther and defined an encoding of the lambda > > calculus into the pi calculus, but I leave that as an exercise for the > > reader. ;) > > > > -Edward Kmett > > > >> {-# LANGUAGE Rank2Types, TypeFamilies, FlexibleInstances #-} > >> module Pi where > > > >> import Control.Applicative > >> import Control.Concurrent > > > > A finally tagless encoding of the Pi calculus. Symantics is a portmanteau > of > > Syntax and Semantics. > > > >> class Symantics p where > >> type Name p :: * > >> new :: (Name p -> p) -> p > >> out :: Name p -> Name p -> p -> p > >> (|||) :: p -> p -> p > >> inn :: Name p -> (Name p -> p) -> p > >> rep :: p -> p > >> nil :: p > >> embed :: IO () -> p > > > > Type level fixed points > > > >> newtype Nu f = Nu { nu :: f (Nu f) } > > > >> fork :: IO () -> IO () > >> fork a = forkIO a >> return () > > > >> forever :: IO a -> IO a > >> forever p = p >> forever p > > > > Executable semantics > > > >> instance Symantics (IO ()) where > >> type Name (IO ()) = Nu Chan > >> new f = Nu <$> newChan >>= f > >> a ||| b = forkIO a >> fork b > >> inn (Nu x) f = readChan x >>= fork . f > >> out (Nu x) y b = writeChan x y >> b > >> rep = forever > >> nil = return () > >> embed = id > > > > A closed pi calculus term > > > >> newtype Pi = Pi { runPi :: forall a. Symantics a => a } > > > >> run :: Pi -> IO () > >> run (Pi a) = a > > > >> example = Pi (new $ \z -> (new $ \x -> out x z nil > >> ||| (inn x $ \y -> out y x $ inn x $ > \ > >> y -> nil)) > >> ||| inn z (\v -> out v v nil)) > > > > A pretty printer for the pi calculus > > > >> newtype Pretty = Pretty { runPretty :: [String] -> Int -> ShowS } > >> > >> instance Symantics Pretty where > >> type Name Pretty = String > >> new f = Pretty $ \(v:vs) n -> > >> showParen (n > 10) $ > >> showString "nu " . showString v . showString ". " . > >> runPretty (f v) vs 10 > >> out x y b = Pretty $ \vs n -> > >> showParen (n > 10) $ > >> showString x . showChar '<' . showString y . showString ">. > " > >> . > >> runPretty b vs 10 > >> inn x f = Pretty $ \(v:vs) n -> > >> showParen (n > 10) $ > >> showString x . showChar '(' . showString v . showString "). > " > >> . > >> runPretty (f v) vs 10 > >> p ||| q = Pretty $ \vs n -> > >> showParen (n > 4) $ > >> runPretty p vs 5 . > >> showString " | " . > >> runPretty q vs 4 > >> rep p = Pretty $ \vs n -> > >> showParen (n > 10) $ > >> showString "!" . > >> runPretty p vs 10 > >> nil = Pretty $ \_ _ -> showChar '0' > >> embed io = Pretty $ \_ _ -> showString "{IO}" > > > >> instance Show Pi where > >> showsPrec n (Pi p) = runPretty p vars n > >> where > >> vars = fmap return vs ++ > >> [i : show j | j <- [1..], i <- vs] where > >> vs = ['a'..'z'] > > > > Pi> example > > nu a. (nu b. (b<a>. 0 | b(c). c<b>. b(d). 0) | a(b). b<b>. 0) > > > > _______________________________________________ > > Haskell-Cafe mailing list > > Haskell-Cafe at haskell.org > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL:
|
http://www.haskell.org/pipermail/haskell-cafe/2010-June/078780.html
|
CC-MAIN-2014-41
|
refinedweb
| 698
| 67.79
|
In this article, we’ll look at how we can remove duplicate elements from List in Python. There are multiple ways of approaching this problem, and we will show you some of them.
Methods to Remove Duplicate Elements from List – Python
1. Using iteration
To remove duplicate elements from List in Python, we can manually iterate through the list and add an element to the new list if it is not present. Otherwise, we skip that element.
The code is shown below:
a = [2, 3, 3, 2, 5, 4, 4, 6] b = [] for i in a: # Add to the new list # only if not present if i not in b: b.append(i) print(b)
Output
[2, 3, 5, 4, 6]
The same code can be written using List Comprehension to reduce the number of lines of code, although it is essentially the same as before.
a = [2 3, 4, 2, 5, 4, 4, 6] b = [] [b.append(i) for i in a if i not in b] print(b)
The problem with this approach is that it is a bit slow since a comparison is done for every element in the new list, while already iterating through our original list.
This is computationally expensive, and we have other methods to deal with this issue. You should use this only if the list size is not very large. Otherwise, refer to the other methods.
2. Using set()
A simple and fast approach to remove duplicate elements from list in Python would be to use Python’s built-in
set() method to convert the list elements into a unique set, following which we can convert it into a List now removed of all its duplicate elements.
first_list = [1, 2, 2, 3, 3, 3, 4, 5, 5, 6] # Convert to a set first set_list = set(first_list) # Now convert the set into a List print(list(set_list)) second_list = [2, 3, 3, 2, 5, 4, 4, 6] # Does the same as above, in a single line print(list(set(second_list)))
Output
[1, 2, 3, 4, 5, 6] [2, 3, 4, 5, 6]
The problem with this approach is that the original List order is not maintained as with the case of the second List since we create the new List from an unordered Set. so if you wish to still preserve the relative ordering, you must avoid this method.
3. Preserving Order: Use OrderedDict
If you want to preserve the order while you remove duplicate elements from List in Python, you can use the OrderedDict class from the collections module.
More specifically, we can use
OrderedDict.fromkeys(list) to obtain a dictionary having duplicate elements removed, while still maintaining order. We can then easily convert it into a list using the
list() method.
from collections import OrderedDict a = [2, 3, 3, 2, 5, 4, 4, 6] b = list(OrderedDict.fromkeys(a)) print(b)
Output
[2, 3, 5, 4, 6]
NOTE: If you have Python 3.7 or later, we can use the built in
dict.fromkeys(list) instead. This will also guarantee the order.
As you can observe, the order is indeed maintained, so we get the same output as of the first method. But this is much faster! This is the recommended solution to this problem. But for illustration, we will show you a couple of more approaches to remove duplicate elements from List in Python.
4. Using list.count()
The
list.count() method returns the number of occurrences of the value. We can use it along with the
remove() method to eliminate any duplicate elements. But again, this does not preserve the order
Note that this method modifies the input list in place, so the changes are reflected there itself.
a = [0, 1, 2, 3, 4, 1, 2, 3, 5] for i in a: if a.count(i) > 1: a.remove(i) print(a)
Output
[0, 4, 1, 2, 3, 5]
5. Using sort()
We can use the
sort() method to sort the set that we obtained in approach 2. This will also remove any duplicates, while preserving the order, but is slower than the
dict.fromkeys() approach.
a = [0, 1, 2, 3, 4, 1, 2, 3, 5] b = list(set(a)) b.sort(key=a.index) print(b)
Output
[0, 1, 2, 3, 4, 5]
6. Using pandas module
In case we are working with the Pandas module, we can use the
pandas.drop_duplicates() method to remove the duplicates and then convert it into a List, while also preserving the order.
import pandas as pd a = [0, 1, 2, 3, 4, 1, 2, 3, 5] pd.Series(a).drop_duplicates().tolist()
Output
[0, 1, 2, 3, 4, 5]
References
- JournalDev article on Removing Duplicate List Elements
- StackOverflow Question
|
https://www.askpython.com/python/remove-duplicate-elements-from-list-python
|
CC-MAIN-2020-10
|
refinedweb
| 786
| 70.43
|
I have to write a code that accepts 5 grades and sorts them from smallest to greatest using linked list.This is what I have so far using examples from the book.
#include <iostream> using namespace std; struct List { int value; List *next; }; int main() { int num, num1,num2,num3,num4; List *head; cout <<"Please enter 5 grades" <<endl; cin >>num; cin >>num1; cin >>num2; cin >>num3; cin >>num4; head = new List; head->value = num1; second->next = NULL; head->next = second; List *second = new List; second->value = num1; second ->next = NULL; head->next = second; List *third = new List; third->value = num2; third->next = NULL; head->next->next = third; List *fourth = new List; fourth->value = num3; fourth->next = NULL; head->next->next->next = fourth; List *fifth = new List; fifth->value = num4; fifth->next = NULL: head->next->next->next->next = fifth; //Print the list cout << "First grade is: "<< cout << "Second grade is: "<< cout << "Third grade is: "<< cout << "Fourth grade is: "<< cout << "Fifth grade is: "<<
|
https://www.daniweb.com/programming/software-development/threads/374262/c-linked-list-pls-help
|
CC-MAIN-2018-30
|
refinedweb
| 162
| 50.17
|
Forum:I've made a new logo for the Game namespace.
From Uncyclopedia, the content-free encyclopedia
Forums: Index > Village Dump > I've made a new logo for the Game namespace.
Note: This topic has been unedited for 575 days. It is considered archived - the discussion is over. Do not add to unless it really needs a response.
I was bored...
There. ?|COMRADE_PONGO_V2|RUN_CMD|RUN_GSLYR 17:45, 18 June 2007 (UTC)
Call me old-fashioned, but I like the control pad. This one is made of black, and black makes me cry. --Whhhy?Whut?How? *Back from the dead* 01:05, 19 June 2007 (UTC)
- I don't see how this is much of anything. All it is is the current Uncyclopedia logo with the word "Game" next to it. It almost looks as if kakun did it. Sorry, that was mean. It's not that bad.-Sir Ljlego, GUN VFH FIYC WotM SG WHotM PWotM AotM EGAEDM ANotM + (Talk) 01:37, 19 June 2007 (UTC)
- Dude, you mentioned KAKUN. You're mean! --Lt. High Gen. Grue The Few The Proud, The Marines 01:38, 19 June 2007 (UTC)
- While the current "control pad" logo is nice, and even though I enjoy the original logo a bit more (probably because I made it), this one isn't even close to the other ones. Sorry Pongo, I know where you were going with it, but the execution is acctaully very crappy. -- Brigadier General Sir Zombiebaron 02:19, 19 June 2007 (UTC)
- Yeah, that one got the most votes, but... SOMEONE didn't like it very much.:27, 19 June 2007 (UTC)
|
http://uncyclopedia.wikia.com/wiki/Forum:I've_made_a_new_logo_for_the_Game_namespace.?t=20130522170736
|
CC-MAIN-2014-52
|
refinedweb
| 270
| 83.56
|
Fraud detection is a topic applicable to many sectors (financial, insurance, etc). The method explained in this post is applied in the market research field by Gather Precision (a great market research tool developed by Gather Estudios, BTW), as an early signal to detect frauds in opinion polls.
Imagine you have four field workers (Peter, John, Mary, Ann) taking surveys on the street. They spend different times gathering the data, and we want to discover if there are significant differences on the average levels. That would mean that at least one of them is taking too few or too much time completing the surveys.
Field worker = { Times in seconds for each survey he completes } Peter = { 150, 200, 180, 230, 220, 250, 230, 300 } John = { 200, 240, 220, 250, 210, 190, 240 } Mary = { 100, 130, 150, 180, 140, 200, 110, 120 } Ann = { 200, 230, 150, 220, 210 }
This is one case where ANOVA comes to the rescue. According to wikipedia, in its simplest form, “ANOVA provides a statistical test of whether or not the means of several groups are all equal”, and that is exactly what we are looking for.
We can use Apache Commons Math to perform some statistical tests. It is an interesting Java library, not really focused on statistics, but pretty easy to use and that luckily contains ANOVA.
import java.util.ArrayList; import java.util.List; import org.apache.commons.math.*; public class FraudDetector { private static final double SIGNIFICANCE_LEVEL = 0.001; // 99.9% public static void main(String[] args) throws MathException { double[][] observations = { { 150.0, 200.0, 180.0, 230.0, 220.0, 250.0, 230.0, 300.0 }, { 200.0, 240.0, 220.0, 250.0, 210.0, 190.0, 240.0 }, { 100.0, 130.0, 150.0, 180.0, 140.0, 200.0, 110.0, 120.0 }, { 200.0, 230.0, 150.0, 220.0, 210.0 } }; final List<double[]> classes = new ArrayList<double[]>(); for (int i=0; i<observations.length; i++) { classes.add(observations[i]); } OneWayAnova anova = new OneWayAnovaImpl(); boolean rejectNullHypothesis = anova.anovaTest(classes, SIGNIFICANCE_LEVEL); if (rejectNullHypothesis) { System.out.println("Significant differences were found"); } } }
The question I asked in stackoverflow includes some discussion and additional information about how to determine the rare cases.
One final thought. Despite I am not an expert in this field, I definitely think we should study more about statistics at the University.
|
https://guidogarcia.net/blog/2012/08/26/analysis-of-variance-anova-applied-to-fraud-detection/
|
CC-MAIN-2019-18
|
refinedweb
| 393
| 54.12
|
IRC log of tagmem on 2003-01-06
Timestamps are in UTC.
19:48:35 [RRSAgent]
RRSAgent has joined #tagmem
19:48:54 [Chris]
Zakim, pointer?
19:48:55 [Zakim]
I don't understand your question, Chris.
19:49:03 [Chris]
rrsagent, pointer?
19:49:03 [RRSAgent]
See
19:49:41 [Chris]
mutter mutter
19:49:58 [DanC]
DanC has changed the topic to:
19:54:35 [DanC]
crud; I haven't reviewed the 2nd draft on comparing URIs.
19:54:45 [Stuart]
Stuart has joined #tagmem
19:55:24 [Ian]
Ian has joined #tagmem
19:58:47 [Norm]
zakim, what's the passcode?
19:58:48 [Zakim]
sorry, Norm, I don't know what conference this is
19:58:58 [Norm]
zakim, this is tag
19:58:59 [Zakim]
ok, Norm
19:59:03 [Zakim]
+??P3
19:59:04 [Norm]
zakim, who's here?
19:59:05 [Zakim]
On the phone I see Chris, Norm_Walsh, ??P3
19:59:05 [Zakim]
On IRC I see Ian, Stuart, RRSAgent, Zakim, DanC, Chris, Norm
19:59:12 [Norm]
zakim, norm_walsh is Norm
19:59:14 [Zakim]
+Norm; got it
19:59:22 [Stuart]
zakim, ??P3 is me
19:59:23 [Zakim]
+Stuart; got it
19:59:51 [Zakim]
+DOrchard
20:00:00 [Zakim]
+??P5
20:00:25 [timMIT]
timMIT has joined #tagmem
20:00:50 [Stuart]
zakim, ??P5 is Roy
20:00:51 [Roy]
Roy has joined #tagmem
20:00:51 [Zakim]
+Roy; got it
20:00:57 [Zakim]
+TimBL
20:01:14 [timMIT]
Happy new Year everyone
20:01:30 [Norm]
Likewise to all
20:02:20 [Ian]
zakim, what's the code?
20:02:21 [Zakim]
the conference code is 0824, Ian
20:02:26 [Zakim]
+Ian
20:02:32 [Ian]
RRSAgent, start
20:02:48 [Zakim]
+??P8
20:03:06 [timMIT]
Zakim, ??P8 is Paul
20:03:07 [Zakim]
+Paul; got it
20:03:07 [Norm]
zakim, ??P8 is PaulC
20:03:09 [Zakim]
sorry, Norm, I do not recognize a party named '??P8'
20:03:17 [Norm]
Beat me to it :-)
20:03:26 [Chris]
Bonne Année à tous
20:03:45 [DanC]
pointer to 16Dec minutes is goofy; goes to a record of 9Dec
20:04:06 [Chris]
20:04:10 [Zakim]
+DanC
20:04:12 [Stuart]
DAn, mea culpa
20:04:38 [PaulC]
PaulC has joined #tagmem
20:05:18 [Norm]
zakim, Paul is PaulC
20:05:19 [Zakim]
+PaulC; got it
20:05:29 [Chris]
???? ?????? SVG 1.0 ? W3C Recommendation?????????
20:06:24 [timMIT]
RRSAgent, pointer?
20:06:25 [RRSAgent]
See
20:06:41 [Ian]
zakim, who's here?
20:06:42 [Zakim]
On the phone I see Chris, Norm, Stuart, DOrchard, Roy, TimBL, Ian, PaulC, DanC
20:06:43 [Zakim]
On IRC I see PaulC, Roy, timMIT, Ian, Stuart, RRSAgent, Zakim, DanC, Chris, Norm
20:06:57 [Ian]
Roll call: All but TB.
20:07:06 [Ian]
Acceped 16 Dec minutes:
20:07:14 [DanC]
$Date: 2002/12/16 22:26:35 $ ok by me
20:07:51 [Zakim]
+Tim_Bray
20:09:19 [Ian]
Next meeting: 13 Jan.
20:09:23 [Ian]
(No regrets)
20:09:30 [Ian]
--------
20:10:01 [PaulC]
I think I would like to get re-elected.
20:11:47 [TBray]
TBray has joined #tagmem
20:11:48 [PaulC]
q+
20:12:17 [PaulC]
Paul's question: Do we have a formal status for "back burner issues"?
20:12:19 [Ian]
On mixedNamespaceMeaning-13: some vague discussion about putting on the back burner.
20:12:22 [TBray]
q+
20:12:30 [Ian]
To Paul: Yes - "deferred"
20:12:35 [PaulC]
q-
20:12:44 [TBray]
to say "I promise to rev Deeplinking-25 by end of January"
20:12:51 [Ian]
DC: I am still concerned about getting something done about some of these issues (deployment).
20:13:21 [PaulC]
I think the TAG needs to think about how to evangelize its "architectural principles".
20:13:32 [Ian]
CL: Rec label will make a bigger splash.
20:14:06 [Stuart]
ack DanC
20:14:08 [Zakim]
DanC, you wanted to talk about deployment/impact
20:14:11 [PaulC]
Evangelize: speaking in public, writing articles for the W3C web site, writing articles for publication in trade press, etc.
20:14:38 [Ian]
ack TBray
20:14:47 [Ian]
TB: I promise to do deepLinking-25 by the end of the month!
20:15:07 [Ian]
TB: I think we really ought to say that we are going to take the Arch Doc to last call, say, by 1 July.
20:15:17 [Ian]
CL: That sounds reasonable to me.
20:15:33 [PaulC]
+1 on July 1 delivery for a first Last Call version of the Architecture document.
20:15:49 [Ian]
TBL: I find there's a fundamental problem with the doc without httpRange-14 resolved.
20:16:09 [Ian]
TBL: It's based on sand since I can't write axioms since terms not well-defined.
20:16:28 [Stuart]
q?
20:16:36 [Ian]
TBL: Sandro Hawke has started working on text and came to the conclusion that the doc is difficult to work with with the doc in its current form.
20:16:39 [TBray]
q+
20:18:01 [Ian]
PC: We need to evangelize the parts we already agree to (e.g., interviews, speaking opportunities).
20:18:20 [Stuart]
q?
20:18:25 [Ian]
CL: I agree that we shouldn't hold up low-hanging fruit for thornier issues.
20:19:00 [Ian]
DC: I would be interested to find out more about the food chain of information going to webmasters, and get in the loop.
20:19:23 [Ian]
TB: I want to register my disagreement with TBL on the state of the arch doc; I think it is useful.
20:19:44 [Ian]
TB: I am willing to invest some more effort in httpRange-14, but we are chartered to produce a Rec.
20:20:23 [Ian]
RF: I find the document hard to work with as well. It's a compromise between two positions that doesn't satisfy either.
20:20:36 [Ian]
RF: I think finding the way to describe the terminology in a precise way is the way forward.
20:20:56 [Ian]
RF: We need to define the terminology associated with resources in a precise and consistent manner.
20:21:16 [Ian]
RF: I think httpRange-14 is a red herring.
20:21:25 [Stuart]
ack TBray
20:22:20 [Ian]
TBL: httpRange-14 is about whether network-available resources are a distinct class. There is confusion between "things in general" and "Things with information content", which makes it difficult.
20:22:42 [Ian]
RF: I think it's necessary for us to agree to a set of terms, otherwise the doc's kind of pointless.
20:22:57 [Ian]
CL: I disagree. Some portions are independent.
20:23:11 [Ian]
RF: But we need to be able to say what is the target of a GET.
20:23:17 [Ian]
CL: Why can't the HTTP spec say that?
20:24:44 [Ian]
[Agreement that glossary with well-defined terms is important.]
20:24:47 [PaulC]
q+
20:25:33 [Roy]
q+
20:25:44 [PaulC]
What are the top 5 terms in the Architecture document that TimBL and Roy think need tighter definitions?
20:25:55 [Ian]
q?
20:25:59 [Ian]
q+
20:26:06 [Ian]
q-
20:26:10 [TBray]
TBray has joined #tagmem
20:27:36 [Ian]
IJ: I think ongoing input from all participants will be key to getting to last call mid-year.
20:28:12 [Stuart]
ack PaulC
20:28:15 [TBray]
q?
20:28:34 [Stuart]
ack Roy
20:28:42 [Ian]
RF: I think discussion of last call should wait until Feb meeting.
20:29:02 [Ian]
RF: I think we need to write down different perspectives on what the terminology should be.
20:29:18 [Ian]
RF: I think that TimBL and my positions will likely converge once written down.
20:29:33 [Ian]
RF: Until then, it's in our court to suggest changes; TAG should not stop work while we do this.
20:30:34 [TBray]
AFK & phone for 3 minutes, sorry
20:30:36 [Ian]
RF: Terms come from 5-6 sources; we should not invent new terms.
20:30:53 [Ian]
RF: There's also descriptive text needed to explain what we're talking about.
20:31:09 [timMIT]
Top 5: Resource, Information Resource (aka Document), URI, ...
20:31:34 [timMIT]
q+ to point out that definitions from various specs are inconsistent
20:32:32 [timMIT]
q-
20:32:50 [Ian]
RF: Nobody has sent me any text for RFC on URIs.
20:32:52 [TBray]
back
20:33:18 [Ian]
-----------------------------------
20:33:21 [Ian]
Agenda items for ftf meeting.
20:33:25 [Ian]
- Arch Doc
20:34:29 [Ian]
DC: What specifically?
20:35:26 [Norm]
Norm has joined #tagmem
20:35:37 [Norm]
Norm has joined #tagmem
20:35:39 [Ian]
SW: httpRange-14 on back-burner or more attention?
20:35:49 [Ian]
TB: We have new input from Sandro Hawke.
20:36:45 [Ian]
TB: Sandro has also proposed some good language.
20:37:10 [DanC]
where did that edit go?
20:37:13 [DanC]
when did timbl do that?
20:37:45 [TBray]
there's a real issue here: whether the architecture recognizes two classes of URIs
20:37:47 [Ian]
TBL: I had produced a draft with language I thought was consistent. That text has been dropped.
20:38:15 [Chris]
q+
20:38:25 [TBray]
q+
20:38:26 [Ian]
TBL: Text that distinguishes documents (network available info) from other objects.
20:38:40 [Ian]
TBL: Those who work with Sem Web technology see this as a problem.
20:38:53 [TBray]
empirically there *are* two classes in practical usage
20:39:07 [Ian]
TBL: It's a problem when you try to build systems that model real-world objects.
20:39:09 [TBray]
but I see no gain & some loss in trying to write the difference into the architecture
20:39:29 [Ian]
TBL: RF has said that this is RDF's problem; I feel uncomfortable taking the group there again.
20:39:50 [Roy]
q+
20:39:57 [Ian]
TBL: Sandro has a different solution: Identifiers always refer to documents. You must distinguish the case when you are referring to an abstract thing behind a document.
20:40:06 [Ian]
TBL: This is the only other consistent model I've seen.
20:40:25 [Ian]
CL: I heard TBL say we have lots of experience with URIs for documents/data.
20:40:38 [Ian]
CL: I agree, and I also agree that the sem web wants to point to things not on the Web.
20:41:06 [Ian]
CL: I agree with Sandro that the way to do that is to define a new way for doing so. One solution is a new URI scheme (e.g., "now" - not on the Web)
20:41:25 [Ian]
CL: This would indicate that the URI is not dereferenceable.
20:41:51 [Ian]
CL: I think we need a new mechanism to do new things, and leave the old one for old things, for which it works fine.
20:42:23 [DanC]
Stuart, pls phrase the question as "is there sufficient new information to believe that re-opening this issue for discussion would be worthwhile?"
20:42:25 [Chris]
And most importantly that would leave the *existing* way of pointing at network stuff alone
20:42:38 [Ian]
TB: Sandro has convinced me that I disagree with what CL said - defining a URI scheme for things not on the Web will not be helpful.
20:43:22 [Ian]
TB: It seems that the Web arch doesn't need to talk about the empirical difference between resource classes.
20:43:23 [Chris]
If you don't do that then you are saying that SW cannot use URI for things not on the web
20:43:44 [Stuart]
ack Chris
20:43:52 [Stuart]
ack TBray
20:44:09 [Ian]
TB: Something can be used for naming and orthogonally for dereferencing (e.g., namespace names). It's a good thing to be able to decide later.
20:44:22 [Ian]
TB: I still have trouble understanding what breaks with this world view.
20:45:03 [Ian]
RF: If you define a new URI scheme, I can create a proxy that GETs representations in that URI space.
20:45:22 [TBray]
the notion that something should be *defined* as non-dereferencable seems deeply broken to me
20:45:24 [Chris]
I accept Roys proxy argument
20:45:36 [timMIT]
q?
20:45:39 [Ian]
RF: Given the way you can use existing applications today, you can't make such distinctions within URI space.
20:45:43 [Roy]
-q
20:46:21 [Roy]
q?
20:46:27 [Roy]
ack Roy
20:46:32 [Ian]
DO: I think we need to be more vigorous when we start putting automated resource representations at end of URis.
20:46:44 [timMIT]
q+ to say that the issue is not things which are not on the web, its things which are not information objects on the web (you can't get them by looking them up) but which you can get information *about* by looking them up.
20:48:20 [Roy]
punt
20:48:53 [Ian]
q+
20:48:55 [DanC]
it's not "at the back of the queue"; it's no longer on the queue. We have decided we can write the arch doc without it.
20:48:59 [TBray]
There are some resources which more or less *are* their representation, e.g. cute-cat.jpg, others clearly not, e.g. XML namespace names. Does the architecture care
20:49:03 [TBray]
?
20:51:21 [TBray]
20:51:28 [Ian]
"Re: WebArch Ambiguity about Objects, PLUS Suggested Major Replacement
20:51:28 [Ian]
"
20:51:55 [DanC]
bray notes 0014 contains specific suggested text
20:51:57 [Ian]
TB: This is being taken up on www-tag (whether we want it to be or not). I recommend that TBL look at whether there's a way forward there.
20:52:45 [Ian]
----------------------------------
20:53:03 [Ian]
XInclude
20:53:21 [TBray]
suggests that this is further evidence that XInclude was a mistake
20:53:24 [Ian]
Content negotiation
20:53:24 [Ian]
20:53:46 [Ian]
Also
20:54:08 [Ian]
DC: I would like to see the WG's response first; whether commenter is satisfied.
20:54:44 [Stuart]
q?
20:54:53 [Stuart]
ack TimMIT
20:54:54 [Zakim]
TimMIT, you wanted to say that the issue is not things which are not on the web, its things which are not information objects on the web (you can't get them by looking them up) but
20:54:56 [Zakim]
... which you can get information *about* by looking them up.
20:54:59 [Stuart]
ack Ian
20:55:11 [Stuart]
ack DanC
20:55:13 [Zakim]
DanC, you wanted to ask if the WG has responded to the XInclude comment yet
20:55:27 [DanC]
Ian, please make a link to "the message [Roy]" sent from the TAG events/schedule stuff
20:55:37 [Ian]
Action IJ: Put together ftf meeting page.
20:57:56 [Ian]
TB: I will be there all day Friday, mid-afternoon Thursday.
20:58:06 [Ian]
NW: Regrets.
20:58:52 [Ian]
------------------------------------------
20:59:10 [Ian]
On a next version of XML.
20:59:19 [TBray]
q+
20:59:42 [DanC]
Date: Mon, 06 Jan 2003 12:47:49 -0500
20:59:49 [TBray]
20:59:55 [Ian]
[TAG-only for now]
21:01:26 [Ian]
[DC reads portion of CL's objection.]
21:01:36 [Chris]
q+
21:01:55 [Ian]
DC: Is XML Base excluded intentionally?
21:01:57 [Ian]
NW: Yes.
21:02:28 [Ian]
CL: XML IDs are not a dying thing.
21:02:33 [Ian]
NW: They are not dying quickly.
21:02:39 [Stuart]
ack Chris
21:02:43 [Ian]
CL: I disagree with NW.
21:02:43 [DanC]
the way XPointer uses ID should die.
21:03:19 [timMIT]
q+ DanC
21:03:40 [Ian]
[Discussion of use of IDs]
21:04:32 [timMIT]
DanC< you queued yourself to say " the way XPointer uses ID should die."
21:04:40 [Ian]
CL: Easier to declare that xml:id is of type ID. If you want anything different, then use DTDs or other validation mechanisms.
21:04:44 [TBray]
in fact for virtually all languages invented at W3C and elsewhere, foo#bar points to <anything id="bar">
21:05:02 [Ian]
CL: I'm not happy having a subset that says you can't use DOM and XPointer.
21:05:23 [Ian]
CL: I want to separate validation and decoration.
21:05:25 [Stuart]
q?
21:06:03 [Ian]
CL: These two concepts were conflated in SGML; we could get this right now.
21:06:24 [DaveO]
DaveO has joined #tagmem
21:06:29 [DaveO]
q?
21:06:31 [timMIT]
CL: There are two separte operations. one is the parsing of the input to produce the infoset. Another is a validation of the document syntax. These were confused in SGML and not quite sepraated in XML. This moves toward fixing this.
21:06:33 [DaveO]
q+
21:06:35 [Ian]
TB: It's too late for xml:id. Every language out there uses "id" to be of type ID.
21:06:56 [Ian]
TB: You could adopt James Clark's solution, or you could bite the bullet and ....[scribe missed]
21:07:05 [Ian]
CL: Another way (also proposed by James) is to say that xml:id is decoration.
21:07:18 [Ian]
TBL: Is this an implicit declaration in all documents?
21:07:24 [Norm]
"...and say that #id means the element with the attribute "id""
21:07:25 [TBray]
that's xml:idAttr and you say xml:idAttr="id"
21:07:31 [DaveO]
I'd like to make a "matrix" suggestion. What are the solutions that we are talking about, and what are there pros/cons?
21:07:31 [DanC]
Bray referred to the decoration idea as "Clark's idattribute" I believe
21:07:33 [PaulC]
q+
21:07:43 [Ian]
TBL: Two ways to do this - declare in namespace, or do by decoration.
21:07:46 [Ian]
s/TBL/CL
21:08:04 [Ian]
CL: I note that content will have to be changed anyway.
21:08:15 [Ian]
TB: All this aside, I think that NW's formulation is correct.
21:08:26 [Ian]
TB: We've muddled along and it doesn't cause practical problems.
21:08:30 [Ian]
[CL: It does.]
21:08:34 [Chris]
Grrrrrrr
21:08:50 [Ian]
TB: The risk of slippery slope for just one new feature is horrendous.
21:08:56 [Chris]
It causes *immense* practicval problems
21:09:01 [Stuart]
ack TBray
21:09:15 [Chris]
GetElementByID is the single most used DOM call
21:09:16 [Norm]
I still assert that the two problems are seperable and should be solved seperately
21:09:39 [Ian]
q- DanC
21:09:45 [Ian]
ack DaveO
21:09:50 [Norm]
q+
21:10:00 [Chris]
I still assert that they are not orthogonal. They are seperable, but not totally orthogonal
21:10:09 [Ian]
DO: I am susceptible to both arguments: no new features v. getting ids correct.
21:10:12 [Chris]
the axes are, like , 70 degrees apart not 90
21:10:17 [DanC]
your point that they're not orthogonal is well made, Chris.
21:10:33 [Ian]
DO: In Web services, lots of "id" attributes being defined over and over (and named "id").
21:10:43 [Chris]
I agree its well made but TimB does not ...
21:10:44 [Ian]
DO: I'd like us to keep the door open on this particular feature creep.
21:11:06 [Norm]
I accept that they are not properly orthogonal. But they are seperable. The problem exists *now* independent of the subset.
21:11:07 [TBray]
rip the name "id" out of the users' hands I say
21:11:08 [Ian]
DO: I would love it if CL listed the various options for dealing with ids.
21:11:41 [Stuart]
ack PaulC
21:11:43 [Ian]
DO: I'd like to keep the issue open to hear the pros and cons.
21:11:47 [Ian]
PC: I agree with DO.
21:11:53 [timMIT]
q+ to note that graph-oriented systems can't use xml's id because there is no distinction between definition and use. XML makes the assumption that one occrrence of the id is special.
21:12:15 [Ian]
PC: I have to keep an open mind for other reasons than DO.
21:12:32 [TBray]
q+
21:13:09 [Ian]
PC: I have some concerns about wording in NW's proposed text about where this work should take place. I think we should make clear that the AC will be deciding this.
21:13:26 [Ian]
NW: I hear that, but think we should suggest something they should agree on.
21:15:34 [Ian]
NW: We can propose two different issues.
21:15:39 [Stuart]
ack Norm
21:15:57 [Chris]
a) subsetting XML
21:16:02 [Chris]
b) xml:id
21:16:31 [Ian]
NW: I suggest writing up another draft in TAG space.
21:16:39 [DanC]
quick straw poll on which list to use?
21:16:52 [Ian]
TB: I'd rather this take place on www-tag.
21:17:01 [DanC]
I'm agnostic; light preference for www-tag
21:17:32 [Ian]
CL, PC: One more round on TAG list would be better.
21:17:47 [Ian]
Action NW: Send another draft to tag@w3.org.
21:17:52 [Ian]
q?
21:18:50 [Ian]
TBL: In an RDF document, there's not a defining instance of an id. When something occurs in more than one place, it's considered to be the same thing.
21:18:54 [Ian]
ack TimMIT
21:18:55 [Zakim]
TimMIT, you wanted to note that graph-oriented systems can't use xml's id because there is no distinction between definition and use. XML makes the assumption that one occrrence of
21:18:57 [Zakim]
... the id is special.
21:19:01 [Ian]
ack TBary
21:19:04 [Ian]
ack TBray
21:19:28 [Ian]
TB: Why can't you have a new spec that defines a subset?
21:20:00 [Ian]
NW: You could, but if you had a combined document that only defined a subset, then I think the people still using DTDs would be cheated out of that useful body of work. And that two parallel things going forward would be confusing.
21:20:59 [Ian]
&danc;
21:21:14 [DanC]
that's a general entity, not a parameter entity
21:21:33 [Ian]
[Discussion about number of specs.]
21:21:56 [Stuart]
q?
21:21:58 [Ian]
TB: I disagree that if you do "grand unification" you would also have to do "all of 1.1".
21:22:14 [Ian]
CL: There's another way to do this - define a small version, and base 1.1 on that.
21:22:17 [Ian]
NW: That's what I had in mind.
21:22:29 [Ian]
CL: You include the subset by reference (in the 1.1 draft).
21:22:51 [Ian]
NW: The two points I want to make are (1) I think that will be a lot of work and (2) I would be uncomfortable *not* doing it.
21:22:56 [timMIT]
Sounds as though we have 3 useful tasks. 1) subsetting 2) xml:ids 3) unification of specs without changing anything else
21:23:49 [Ian]
TB: I am not comfortable with "MUST do all of 1.1."
21:24:04 [Ian]
TB: I am fine with two statements (1) big job and (2) might be problematic if only include subset.
21:24:12 [Ian]
-------------------------------------
21:24:14 [Ian]
Action item review
21:24:21 [Ian]
# Status of URIEquivalence-15, IRIEverywhere-27.
21:24:27 [Ian]
#
21:24:27 [Ian]
1. Action MD 2002/11/18: Write up text about IRIEverywhere-27 for spec writers to include in their spec.
21:24:27 [Ian]
2. Action CL 2002/11/18: Write up finding for IRIEverywhere-27 (from TB and TBL, a/b/c), to include MD's text.
21:24:43 [Ian]
CL: Whoops!
21:25:12 [Ian]
SW: Please have an update for 13 Jan.
21:25:13 [Ian]
#
21:25:13 [Ian]
1.
21:25:13 [Ian]
6.
21:25:13 [Ian]
# binaryXML-30
21:25:13 [Ian]
1. Action CL 2002/12/02: Write up problem statement about binary XML; send to www-tag.
21:26:08 [Ian]
#
21:26:08 [Ian]
2.
21:26:08 [Ian]
1. TB's "How to Compare Uniform Resource Identifiers" draft finding.
21:26:13 [Ian]
21:26:25 [Ian]
ack DanC
21:26:26 [Zakim]
DanC, you wanted to offer to review "How to Compare Uniform Resource Identifiers" draft finding
21:26:35 [PaulC]
q+
21:27:13 [Ian]
PC: There are four software groups at MS who are looking at your draft; I need some more review time.
21:27:46 [Ian]
--------
21:27:51 [Ian]
RDDL challenge
21:28:03 [Ian]
NW Action :
21:28:04 [Ian]
21:28:14 [DanC]
oops; norm sent something? darn; I thought I was watching for that
21:28:19 [Ian]
NW: They're all adequate. Just pick one. I picked Jonathan's proposal.
21:28:27 [Roy]
q+
21:28:48 [Ian]
ack Roy
21:28:50 [Stuart]
ack PaulC
21:28:52 [TBray]
q+ to say I now like Sandro's proposal
21:28:53 [Ian]
RF: WHy do we need to pick one?
21:29:04 [Ian]
PC: What's http content negotiation all about?
21:29:12 [Ian]
PC: Why aren't image formats similar?
21:29:17 [Ian]
TBL: You need dominant image formats.
21:29:23 [Roy]
(i.e.. let the market decide which one dominates)
21:29:35 [Ian]
PC: I am not sure that having a single format is the right answer.
21:29:56 [Chris]
q+
21:29:59 [TBray]
I am increasingly convinced that a single format is desirable
21:30:26 [Roy]
I am increasingly convinced that I don't know which is better.
21:30:49 [Ian]
TB: We can't say "you MUST use X" but it would be a benefit to the community to bless one format.
21:30:57 [Ian]
TB: Also, check out Sandro's suggestion....
21:31:47 [DanC]
conneg and separate URIs are not exclusive!
21:31:52 [DanC]
you can do both.
21:32:10 [timMIT]
q+
21:32:20 [timMIT]
Big general discsuusion, old one, pros and cons.
21:32:35 [Stuart]
ack TBray
21:32:36 [Zakim]
TBray, you wanted to say I now like Sandro's proposal
21:32:41 [Stuart]
ack Chris
21:32:51 [Stuart]
ack TimMIT
21:33:48 [Ian]
Adjourned
21:33:55 [Zakim]
-Norm
21:33:56 [Ian]
RRSAgent, stop
|
http://www.w3.org/2003/01/06-tagmem-irc.html
|
CC-MAIN-2015-06
|
refinedweb
| 4,563
| 80.51
|
This is my first post and I'm a newly enrolled student/novice to Java.
I have created a simple program that calculates the area of a box, and the error handling I have obviously got wrong. When I run the program, it asks the first question ("Enter the height of the box") and then handles the error ok when invalid data entered, THEN when asked the second question ("Enter the width of the box") it handles the error BUT then takes you all the way back to the first question instead of returning to the second.
Can someone please help out here as I'm sure it would be a simple fix.
I have posted the code below.
Thanks - Stew.
import java.io.*; public class TestProg { public static void main(String args []) throws IOException { String strHeight, strWidth; float height, width, total; boolean done = false; BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); while(!done) { try { System.out.print("Enter the height of the box: "); strHeight = dataIn.readLine(); height = Float.parseFloat(strHeight); System.out.println(); if(height <= 0) throw new NumberFormatException(); System.out.print("Enter the width of the box: "); strWidth = dataIn.readLine(); width = Float.parseFloat(strWidth); System.out.println(); if(width <= 0) throw new NumberFormatException(); else done = true; total = height * width; System.out.println("The area = " + total); } catch(NumberFormatException e) { System.out.println("Invalid format!"); } } } }
|
http://www.dreamincode.net/forums/topic/25967-error-handling/page__pid__214252__st__0
|
CC-MAIN-2016-22
|
refinedweb
| 226
| 57.57
|
I.
I created a fresh virtualenv on my media server and installed the following packages:
Then I placed the following script in the root of the virtualenv. The code is intentionally simplistic since
youtube-dl will be doing all the hard work:
import subprocess import sys from flask import Flask, flash, redirect, request, render_template, url_for DEBUG = False SECRET_KEY = 'this is needed for flash messages' BINARY = '/path/to/bin/youtube-dl' DEST_DIR = '/path/to/my/videos' OUTPUT_TEMPLATE = '%s/%%(title)s-%%(id)s.%%(ext)s' % DEST_DIR app = Flask(__name__) app.config.from_object(__name__) @app.route('/', methods=['GET', 'POST']) def download(): if request.method == 'POST': url = request.form['url'] p = subprocess.Popen([BINARY, '-o', OUTPUT_TEMPLATE, '-q', url]) p.communicate() flash('Successfully downloaded!', 'success') return redirect(url_for('download')) return render_template('download.html') if __name__ == '__main__': app.run(host='0.0.0.0', port=8801)
When a video URL is POSTed to the download view, it will shell out to the
youtube-dl binary and block until the download finishes. I'm specifying an output template for youtube-dl to use when saving the downloaded video, ensuring everything ends up in a directory watched by Plex.
I made a simple template using bootstrap, which looks like:
<!doctype html> <html> <head> <title>youtuber</title> <link rel=stylesheet type=text/css <script src="{{ url_for('static', filename='js/jquery-1.11.0.min.js') }}" type="text/javascript"></script> <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script> </head> <body> <div class="container"> {% for category, message in get_flashed_messages(with_categories=true) %} <div class="alert alert-{{ category }} alert-dismissable"> <button type="button" class="close" data-×</button> <p>{{ message }}</p> </div> {% endfor %} <h1>Download</h1> <form action="{{ url_for('download') }}" method="post"> <div class="form-group"> <label for="url">URL</label> <input type="text" name="url" class="form-control" id="url" placeholder="url" /> </div> <button type="submit" class="btn btn-primary">Download</button> </form> </div> </body> </html>
The final piece to the puzzle is a Chrome extension that adds a button to the toolbar which, when clicked, will send the currently open URL to the Flask app for downloading (via an ajax request).
This extension will add a toolbar-icon and run in the background waiting for click events. In addition to a simple 16x16 icon, here are the three files required for the extension.
manifest.json stores metadata about the extension, including the name of the background script and the icon used in the toolbar:
/* manifest.json */ { "background": {"scripts": ["background.js"]}, "browser_action": { "default_icon": "youtuber.png", "default_title": "youtuber" }, "name": "YouTuber", "description": "Store youtube vids on media server", "icons": {"16": "youtuber.png"}, "permissions": [ "tabs", "http://*/*", "https://*/*"], "version": "0.1", "manifest_version": 2 }
background.js binds a click handler which executes our YouTube script, making the ajax request.
/* background.js */ chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.executeScript(tab.id, {file: "youtuber.js"}); });
Finally, here is
youtuber.js, the script that POSTs the URL to the Flask app running on my media server. When the download finishes an ugly little message pops up letting me know it's done.
var youtubeURL = location.href; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { alert('Finished downloading ' + document.title); } else if (xmlhttp.readyState == 4) { alert('Something went wrong: ' + xmlhttp.status); } } xmlhttp.open('POST', '', true); xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlhttp.send('url=' + encodeURIComponent(youtubeURL));
Now any time I'm watching a YouTube video I want to save, I simply click the little toolbar icon and it shows up on my media server!
Thanks for taking the time to read this post. I hope you found it useful!
Plex is great, Flask is great, thanks for sharing this complete example.
However, for this particular use case there's already an excellent bookmarklet available from the Plex team that will queue up videos from all the big video streaming sites.
That said, I'm already thinking of a couple other projects that could use the pattern you've demonstrated in a concise bit of Flask -- nice!
will queue up videos from all the big video streaming sites.
That sounds very useful, thanks for sharing. Does that bookmarklet also download the video files themselves for you? Just to be clear, the Flask app + extension I've presented in this post will download the files themselves.
As far as I know the Plex feature will add media to the Plex Queue fmor the bookmarklet or a link in an email message. It doesn't download the content and add it to the library, but it does support a wide range of media sites/sources, shown here:
Even so, the example you made looks great... thanks again.
nice and concise article. going to get my hands dirty soon on this. these short examples enables newbies like me. hope to get more from you.
Commenting has been closed, but please feel free to contact me
|
http://charlesleifer.com/blog/a-flask-front-end-and-chrome-extension-for-youtube-dl/
|
CC-MAIN-2014-35
|
refinedweb
| 812
| 59.09
|
We, both of which are now open source, and are part of the “JavaFX Public API” shown in the diagram. For developers interested in porting JavaFX to other platforms or improving the graphics performance — well we will be open sourcing Prism and Glass in the next few months :-).
Since javafx-ui-common is such a foundational part of the JavaFX platform, I thought I should give a short tour of what is in there, including the (gasp!) non-public portions. As always, non-public API (or rather, unsupported API, meaning anything that is not in the javafx namespace such as com.sun.*) cannot be depended on from release to release. But for those of you wondering how things work, there is some very important stuff buried in the unsupported packages, and for those of you wanting to actually hack on OpenJFX, this will be of even greater interest. If you haven’t yet, you might want to brush up on the overall architecture with this article.
In fact, our tour will begin in the unsupported package, with the Toolkit class, which you see as the second layer in the above diagram. This article is of interest to anybody wanting to work on JavaFX itself.
Toolkit
The Toolkit is the interface which sits between the “top half” of the JavaFX platform (which includes all of the public, supported API) and the “bottom half”. The bottom half of the platform is essentially made up of the windowing code, media engine, web engine, and graphics engine. The Toolkit APIs abstract away the implementation details of these engines from the code sitting above it.
In the early days of JavaFX, going all the way back to JavaFX 1.0, we had two different toolkits: Prism, and Scenario. Scenario was a complete Swing-based implementation, where the AWT EventQueue was used for events and all rendering was done with Java2D. It was the easiest way for us to bootstrap JavaFX while we continued work on the Prism hardware accelerated pipeline and Glass windowing framework which was intended to replace Swing and AWT.
Since then, we’ve had many different toolkit implementations for different prototypes. For example, last JavaOne we showed JavaFX running on Android and on iOS. Both of these demos had their own Toolkit implementations — one which was based on the Android APIs, and one based on iOS. It would not be unreasonable to think that somebody might implement, say, a GWT or JavaScript based Toolkit for rendering in a browser. We also have a mock Toolkit implementation that we use for running unit tests. Sometimes we have stubbed out the toolkit for performance testing purposes, either to simulate what happens when the OS is very slow or to simulate what happens when graphics is blistering fast (i.e.: for doing benchmarking and analysis).
For our own purposes, we have actually consolidated the real implementation on a single toolkit implementation called Quantum, which relies on Prism and Glass for graphics and windowing. But in theory you could write a completely different toolkit which used completely different techniques for rendering and windowing.
The Toolkit API is not pretty. It grew organically, with new methods appearing on an as-needed basis. But it works, and does its job well. It lives in the com.sun.javafx.tk package. The Toolkit API is not a supported API, meaning it can change in incompatible ways (and in fact does quite often). But when developing for the platform or if you are interested in porting JavaFX onto other systems or using alternative graphics / media / web / windowing implementations, the Toolkit would be the place to look.
Scene, Stage, Application, Node, and the Scene Graph
Now back to the supported public API. The core of the JavaFX platform is made up of Scene, Stage, Application, and Node. The Application class really doesn’t do much on its own, but is used as an entry point for launching the application. There is a JavaFX launcher class used to create and invoke the lifecycle methods on the Application.
The Stage and Scene however are much more interesting. Both have a “peer” on the toolkit side, the TKStage (standing, of course, for ToolkitStage) and TKScene interfaces. The Stage will create the peer at the appropriate time by asking the Toolkit to create one for it. The Scene likewise creates a TKScene peer at the appropriate times. Communication is always from the Stage or Scene to the TKStage and TKScene. However in some instances (such as when the window bounds change, or an event is to be delivered) the Toolkit needs to be able to notify the Stage or Scene. For this, we have a TKStageListener and TKSceneListener, and the Stage / Scene is notified of various events through these listeners. There is a TKPulseListener used for notifying the Scene of each animation “pulse”.
Generally speaking, these are the only two places where the Toolkit calls back up to JavaFX code.
The Toolkit will send a “pulse” event to the Scene. During each pulse, the Scene will process CSS, perform layout, update the “picked” node (which nodes have the mouse over them and which don’t), and synchronize with the toolkit.
Each Node has a corresponding “PGNode” peer. Probably we should have called these TKNodes (to stand for ToolkitNode, whereas PGNode stands for PlatformGraphicsNode). And maybe we’ll do such a rename just for clarity. Remember, these PGNodes are not supported API so we can change them at any time!
There are two basic types of Nodes: “leaf” and “parent” nodes. Every leaf node has a different type of PGNode peer. For example there is a PGRectangle, PGShape, PGImageView, and so forth. All parent nodes use the PGGroup as their peer. It is through these peers that the JavaFX nodes tell the toolkit what needs to be drawn where. For example, the Rectangle node tells its PGRectangle peer what the x, y, width, height, fill, and other attributes are that should be used to render the Rectangle. The PGRectangle implementation, provided by the Toolkit, is then responsible for taking care of this. The Toolkit is basically a factory for creating these peer instances. As such, a custom Toolkit can have a completely different implementation of these interfaces.
There is a ton of implementation in Scene and Node and Parent which form the fundamental building blocks of the scene graph and UI controls. Perhaps in the future I can provide additional detail on how these pieces fit together. For example, you can look into Node and see how the layout bounds are computed, the bounds in parent, and so forth. Or how we keep track of which Nodes are dirty and which nodes need their state synchronized with their peers. Or how we keep track of dirty layout and perform layout.
Parent is interesting from an implementation perspective because we went to great lengths to make the computation of the parent node’s bounds cheap. There are some fast paths in there for keeping track of whether a child node’s movement / bounds change impacts the bounds of the parent node (since computing the full bounds of the parent node can be quite expensive).
We get a lot of questions on the JavaFX Forums about layout. You will find that some of the layout basics (such as keeping track of which nodes and branches require layout and the actual layout methods themselves) are built into Parent and Node. You will also find that all of the built in layout managers live in the javafx.scene.layout package. Amy Fowler put a lot of work into writing reusable routines for performing common layout tasks correctly, encapsulating all of the rules regarding “managed” vs. unmanaged nodes, padding, margins, alignment, and so forth.
The other packages are fairly self explanatory, such as the javafx.scene.image package containing the ImageView node and associated APIs, the javafx.scene.input package containing InputEvent and related APIs (such as KeyEvent and MouseEvent), the javafx.scene.shape package containing Rectangle, Circle, Path, and the other shape nodes, the javafx.scene.text package containing the Text node, and so forth.
One other area of interest is the javafx.scene.effect package which contains all of the filter effects in JavaFX. Effects are interesting in that they also have peers. These peers are part of a package called “Decora” which was developed by Chris Campbell at Sun back in the early days of JavaFX, and for historical purposes are in a package called “com.sun.scenario.effect”. We expect this package to be changed to be renamed something sensible, like perhaps com.sun.decora or com.sun.prism.decora. In addition, we expect the way the peers are created to be done through the Toolkit, and the peers to be prefixed with PG or TK or D or something. I hate having two classes with the same name, just in different packages!
This is really just barely scratching the surface of course. The general layout of the code and package structure should be pretty easy to follow. I encourage you to get your hands dirty and learn how JavaFX is built. Not only will it give you insights into how the platform is designed to be used, but will also make it much easier to contribute bug fixes, features, and tweaks to the JavaFX platform.
[…] posts feedrss « JavaFX links of the week, February 13 A Short Tour Through JavaFX-UI-Common […]
Can you release a jar-source file foreach
[…] In OpenJFX news, the scenegraph APIs in the javafx-ui-common project were open sourced. Richard Bair goes into more detail about what this project contains. […]
hi;
your diagram above does not contain the name of the API that is shown in the title of your article (which is UI-common).
It will help reduce confusion if make a diagram which has the name the thing you are talking about.
regard
Rob
As Richard notes in the first paragraph, it is part of the JavaFX Public API block at the top of the diagram.
No Touch and Swipe support??
|
http://fxexperience.com/2012/02/a-short-tour-through-javafx-ui-common/
|
CC-MAIN-2015-40
|
refinedweb
| 1,682
| 62.27
|
Member Since 5 Years Ago Post Method In Route Says 404 | Not Found
Replied to Post Method In Route Says 404 | Not Found
Let's break it down
// In your route you are expecting {product} to be passed in Route::post('/product/{product}','[email protected]')->name('product.alternateimages');
However, in the form itself you aren't passing product at all ..
<form method="POST" action="{{ route('admin.product.alternateimages') }}" enctype="multipart/form-data" class="add-new-post">
Then in the controller itself, you are trying to access
product off
$request ... So whats the solution,
<form method="POST" action="{{ route('product.alternateimages' , [ // call product.alternativeimages as //you have named it in your route 'product' => $product ]) }}" enctype="multipart/form-data" class="add-new-post">
documentation link :
Then in your controller,
public function alternateimages(Request $request, Product $product ) { // logic }
Explore these links to fully understand
Hope that helps
Replied to Liskov Substitution Principle
Thank you @sergiu17 , I think that makes more sense. Much appreciated. I thought I can mark your and @bobbybouwmann answers best at the same time lol. However, I can mark only one answer best. Thank you both for your time
Replied to File In Console Directory Loses Value Inside Another Function?
I think you are setting
$accessToken as local variable rather than class property
protected $accessToken; public function __construct() { // shouldn't this be assigned as a class property // rather than method property $this->accessToken = config('values.accessToken'); parent::__construct(); } ... public function commandWork() { $token = $this->accessToken; //equals null? dd($token); //returns null? ... }
Replied to Liskov Substitution Principle
hey @bobbybouwmann, thanks for your reply and what would be the violation ??
Started a new conversation Liskov Substitution Principle
Hey guys,
I am trying to come up with a real world example for Liskov substitution principle in an ecommerce application context. Now I understand the principle, however, I am struggling to come up with a really good use case. Can any body help out, please?
Replied to Show Latest Videos
May be this is what you need
Replied to Foundation, Bootstrap Or Other
I would say look into tailwind.css , which is a utitly based library. It will help in reducing your css bundle and actually help in coding faster. Foundation and bootstrap are great frameworks, but they come with a lot of baggage
Replied to Object Of Class Closure Could Not Be Converted To String
You have run the query but haven't asked to return any thing ?? try
$query->distinct() ->join('drilldown_boards_items AS dbi', 'dbi.board_item_id', '=', 'available_boards_items.id',function ($join) { $join->on('user_boards_items AS ubi', 'ubi.board_item_id', '=', 'available_boards_items.id'); }) ->addSelect(DB::raw(("AND uib . user_name = '[email protected]'"))) ->addSelect('dbi.board_item_id') ->addSelect('name') ->addSelect('label') ->addSelect('is_dashboard') ->addSelect('is_scoreboard') ->addSelect(DB::raw('(CASE WHEN ubi.user_name IS NULL THEN 0 ELSE 1 END) AS is_selected')) ->orderBy('label', 'desc') ->get();
so you need to call
get() function on query
Replied to A Error In Laravel-5-boilerplate
Hi ya, Please pay attention to the namespace. Your trait is located at
App\Models\Article\Traits\Relationship
But where ever you are using , as from the error page you have provided, its trying to use
App\Models\Auth\Traits\Relationship
Hope that fixes it
Replied to How To Secure An Internal API From Public?
Well I think to make sure that it is an internal api call, you would have a simple middleware which would check the ip address and see if the api call is being made from same api. hope that helps
Replied to Access To API Via A Guest Account With Abilities
I would suggest to take the middleware out and use it in controllers' constructor function where you can specify which routes should be protected and which routes can be accessed without being logged in.
Here is the link for video where Jeffrey talks about middleware
Replied to Formulaire
I think you need to bind your form to model as your Laravel Collective give you that method so maybe something like below
{!! Form::model($post, ['route' => ['news.update', $post->id]]) !!}
Hope that helps
Replied to How To Secure An Internal API From Public?
Hi ya,
I am sure I am quite late to the party. However, I had been stuck myself in an exactly same situation and was trying to figure out a way where I could achieve the same results as described by @aligajani . I am writing my solution and understanding of it for any body who might need it.
After quite a bit of research and understanding how JWT works which by the way I still need to research a bit more to fully understand it. However, to get an overview I can't find a better article to explain in simple words other than.
Now, once I understood how JWT works, it was easy for me to wrap my head around the whole flow. So here is how I approached it. As I am working on an internal API for my company, I created a middleware to check whether a request to certain endpoints is coming from whitelisted API which you can easily get from $request->api().
Then I installed the excellent package by tymondesigns at. I followed the installation and generated the secret key. Now here comes the fun part.
I wanted the end points to be secured without needing for me to be logged in, hence I created my own middleware where I grabbed certain user from my users table and created a JWT token from that user object.
$user = App\User::whereEmail('email')->first() $token = JWTAuth::fromUser($user);
once I got the token all I needed to do was to call my end point i.e. /api/v1/users?token={generatedToken} and voila !!! all good to go. However, we also need to refresh the token after certain time, which again the package thankfully provide two middlewares
jwt.auth and jwt.refresh
jwt.auth midleware tries to create token using authenticate method through credentials, so i swapped it for my middleware where I authenticate user as above and jwt.refreshes the token.
If you read the article I mentioned and then read the package wiki it will all make sense. Cheerio !!
Replied to [Laravel 5.3] Error On Gulp Execution
I am having same problem :(
Replied to Database Connection To SQL SERVER 2012
Right after researching for few days, bumped into this brilliant article about how to connect to SQL SERVER. I hope it might help some one and save him the amount of time i spent trying to figure out how to do it..
Replied to Connect Laravel To Microsoft SQL
Replied to Connect Laravel To Microsoft SQL
Thanks @maximebeaudoin for your help. However, I installed them drivers on the windows that i am running on parallel desktop on my IMAC. Its really frustrating because i have never tried to connect to a SQL Server before. I even tried the OBDC Driver but there is no step by step instructions as how to do it properly. If you do know of any step by step instructions then please let me know. I would really appreciate as its driving me crazy :(
Replied to Database Connection To SQL SERVER 2012
Ok for some reason my question decided to post itself 4 times :(. sorry guys no idea how that happened. As fas i know all i need to do is to provide the parameters as i have shown in the code above and i should be good to go. but its just not working for me :(
Started a new conversation Database Connection To SQL SERVER 2012
I am trying to connect to SQL Server 2012. I have already changed the default from 'mysql' to 'sqlsrv' in my app.php file and have also provided the following connection parameters
'sqlsrv' => array( 'driver' => 'sqlsrv', 'host' => '192.***.**.*', 'database' => 'Database name', 'username' => 'Username', 'password' => 'password', 'prefix' => '', ),
I have tried all sorts but i am getting the pdo exception of driver not found. what am i doing wrong ?? Please help
Replied to Connect Laravel To Microsoft SQL
Hi there, I have been trying to sort out this issue for past week and no luck so far.. I developed the database locally using mysql and now trying to move the application to SQL SERVER 2012 at work and i am getting PDO Exception (Driver not found). Could some one help please ??
|
https://laracasts.com/@alishahUK
|
CC-MAIN-2019-43
|
refinedweb
| 1,385
| 61.77
|
I'm using FOSuserbundle to get started with User registration
I've got it registering / logging in and out. What I want to do now is grab the logged in users data and present it on every page of my site. Like "Hi username" in the header type of thing.
It seems like embedding a controller in my app/Resources/views/base.html.twig is the best way to do this
So I wrote my controller to access the user profile data. What I can't figure out is how to access FOS methods in my embedded controller. So from my Acme/UserBundle/Controller/UserController.php I want to do this:
public function showAction()
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException(
'This user does not have access to this section.');
}
return $this->container->get('templating')
->renderResponse('FOSUserBundle:Profile:show.html.'.$this->container
->getParameter('fos_user.template.engine'), array('user' => $user));
}
You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that :
app.user.
Now, you can access every property of the user. For example, you can access the username like that :
app.user.username.
Warning, if the user is not logged, the
app.user is null.
If you want to check if the user is logged, you can use the
is_granted twig function. For example, if you want to check if the user has
ROLE_ADMIN, you just have to do
is_granted("ROLE_ADMIN").
So, in every of your pages you can do :
{% if is_granted("ROLE") %} Hi {{ app.user.username }} {% endif %}
|
https://codedump.io/share/jGV2ZXU5wUpL/1/accessing-the-logged-in-user-in-a-template
|
CC-MAIN-2016-44
|
refinedweb
| 269
| 50.73
|
#include "gl_box.h"
#include "movie.h"
#include "sphere.cpp"
#include "cylinder.cpp"
#include "gl_box.cpp"
#include "drawable.cpp"
#include "fat_slider.h"
#include <string>
#include <map>
This is the callback function for the fltk file chooser widget which is used in 2 functions.
This is the callback routine for the fltk timer.
Its purpose is to tell the gl_box to redraw its data, which normally causes the frame number to advance. It also sets the timer to fire again.
This is the fltk callback function for the rate_slider widget.
It sets the delay value to the square of the value obtained from the slider widget. This is done to give more control for small time values.
This callback adjusts the gl_size variable to control the sizes of spheres and cylinders.
This callback sets the value of the near_counter when its adjustment buttons are clicked.
This callback sets the value of the far_counter when its adjustment buttons are clicked.
This is the callback function for the frame_counter widget.
It allows moving forward or backward 1 or 10 frames at a time.
This is the callback function for the zoom_slider.
It sets the distance from the view point to the center of the displayed animation.
This is the callback function for the reset_button.
It sets the object and light rotations to their default values.
This is the function invoked by the File--Save Movie menu item.
It sets the portable pixmap prefix in the gl_box based on the user's choice. It also sets the gl_box's save_movie variable so that the gl_box can write each frame to a ppm file after drawing the frame.
This is the function invoked by the File--Save Frame menu item.
It sets the portable pixmap filename in the gl_box based on the user's choice. It also sets the gl_box's save_frame variable so that the gl_box can write the current frame to a ppm file after drawing it.
This is function invoked by the level of detail radio buttons under the Options menu.
The second parameter (user data) is the level of detail (0-9).
This callback sets the spin rate for automatic rotation of the image.
Bigger values mean faster rotation. Positive values turn left and negative values turn right.
This callback calls set_stereo with the proper value to change the stereo mode to normal, fullscreen, stereo or cross-eyed stereo.
This is the callback function for the lights option from the Options menu.
It will either turn OpenGL lighting on or off.
This callback function turns the wobble mode of the gl_box to either on or off.
Wobble mode is useful for molecules to assist in visualizing the 3D structure.
This is the callback function for the transparency option from the Options menu.
It will either turn OpenGL pixel blending on or off.
This is the axes callback function from the Options menu.
It sets the gl_box's axes variable to enable or disable drawing axes.
This is the box callback function from the Options menu.
It sets the gl_box's box variable to enable or disable drawing a box around the displayed data.
This is the callback routine for the trans_button widget.
The user data (second parameter) is the index of the color for adjusting alpha values with the trans_slider widget.
This is the callback function for the trans_slider widget.
It changes the alpha value for the selected color. This change takes effect on the next draw cycle in the gl_box.
This is the callback function for the color_button.
The user data determines which color to adjust. If the user data is 0, then the OpenGL clear color (background) is adjusted. If it is positive, the color index value is set to 1 less than the user data value.
The fltk fl_color_chooser function is used to adjust the selected color.
This function is called after opening a movie file to set the menu items for the color_button and trans_button.
It sets the color menu to have options for the background and all the colors in the movie. Each menu item sets the user data to indicate which color to adjust.
It sets the transparency menu to have options for all the movie's colors. The background is opaque.
This callback uses the fl_file_chooser function to select either an animp movie file (.an) or a molecule file (.pdb).
Function to handle unassigned menu options.
There should not be any of these.
This callback writes ".animprc" and exits.
This function reads ".animprc" and sets values stored there.
Store more state variables in ".animprc".
When opening a file, the data normally used for drawing the GL display is being modified.
The in_open variable is used to avoid drawing the display while the data is being read.
[static]
Animp uses one movie structure to hold the data for displaying either a movie or a molecule.
This movie pointer (m) is passed into the gl_box structure using set_movie.
rev_color_table is used to get the element string like "He" for a color index when building the color button menu.
The window variable is used only within animp.cpp to refer to the fltk window.
It is primarily used in main with 1 use in the quit callback to make the window disappear so Fl::run() can return.
The animp controls are placed in an Fl_Group to facilitate diplaying/not displaying the controls.
In full-screen mode the controls are not displayed.
The gl pointer is a pointer to the gl_box which is used to display the animation.
It is a global variable for convenient access by callback functions for the fltk widgets.
The rate_slider widget controls the length of time for the timer callback.
Sliding left shortens the time. A shorter time results in a faster animation.
The size_slider controls a scaling factor for spheres and cylinders.
The near_counter is used to specify the front clipping plane for software clipping.
It starts at 0.0 which clips nothing and can be as large as 1.0 which would clip everything.
The near_counter is used to specify the far clipping plane for software clipping.
This is added to the near_counter value to determine the far clipping value. It starts at 1.0 which clips nothing. Once set to a small value it will work in concert with the near_counter to allow viewing slices of the data.
The zoom_slider controls the distance of the view point from the middle of the displayed data.
The trans_slider controls the alpha value for the currently selected color.
The stop_button is used to pause the animation.
The reset_button is used to reset the rotation of the displayed data and the rotation of the light source.
The frame_counter widget is used to advance (or reverse) the movie 1 or 10 frames at a time.
The color_button is used to bring up a list of colors to adjust.
Once a color is selected, the user is presented a color selection widget to adjust that color.
The trans_button is used to display a list of colors to select.
The selected color's alpha value can then be adjusted using the trans_slider.
The name array is used to hold the file name selected using the fltk file chooser widget.
This is the time for the fltk timer used to control the animation speed.
This is the scale factor for increasing or decreasing the size of spheres and cylinders.
The color_select variable is used to determine which color is to be adjusted by the trans_slider widget.
It is set in one function and used in another, so it is easier to make it global.
This is an array of menu items for easy construction of the transparency menu.
This is an array of menu items for easy construction of the color menu.
FLTK menu for the menubar at the top of the screen.
|
http://animp.sourceforge.net/animp_8cpp.html
|
CC-MAIN-2017-43
|
refinedweb
| 1,304
| 76.62
|
[Please don't CC me when replying to the list. Thanks.] I wrote: >To give us something substantial to debate/argue over, I'll try writing >a first draft of this function and some documentation for it this >weekend. I'll post it here for criticism, hopefully Monday. Okay, here it is. I'm not too sure about setID; I -think- the way it works is such that a setID program will have its real id different from its effective id, and that this will also be the case for any programs it invokes. Is that right? Anyway, see what you think. It's a bit rough and ready, and has had virtually no testing, but it should be enough to spark off criticism. If you can tell me what's wrong with it, I'll try to fix it! --Charles Briscoe-Smith White pages entry, with PGP key: <URL:> PGP public keyprint: 74 68 AB 2E 1C 60 22 94 B8 21 2D 01 DE 66 13 E2 /* fopenconf -- Locate and open configuration file Copyright 1997 C. P. Briscoe-Smith! */ #include <stdio.h> FILE *fopenconf (const char *filename, const char *opentype, const char *overridepath); /* The `fopenconf' function opens an I/O stream to a configuration file named FILENAME, and returns a pointer to the stream. The configuration file is searched for along the configuration path, as specified below. The OPENTYPE argument is a string that controls how the file is opened and specifies attributes of the resulting stream. It is interpreted as for `fopen'. If the OVERRIDEPATH argument is NULL, fopenconf obtains the configuration path internally, otherwise OVERRIDEPATH is used as the configuration path. If obtaining the configuration path internally, fopenconf checks whether the effective uid and gid are the same as the real uid and gid. If there are any differences, a built-in configuration path is used, otherwise the configuration path is obtained from the environment variable "CONFIG_PATH". The path is always searched to find the file; it is illegal for the FILENAME argument to begin with a '/'. It is explicitly allowed for a '/' to be present in FILENAME other than at the beginning; this allows configuration files to be hierachically organised below the configuration directories. The path search is carried out as follows. Each colon-separated path element is tried in turn. A slash and the FILENAME are appended to the path element and lstat(2) called on the result. If this succeeds, the resulting path is used. If the search fails to produce an accessible file, or the open fails, `fopenconf' returns a null pointer. */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <string.h> FILE * fopenconf(const char *filename, const char *opentype, const char *overridepath) { const char *path; const char *builtinpath="/etc:/usr/local/etc:/usr/etc"; size_t trailerlen=strlen(filename)+2; if (overridepath) path=overridepath; else if (getuid()!=geteuid() || getgid()!=getegid()) path=builtinpath; else path=getenv("CONFIG_PATH"); if (path==0) path=builtinpath; while (path) { const char *elem=path; size_t len; char *fullname; struct stat statbuf; path=strchr(path, ':'); if (path) { len=path-elem; path++; } else { len=strlen(elem); } if (len==0) { len=1; elem="."; } fullname=malloc(len+trailerlen); if (fullname==0) return 0; strncpy(fullname, elem, len); fullname[len]='/'; strcpy(&fullname[len+1], filename); if (lstat(fullname, &statbuf)==0) { FILE *fp=fopen(fullname, opentype); free(fullname); return fp; } free(fullname); } return 0; } #ifdef TEST void testit(const char *name, const char *override) { FILE *fp; struct stat statbuf; fp=fopenconf(name, "r", override); printf("Tried `%s'. %s.\n", name, fp ? "Okay" : "Bad"); if (fp) { fstat(fileno(fp), &statbuf); printf(" %4d,%8d %04o l:%2d u:%8d g:%8d s:%8d\n", statbuf.st_dev, statbuf.st_ino, statbuf.st_mode, statbuf.st_nlink, statbuf.st_uid, statbuf.st_gid, statbuf.st_size); } } int main(void) { testit("termcap", NULL); testit("termcap", ""); return 0; } #endif -- TO UNSUBSCRIBE FROM THIS MAILING LIST: e-mail the word "unsubscribe" to debian-devel-request@lists.debian.org . Trouble? e-mail to templin@bucknell.edu .
|
https://lists.debian.org/debian-devel/1997/07/msg00827.html
|
CC-MAIN-2015-27
|
refinedweb
| 664
| 55.03
|
A digest of the weeks news, articles and book reviews on I Programmer from Thursday 2nd February to Wednesday 8th February.
I Programmer Weekly Wednesday 08 February
Use the I Programmer Weekly menu option to find out what was published in the news, book reviews and articles for any week on I Programmer.
Social Game Players Sue Google Wednesday 08 February
Many groups of users have been angry with Google over its axing of projects, tools and resources but one group is so incensed about the closure of the SuperPoke Pets website that it has initiated a class action asserting "fraud in the inducement and unjust enrichment".
Amazon's Cloud Comes To Windows Phone Wednesday 08 February
Microsoft has released a beta version of a toolkit that lets you create Windows Phone apps that can connect to Amazon Web Services.
Google's X Site Solved Tuesday 07 February
Yesterday we ran a news item on Google's mysterious Solve for X website. Now the mystery is solved and we know what it is all about.
Windows Phone Marketplace Expands Tuesday 07 February
Microsoft has announced that five of the recently announced Windows Phone 7 markets (Argentina, Indonesia, Malaysia, Peru, and the Philippines) are now officially open for business.
PostgreSQL Plus Cloud Database Tuesday 07 February
EnterpriseDB has ported its Postgres Plus to Amazon Web Services to create Postgres Plus Cloud Database.
Google's X Factor - A TED Replacment? Monday 06 February
Google is launching yet another website. It is designed to be a forum to discuss off-the-wall ideas and cutting edge technologies. Is this Google's answer to TED.com?
Widespread Celebrations But No Pardon For Turing Monday 06 February
A petition signed by over 21,000 people asked the UK Government to grant a pardon to Alan Turing. That request has now been declined.
Online Computer Science Education for Free Monday 06 February
Last.
Siri Horror - Again Sunday 05 February
This Siri video is professional enough to be a trailer for a movie. Take a look, but be warned this one isn't so funny as scary.
Google Summer of Code 2012 Sunday 05 February
Google's 8th year of its program that gives students the chance of working in open source software development during their summer break was announced at the FOSDEM open source conference in Belgium.
Cartoon - Recursion Sunday 05 February
This week's selected xkcd cartoon of the week is about the most feared of programming concepts - recursion. And, to paraphrase a well known quote, if you don't fear it, then you don't understand it.
ACTA Activists Organize Street Protests Saturday 04 February
As awareness of ACTA spreads protests are being organized across Europe, in the hope of stopping a treaty that threatens Internet freedom and is seen as more dangerous than SOPA.
$100,000 Prize For Proving Quantum Computers Are Impossible Saturday 04 February
Quantum computing is currently a major area of research - but is this all a waste of effort? A prize of $100,000 has been offered for any proof that quantum computers are impossible.
Joomla Magazine February 2012 Friday 03 February
The promise of becoming your own SEO expert forms one of the articles in the February issue of the Joomla magazine, which is now available.
Google's Bouncer Detects Malware Friday 03 February
Google has revealed Bouncer, a service it has developed for automated scanning of apps submitted to the Android Market to eliminate malware.
Windows Phone 8 - Silverlight Apps Are Legacy Friday 03 February
It isn't exactly official, but if reports based on a leaked internal video are true, the Windows Phone 8 (WP8) codenamed Apollo is going to be based on Windows 8 code.
LibreOffice Development Status Report Friday 03 February
Since The Document Foundation was announced in September 2010 it has made tremendous progress with LibreOffice, now summarized in an infographic. It is a real insight into the workings of a major open source project.
Perl Foundation Receives Cash Injection Thursday 02 February The craigslist Charitable Fund has donated $100,000 to the Perl community for Perl5 maintenance and general use.
Google+ Page For Android Developers Thursday 02 February
Over 35,000 people have already demonstrated support for the new Android Developer Google+ page - which makes you wonder why it took so long to create.
Firefox 10 - More For Developers Thursday 02 February
Only six weeks after Firefox 9, the latest version, 10, is now being downloaded onto users' machines. And its main new features are aimed at developers. Is this the start of the browser developer wars?
Getting Started with Python Wednesday 08 February
So you want to get up to speed with Python. Here's a lightening tour for the beginning to intermediate programmer who is already familiar with some fundamental programming ideas.
Private Functions In JavaScript Friday 03 February
JavaScript doesn't have a native namespace facility so how are you supposed to keep utility and helper functions private? The solution is to use inner functions but this is just the start of the story.
Getting started with Windows Kinect SDK 1.0 Monday 06 February
Version 1.0 of the Kinect SDK is now available together with the Windows version of the Kinect hardware. Now you can get started creating full commercial applications. Our new e-book shows you how to do this in C#.
|
http://www.i-programmer.info/i-programmer-weekly/187-2012/3763-february-week-1.html
|
CC-MAIN-2016-44
|
refinedweb
| 896
| 50.46
|
Printable View
You right part 2 isn't really useful in a pentest. I don't do this as a job. It's just a hobby so I didn't really think about that.You right part 2 isn't really useful in a pentest. I don't do this as a job. It's just a hobby so I didn't really think about that.Quote:
First off, great script. (BTW if anyone here has any perl coding skills, I'm writing an ASM ghostwriting automation tool in perl. Any help would be appreciated. that should help to make FUD paylaods.)
Second off I get this errror on part two. Also, I'm not entirely sure how to integrate part two into a pentest. All this does is set up the site and java so that when a user browses to my ip from a spoofed DNS response he will be pwned?
[*] Stripping out the debugging symbols...[*] Moving trojan horse to web root...
**************************************
1) apache server
2) java applet attack
3) create evil PDF
**************************************
Select an attack (1-n):2
Traceback (most recent call last):
File "./crypter.py", line 137, in <module>
subprocess.Popen(args=["gnome-terminal", "--command=sh /opt/metasploit/msf3/javaAttack.sh"]).pid
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or director
I've been getting this output and trying to debug, but so far I have no idea whatt's causing it. Do you?
As for your error, did you set execution permission for javaAttack.sh and is it in your metasploit directory ?
If you did and it still isn't working maybe changingtotoCode:
subprocess.Popen(args=["gnome-terminal", "--command=sh /opt/metasploit/msf3/javaAttack.sh"]).pid
will work.will work.Code:
subprocess.call('sh javaAttack.sh')
This is a strange error and you are the first one to have it.
I don't think I will able to help with your ghostwriting tool as I don't know so much about asm and I haven't really done much in perl before.
I'm kind of trying to learn more asm cause I find you need it a lot.
To make my script FUD again I thought to write a c++ program that would call a process in suspend mode and then write the shellcode to the process and resume the process. This is kind of a known method to AV's so I would need to obfuscate my API calls.
I also think that encrypting your shellcode on disk and decrypting it in memory is not good enough anymore. AV sandboxes really step step per step trough your program until they find something. Ghostwriting asm is probably the best option.
Also this seems interesting:
Any more ideas ?
So I read that paper, and it was pretty awesome. If you can use that in your script it would be pretty cool. A couple things. 1) Allow for just compiling and placing of the trojan in root. Do not force the listener to be started. In a pentest with phishing, it is annoying to have to cancel the listener every time, instead of continuing down the custom payload path with your executable.
2) when I finally finish my ASM GW script, allowing for default payload obfuscation, integration into your script would be very cool. Do not let this stop you from writing your own, I have several py ghostwriting scripts I can give you to help you get started.
3) My javaAttack.sh is obviously both executable and found in the dir, but even when I change your line to the suggested one it fails with the same error.
4) Have you looked at using different wrappers for the shellcode? usually it's the wrapper that is detected and not the sc. See: for several cool examples.
5) Maybe you can have a c/c++ prog inject the shellcode to a running process or something. Again, many methods exist for this.
6) Have you checked out shellcodeexec? You should. You may find it cool.
Let me know what you think of all these. :D
1)I tested the method of connecting to 127.0.0.1:445 to check that your malware is running in a sandbox or not and it worked on avira and some other av's. Altough it doesn't bypass all of them. I know av's don't like socket API's so maybe I'll try to hide them. I'll post the code for this tomorrow. I will allow for just compiling and placing the exe in /root in the next version of the script.
2)Yes it would be really cool to integrate the scripts. Also I would really appreciate it if you would share one of your py GW scripts. I think I could learn a lot from them.
3) Tomorrow I'll take a deeper look at the error. I'll finally have some time to work on the script :p
4)I'll look into it. Altough I don't really like to use c# for this. You would always need a windows machine to compile.
5)I'll try some different methods and see wich one is the best.
6)I'll also check it tommorow.
ThisThisCode:
import random
reg32 = ["EAX", "EBX", "ECX", "EDX", "ESP", "EBP", "ESI" ,"EDI"]
reg16 = [['AL', 'AH'], ['BL', 'BH'], ['CL', 'CH'],[ 'DL', 'DH']]
BitWiseOps = ["And", "Or", "XOr", "Mov"]
StackOps = ["Push", "Pop"]
Xors = [["XOR {DREG}, {DREG}", "MOV {REG}, {DREG}"],
["SUB {REG}, {REG}"],
["OR {REG}, ffffffffh", "Push {DREG}", "MOV {DREG}, ffffffffh", "SUB {REG}, {DREG}", "Pop {DREG}"],
["OR {REG}, ffffffh", "AND {REG}, 55555555h", "AND {REG}, AAAAAAAAh"]]
Movs = [["OR {REG}, ffffffffh", "AND {REG}, {amount}"], ["XOR {REG}, {REG}", "ADD {REG}, {amount}"]]
def GhostWriter():
file = open(sys.argv[1], 'r')
fileLines = file.read()
fileLines = fileLines.splitlines()
for i in range(len(fileLines)):
l = fileLines[i]
if len(l) < 4:
print "invalid line is less than 5 characters long :" + l
#break;
elif l[:1] == "//":
print "comment line: " + l
else:
if l[:3] == 'Pop' or l[:4] == 'Push':
l = stack(l)
else :
l = bitWiseObfuscation(l)
fileLines[i] = l
newName = sys.argv[1]#.split('.')
if len(newName) > 1 : newName = newName.replace(".", "REMADE.", 1)
else: newName = sys.argv[1] + "REMADE"
newFile = open(newName, 'w')
for l in fileLines: newFile.write(l)
newFile.close()
print "file saved as: " + newName
def bitWiseObfuscation(l):
cmds = readCommand(l)
print cmds
if len(cmds) == 3:
if cmds[0].upper() == "XOR" and cmds[1].upper() == cmds[2].upper():
newRegister = getRandomRegister(cmds[1].upper())
newCommands = Xors[random.randint(0,3)]
finalCommand = ""
for c in newCommands: finalCommand += c + "\n"
finalCommand = finalCommand.replace('{DREG}', newRegister)
finalCommand = finalCommand.replace('{REG}', cmds[1].upper())
finalCommand = finalCommand.replace('{REG}', cmds[1].upper())
return finalCommand
elif cmds[0].upper() == "MOV":
newCommands = Movs[random.randint(0,1)]
finalCommand = ""
for c in newCommands: finalCommand += c + "\n"
finalCommand = finalCommand.replace('{REG}', cmds[1].upper())
finalCommand = finalCommand.replace('{amount}', cmds[2].upper())
return finalCommand
return l + "\n"
def getRandomRegister(register):
newRegister = reg32[random.randint(0,7)]
if newRegister != register.upper(): return newRegister
else: return getRandomRegister(register)
def stack(command):
return command
def readCommand(command):
commandParts = command.rsplit()
for i in range(len(commandParts)):
if len(commandParts[i]) == 3 and ',' in commandParts[i]:
commandParts[i] = commandParts[i].replace(',', '')
elif len(commandParts) == 2 and ',' in commandParts[i] and i == 1:
commandParts = [commandParts[0]] + commandParts[1].split(',')
return commandParts
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print "please write a path to a file as the first parameter (after the script name)"
else:
GhostWriter()
nice tool , ive modified loop values to 105000 but yet it is detected by kaspersky , avira , f-secure , bitdefender please have a look to update it so it may bypass all of them. I would say to make it dynamic ghostwriting .
Regards
Scorpoin
As I've been working on ASM ghostwriting for the past many months, I can tell you this with some authority. To do anything more complicated than xor or static string replacement is *HARD*. THis is not something that'll happen overnight.
Thanks for your prompt response. @Shadow and @LHYX1 could you guys please help me out what do I need to change to avoid this detection since it is scantime based not runtime based encryption. @LHYX1 Ive edited your script structure.c to fulfill my need.
Please share you valuable thoughts and do let me know some guide or something where I can learn more. If possible let me know if possible to make changes to current script. I have not make any changes to cyrpter.py .Please share you valuable thoughts and do let me know some guide or something where I can learn more. If possible let me know if possible to make changes to current script. I have not make any changes to cyrpter.py .Code:
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <time.h>
int main(){
char junkA []= %s;
unsigned char payload[] = %s;
char junkB []= %s;
unsigned char key = %s;
unsigned int PAYLOAD_LENGTH = %s;
int i;
unsigned char* exec = (unsigned char*)VirtualAlloc(NULL, PAYLOAD_LENGTH/2 ,0x1000,0x40);
unsigned char* unpack = (unsigned char*)VirtualAlloc(NULL, PAYLOAD_LENGTH/2, 0x1000,0x40);
int z, y;
int devide;
int x = 0;
time_t start_time, cur_time;
time(&start_time);
do
{
time(&cur_time);
}
while((cur_time - start_time) < 2);
for(i=0; i<PAYLOAD_LENGTH; i++)
{
devide = %s
if(devide == 0)
{
unpack[x]=payload[i];
x++;
}
}
for(i=0; i<PAYLOAD_LENGTH/2; i++)
{
for(z=0;z<7000;z++)
{
for(y=0;y<700;y++)
{
exec[i]=unpack[i]^key;
}
}
}
((void (*)())exec)();
return 0;
}
Regards
scorpoin
@LHYX1
Sorry for the thread hijack, but wanted you to check this out:
@ info:
if anyone hear .. the ""package mingw32"" is the DEFAULT install in BT5-R3!:)
|
http://www.backtrack-linux.org/forums/printthread.php?t=48522&pp=10&page=11
|
CC-MAIN-2014-35
|
refinedweb
| 1,634
| 67.25
|
Clojure: Basic Syntax
This page is WORK IN PROGRESS.
comma and space
comma can be used as separator.
;; comma can be used as separator ;; the following are equivalent (+ 1 2 3) ; 6 (+ 1, 2 , 3) ; 6
comment
;; by lisp convention ;; comment on a line by itself start with 2 semicolons (+ 3 4) ; comment after a expression start with one semicolon
Comment can also be written as
(comment …), but the comment body must be a valid lisp syntax, cannot be any character.
This returns
nil.
;; comment can also be written as (comment …) (comment this is a block comment. (comment block comment can be nested.) )
;; comment body must be valid clojure syntax. ;; a semicolon by itself is not (comment : ) ;; compiler error
You usually use this form
(comment …) to comment out a block of Clojure code.
;; (comment …) is usually used to comment out block of code (comment (+ 3 4) )
printing
use
pr to print. It returns
nil.
(pr "aa" "bb" "cc") ; prints "aa" "bb" "cc"
prn → same as
pr but with a newline at the end.
pr and
prn prints in a machine-readable way. (that is, can be read back by Clojure.)
To print in a human friendly way, use
println
strings
"some string abc"
to join string (concatenate), use
str. clojure.core/str
;; join string (str "aa" "bb") ; "aabb" (str 3 " cats") ; "3 cats"
substring
(subs str start_index)
(subs str start_index end_index)
Index start at 0. Start index is inclusive. End index is exclusive.
;; get substring, starting at index 1. (subs "abcd" 1) ; "bcd" ;; get substring, with start/end indexes. (subs "abcd" 1 3) ; "bc"
Clojure string functions
For string functions, use the Clojure library
clojure.string.
clojure.string - Clojure v1.8 API documentation
Example of calling a function in
clojure.string namespace:
; calling function upper-case from namespace clojure.string (clojure.string/upper-case "bb") ; BB
Note: slash is used to separate name space.
Call Java's String Methods
Clojure itself doesn't have many string functions. It is common to call Java's methods in Clojure.
String (Java Platform SE 8 )
To call Java's string method, use the syntax
(. java_object method_name args).
For example, there's Java String method named
charAt. To use it, do:
;; call Java method on object (. "abc" charAt 1) ; \b
A more commonly used syntax to call Java method is
(.method_name java_object args)
(.charAt "abc" 1) ; \b
〔►see Clojure: Call Java Method〕
Numbers
Numbers can be written in the form
baserdigits. For example, the binary number
10 can be written as
2r10, and the hexadecimal
1a can be written as
16r1a
;; binary number input 2r1111 ; 15 ;; hex number input 16r1af ; 431 0x1af ; 431 (this form is from Java) ;; oct number input 8r77 ; 63 ;; base 36. using 0 to and a to z as digits 36rj7 ; 691
Arithmetic
;; addition, plus (+ 3 4) ;; substraction, minus (- 7 4) ;; can have 3 or more args (- 7 4 1) ;; multiply, times (* 2 4)
Here's division, quotient, remainder/mod, and ratio.
;; division (/ 7 4) ; 7/4 return a ratio. A Clojure datatype (/ 7 4.) ; 1.75 ;; integer quotient (quot 11 4) ; 2 ;; remainder (aka mod) (rem 11 4) ; 3
Closure does not have a math lib bundled.
To use math function such as sine, use Java's Math class. Like this:
(Math/methodName arg)
;; exponentiation. 2 to the power of 3 (Math/pow 2 3) ; 8.0
Math (Java Platform SE 8 )
〔►see Clojure: Call Java Method〕
Converting String and Numbers
;; convert string to number (bigint "123")
;; convert number to string (str 123)
Codepoint to Character
;; unicode codepoint (integer) to char (char 97) ; a
Comparison Functions
(< 3 7) ; true (<= 3 7) ; true (> 3 7) ; false (>= 3 7) ; false
logic operations:
;; boolean and (and true false) ; false ;; boolean or (or true false) ; true ;; boolean not (not true) ; false
Block of Expressions
Sometimes you need to group several expressions together as one single expression. This can be done with
do. (“do” is like lisp's “progn”)
(do (pr "a") (pr "b")) ;; is equivalent to (pr "a") (pr "b")
Most of the time it's used inside “if”. clojure.core/if
For example:
(if something (do ; true … ) (do ; else … ) )
do returns the last expression in its body.
(do 3 4 ) ; 4
define global variable
Use
def to set a value to a variable. Variable does not need to be declared.
;; define a var (def x 3) x ; 3
def can be used to change a variable's value.
;; define a var (def x 3) (pr x) ; 3 ;; reset to 4 (def x 4) (pr x) ; 4
Local Constants: let
To create local constants, use
let. It has this form
clojure.core/let
(let [var1 val1 var2 val2 …] body)
(let [x 3] x) ; 3
(def x 4) (let [x 3] (pr x) ) ; 3 (pr x) ; 4
You can bind multiple variables:
(let [x 3 y 4] (+ x y)) ; 7
Later variable can use values of previous variables:
(let [x 3 y x] (+ x y)) ; 6
the value part can be any expression.
(let [x 3 y (+ 2 x)] (+ x y)) ; 8
Binding Form
The first arg of
let is called “binding form”. It is also used in function definition. 〔►see Clojure: Functions〕
Clojure's binding form is very flexible. You can do Destructure Binding. 〔►see Clojure: Binding Forms, Destructuring〕
True and False
The following are builtin literals.
true
false
nil
Clojure
nil is Java's
null.
false and
nil are false, everything else evaluates to
true in true/false context.
(if nil 1 2) ; 2
If Then Else
The form for if statement is:
(if test body).
If you want a “else” part, the form is
(if test true_body false_body). Use a
(do …) to group the bodies.
if returns the value of the evaluated branch.
Example:
(if (< 3 2) 9 ) ; nil
(if (< 3 2) "yes" "no" ) ; "no"
(if nil 3 4 ) ; 4
Iteration
Here's basic functions related to iteration:
(for [i (range 7)] (inc i)) ; (1 2 3 4 5 6 7)
clojure.core/range clojure.core/inc
Recursion
A function that calls itself is called recursion.
In a function definition, If a function calls itself as exit, then such recursion is called tail recursion or linear recursion.
Linear recursion is not nested in nature. You can think of it as “pass and forget”.
What is the difference between tail-recursion and non-tail-recursion?
Tail recursion can be trivially expressed as iteration or linear loop.
In programing languages, some programing language automatically compile tail-recursion into a iteration. (so that, it saves memory, avoiding stackoverflow, etc.) Scheme (programming language) is the language most famous for enforcing the tail-recursion optimization into its compiler, by spec.
Clojure supports recursion. That is, function can call itself.
Clojure also supports manual tail-recursion using
recur. That is, the compiler optimize recursion that's linear into a iteration-like construct.
If the recursion is linear recursion, than you can call
recur at the place you want to call function itself. The advantage is that there'll be no limit on recursion depth.
Collection and Sequence: list, vector, hash table …
Clojure: Collections (List, Vector, Set, Map, …), Sequence
Defining a Function
Clojure data types
Clojure is not typed. Variable doesn't have a type, value has type.
Clojure Char Data Type Literal
- Newline (Line Feed; Unicode codepoint 10 in decimal) is
\newline
- Tab character (Unicode codepoint 9 in decimal) is
\tab
- Unicode character can be written as
\u4_digits_hex. For example, α is
\u03b1(what about outside bmp?)
keywords
“keyword” is a primitive datatype in Clojure. Keywords are symbolic identifiers. Usually used as keys for hash table. It's like Ruby's “symbol”.
keywords starts with a
:, like this:
:abc
To convert a string to keyword, use
keyword function.
keyword is also a function. The work on hasmap and return the corresponding value.
symbols
Clojure symbols is the same as other lisp “symbols”. Symbols are identifiers, but unlike identifier in other languages, Clojure's “symbol” can remain in a unevaluated form.
symbols, eval to themself. Like other lang's variables, but can hold eval.
but symbol is also a function, that can work on hashmap and look themself up.
symbols can include these characters: * + ! - _ ?
global settings often starts and end with a asterisk, for example:
*max*
namespace
regex
states, transactions
- refs → {synchronous, coordinated}.
ref
- agents → {asynchronous, independent}.
agent
- atoms → {synchronous, independent}.
atom
- var → like global var.
def
“refs” is typical set variable.
(deref val) is same as
@val
transactions
“transactions” is like database transactions. Process inside a transaction happen together or not at all, there's no possibility of partial success. (this property is often called “atomicity”)
“transactions” are isolated. No 2 transactions see each other.
dosync creates a transaction. Other wise it's similar to
do. clojure.core/dosync
ref-set is for setting a ref. It can only be used within a transaction. clojure.core/ref-set
alter is like
ref-set, except it takes a function and other args. clojure.core/alter
atom
atom is like ref, except it's rather for independent entities (update that do not need to be coordinated with others).
agents (asynchronous)
most useful.
thread-local state: var, def
validator and watch
clojure.core/set-validator!
understanding clojure
reader forms
- symbol
- literals
- lists
- vectors
- maps
- sets
- deftype, defrecord, constructor calls
symbols begin with a non-numeric character. Can contain 0 to 9, a to z, * + ! - _ ?
/ is used once to separate namespaces.
. has special meaning — it can be used one or more times in the middle of a symbol to designate a fully-qualified class name, for example, 「java.util.BitSet」, or in namespace names.
Symbols beginning or ending with . are reserved by Clojure.
Symbols containing / or . are said to be 'qualified'.
Symbols beginning or ending with : are reserved by Clojure. A symbol can contain one or more non-repeating ':'s.
forms → lisps refer to its syntax units as “forms”. For example,
(+ 3 4) is a form. Anything that returnsa value is a form.
literal → a form that eval to itself. String
"…", number, character
\b, are literals.
true,
false,
nil, are also literals.
symbol → Symbols are like other lang's identifiers, except that lisp symbol is a identity that can be held unevaluated and be manipulated in unevaluated state. For example, if x has value of 3 (
def x 3), then
'x eval to the symbol “x” itself, not its value. Macros are possible because of this. (You can think of “symbol” as a string, a label, a identifier.)
expressions → a form made of other forms. Typically they are enclosed by brackets. For example, list
(…), vector
[…], map
{…}.
Normally, a form is a function in the form of a list 「(‹head› …)」. The first element is the symbol of the function. The rest are arguments, and are evaluated in order.
special form → a form that has different evaluation order or special in some other way. For example,
if is a special form.
|
http://xahlee.info/clojure/clojure_basics.html
|
CC-MAIN-2017-39
|
refinedweb
| 1,810
| 67.45
|
On Mon, Sep 30, 2002 at 09:32:07AM -0700, Sean 'Shaleh' Perry wrote: > On Monday 30 September 2002 09:23, Clint Adams wrote: > > >... > > > > I don't think an interactive preinst is appropriate, people get upset > > about debconf notes, and warning anywhere after the binary is unpacked > > is too late. Do you have a better way? > > bogofilter2 (or whatever) like most of the other packages do when they > completely break things? > > We are all thinking about this today. What happens in 6 months, a year, > when a user from stable upgrades and loses their filtering software? But bogofilter isn't in stable, it's only in unstable and this makes a difference. So I would say it's better not to clutter up the namespace by changing the package name. Of course, I would also tend to vote for the interactive preinst, since this is quite a major change. It seems like if an interactive preinst is ever appropriate, this would be it. Also, I would guess that the worst case scenario should be that all of a user's mail starts getting sent to the spambox, which is hardly the end of the world. Any user who has set up procmail to delete mail based on bogofilter has a seriously unstable system as it is. -- David Roundy
|
https://lists.debian.org/debian-devel/2002/09/msg02194.html
|
CC-MAIN-2015-22
|
refinedweb
| 218
| 70.63
|
Subject: Re: [boost] [Endian] Performance
From: Phil Endecott (spam_from_boost_dev_at_[hidden])
Date: 2011-09-07 15:03:56
Stewart, Robert wrote:
> Examples were given recently of swapping bytes in large data
> sets, where each extra cycle quickly accumulates into noticeable
> delays.
I've just tried this:
static inline uint32_t byteswap(uint32_t src)
{
return (src<<24)
| ((src<<8) & 0x00ff0000)
| ((src>>8) & 0x0000ff00)
| (src>>24);
}
int main()
{
uint32_t buf[1024];
while (1) {
size_t bytes = read(0,buf,4096);
if (!bytes) break;
std::transform(buf,buf+bytes/4,buf,&byteswap);
write(1,buf,bytes);
}
}
My first test file is a 600 MB video, which is large enough to fit into
the test system's RAM; these timings are for "warm" runs i.e. the test
data is all cached. This is on the i.MX53 system I called "B" in my
last posts. Output is redirected to /dev/null.
1. With the byteswapping DISABLED, i.e. just the I/O:
real 0m2.495s
user 0m0.030s
sys 0m2.460s
2. With the byteswapping enabled, compiled with -O4:
real 0m3.019s
user 0m0.900s
sys 0m2.110s
In this case the core of the assembler is this nice simple loop:
L4:
ldr r1, [r3, #0]
rev r1, r1
str r1, [r3], #4
cmp r0, r3
bne .L4
3. With the byteswapping enabled, compiled with -O4 -funroll-loops:
real 0m2.516s
user 0m0.450s
sys 0m2.060s
(This code is much longer and less readable but it seems to be worthwhile.)
4. Then I tried this bytewise swapping: (Please tell me if you think
this code is wrong, I didn't check the output)
char buf[4096];
while (1) {
size_t bytes = read(0,buf,4096);
if (!bytes) break;
for (int i=0; i<bytes; i += 4) {
std::reverse(buf+i,buf+i+4);
}
write(1,buf,bytes);
}
Timing with -O4: (loop unrolling seems to make no improvement)
real 0m5.131s
user 0m3.180s
sys 0m1.940s
Increasing the block size doesn't make any significant difference;
reducing it below 4096 bytes does slow it down.
So the overhead of byteswapping compared to I/O - for a file cached in
memory - is between about 25% (case 3) and 150% (case 4) on this system.
I've also done a quick test with a file that is larger than RAM and so
must be read from the SSD. In this case the results are:
Case 4 above, bytewise swapping:
real 0m44.969s
user 0m15.910s
sys 0m12.800s
Case 3 above, rev instruction with loop unrolling:
real 0m44.624s
user 0m2.290s
sys 0m12.990s.
Regards, Phil.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
|
https://lists.boost.org/Archives/boost/2011/09/185636.php
|
CC-MAIN-2019-22
|
refinedweb
| 451
| 77.84
|
First time here? Check out the FAQ!
I wish to return the result of a calculation done in Cython with the result of mpc_t to ComplexNumber
from sage.libs.mpc cimport *
cpdef f():
cdef mpc_t z
mpc_init2(z, 1024)
mpc_set_ui(z, 11, MPC_RNDNN)
# how to convert the result to a ComplexNumber with the corresponding precision???
return ?
This should return ComplexNumber(7,0) with precision 1024 bits. What is the correct spell?
The real counterpart just works fine:
from sage.rings.real_mpfr cimport RealNumber
from sage.rings.real_mpfr import RealField
cpdef g():
cdef RealNumber my_number = RealField(128)(5)
mpfr_mul_ui(my_number.value, my_number.value, 17, MPFR_RNDN)
return my_number
returns 85.000000000000000000000000000000000000 as it should.
I would like to modify the plot code of a plot attribute in a derived class
class Foo(Bar):
def plot(self, **options):
super(Foo, self).plot(options)
This does not seem to work. What is the right way to pass the options?
What is the right way to pickle a cython extension class? Consider the example
cdef class Stuff:
def __init__(self):
pass
then
a = Stuff()
a == loads(dumps(a))
gives the result False because the address of the new object generated by loads is different from the original object a.?
|
https://ask.sagemath.org/users/429/hartmut-monien/?sort=recent
|
CC-MAIN-2021-39
|
refinedweb
| 204
| 68.47
|
I.
Using these in my build is currently rather awkward. Up to now,
I've had explicit calls to Antlr to build each grammar file. The
file gets done whether or not it's changed recently, which slows the
whole build down. What I'd like is a way to automatically figure out
where the grammar files are to build, and build them if necessary.
I keep the grammar files in directories like src/parser1/Catalog.g,
src/parser2/Catalog.g and I want to generate them to gen/parser1,
gen/parser2. That way I can keep the generated
gen directory out of source control (as it should
be). Some directories have a regular grammar file (always called
Catalog.g) only, others also have a tree walker grammar (called
CatalogWalker.g) if I do tree building and walking.
src/parser1/Catalog.g,
src/parser2/Catalog.g
gen/parser1,
gen/parser2
gen
It may be possible to get ant to do this, but my ant is rusty and
frankly I'm happy to keep it that way. My usual build process these
days is to use Rake, but it has an issue here - calling Antlr
multiple times would lead to multiple JVM invocations which can be
slow due to the start-up time of the JVM. After toying with some
alternatives I thought that it would be worth giving JRuby a spin.
Ruby makes it easy to find and select out the directories that
match my naming conventions
Dir['src/parser*'].
select{|f| f =~ %r[src/parser\d+]}.
collect{|f| Antlr.new(f)}.
each {|g| g.run}
The regular expressions used for File globs (as in
src/parser* isn't quite enough for my naming
convention, so I have to filter the results with a more precise
regexp. Once I have my real directories I create a command object to
process them.
src/parser*
As I was working on this, I decided that I wanted to be able to
run the script both with regular ruby (calling Antlr via the command
line) and JRuby (calling the Antlr command facade directly). That
way I could run the script on machines that didn't have JRuby
installed. Doing so is pretty easy, I just have to keep the JRuby
bits isolated.
The Antlr class does all the figuring out of what
needs to be done and delegates to an internal engine to actually
call Antlr in the two different styles. I initialize the object with
the directory to process, and it figures out the right target
directory and whether it needs to generate a walker.
Antlr
class Antlr...
def initialize dir
@dir = dir
@grammarFile = File.join @dir, 'Catalog.g'
raise "No Grammar file in #{dir}" unless File.exists? @grammarFile
walker_name = File.join @dir, 'CatalogWalker.g'
@walker = File.exists?(walker_name) ? walker_name : nil
@dest = @dir.sub %r[src/], 'gen/'
end
When I run the object it checks to see if it needs to run before
invoking the engine.
class Antlr...
def run
return if current?
puts "%s => %s " % [@grammarFile, @dest]
mkdir_p @dest
run_tool
self
end
def current?
return false unless File.exists? @dest
output = File.join(@dest,'CatalogParser.java')
sources = [@grammarFile]
sources << @walker if @walker
return uptodate?(output, sources)
end
The run_tool method takes the data out of fields and
puts it onto command line arguments for Antlr (I'll call the facade
with a string array of arguments too.)
run_tool
class Antlr...
def run_tool
args = []
args << '-o' << @dest
args << "-lib" << @dest if @walker
args << @grammarFile
args << @walker if @walker
@@engine.run_tool args
end
For the engine I have two implementations. The simplest just
makes a command line call.
class AntlrCommandLine
def run_tool args
classpath = Dir['lib/*.jar'].join(File::PATH_SEPARATOR)
system "java -cp #{classpath} org.antlr.Tool #{args.join ' '}"
end
end
The JRuby version is a bit more involved as it has to import the
Antlr facade file and sort out classpaths.
class AntlrJruby
def initialize
require 'java'
Dir['lib/*.jar'].each{|j| require j}
include_class 'org.antlr.Tool'
end
def run_tool args
Tool.new(args.to_java(:string)).process
end
end
With all the time I've spent tearing my hair out with classpaths
I just love the fact that I can just require a jar at runtime
here. Especially since the code Dir['lib/*.jar'].each{|j|
require j} loads all the jars in a directory - which is
something that java makes horribly hard.
Dir['lib/*.jar'].each{|j|
require j}
The last trick is ensuring that the right engine is used for the
job. I do this with some inline code inside the Antlr command
class.
class Antlr...
tool_class = (RUBY_PLATFORM =~ /java/) ? AntlrJruby : AntlrCommandLine
@@engine = tool_class.new
Pretty simple and sweet that it runs in regular ruby or JRuby.
But there's a punch line and joke's on me. I set all this up to
use JRuby because I was afraid that the start up time of the JVMs
would make running it from C ruby too slow. But the the C ruby
actually does a clean build faster than the JRuby version. Maybe
this will change once I get more grammar files to build, but for the
moment it looks like I've fallen victim to premature
optimization. (And it's not worthwhile for me to figure out why,
both builds are fast enough for now.)
|
http://martinfowler.com/bliki/FlexibleAntlrGeneration.html
|
crawl-001
|
refinedweb
| 885
| 66.64
|
- Advertisement
Content Count20
Joined
Last visited
Community Reputation702 Good
About axel1994
- RankMember
Personal Information
- Website
I made a working alternative Finally block for C++ exceptions. Opinions welcomed.
axel1994 replied to redshock's topic in General and Gameplay ProgrammingYou don't seem to know how finally works: See the Java code below. Your code would not execute the finally. However in Java it will execute the finally. Finally is always called in Java unless you: Call system.exit() Another thread interrupts this one The JVM crashes Ofcourse a C++ finally needs to mirror this. public class Main { public static void main(String args[]) { something(); } public static int something() { int success = 1; int failure = -1; try { exceptionthrower(); return success; } catch (Exception e) { return failure; } finally { System.out.println("Will always be printed"); } System.out.println("Wil never be printed"); } public static void exceptionthrower() throws Exception { throw new Exception(); } }
Computer Science vs Software Engineering
axel1994 replied to JayNori's topic in Games Career DevelopmentThis is not the point of this discussion. Whatever way you look at it. Having a degree is an advantage. It's not necessary but it's an advantage.
Where do I go next?
axel1994 replied to Bigfatmeany's topic in For Beginners's ForumSorry, I wasn't meaning to refer to it as a language, I was simply meaning that I could do it using the library, however I was trying to say that I was unsure about starting to learn and do those things in other languages, such as c#. Anyone can say that they can do something. But there is a big difference between thinking you can do it and actually doing it. I might actually believe I can do something. But that doesn't mean anything. It doesn't give the experience you get from actually doing it.
Pure Java or LWJGL?
axel1994 replied to Vlad Muresan's topic in For Beginners's ForumDidn't see the date
Have you made a game engine
axel1994 replied to Nathan2222_old's topic in For Beginners's ForumMay I ask what feature this is? (that doesn't exist enywhere else)
Math?
axel1994 replied to asdfghjkl1's topic in For Beginners's Forumthis depends on where you start from. If you start from scratch, you'll need more math, than when you are going to use an engine. Aren't most engine programmers and such (in the actual industry) engineers and computer scientists?
OpenGL Drawing texture problem
axel1994 replied to axel1994's topic in Graphics and GPU ProgrammingOw, damn Thank you so much. Can't believe I spend 2 days looking for that. Now It works perfectly. I now found that the order of texture coordinates should be 0,1,2,3. Now the image shows amazing. It works great along with the camera
OpenGL Drawing texture problem
axel1994 posted a topic in Graphics and GPU Programming Loading the texture I use:; loading everything into opengl I use the code: . [attachment=19229:img_cheryl.jpg] [attachment=19230:tex.png]
What should I start with ?
axel1994 replied to Nathan2222_old's topic in For Beginners's ForumOpengl is cross platform so It'll work on every system. (the available version is different, windows can use the highest version) DirectX is the other choice, is windows specific. It's mostly a matter of taste
- Nobody said that it's impossible. It's just not practical. The art, the programming, it's too much. Sure, you can make a great game in 3 years. But it won' t be the equivalent of an AAA game. (maybe an AAA game from a decade ago, but we are considering AAA games from today, not gta 3 or Doom (which I would consider AAA)) Implying otherwise is egoistical. (sort of) Why? Because that would imply that that person could do the exact same amount of work in the same time as hunderds of people from a big company. So you think, sure I'll just work for 10-15 years. You'll need amazing motivation (and money, since where are you going to get money to eat?) to do that and finish the project. But the work done today is old news in 15 years time. AAA isn't better than indie. Games don't need to be like that to be good. The reason why I started this discussion is that having unrealistic expectations isn't good. I think many people (everyone?) have a dream game, which would require it to be AAA. But most people know that it's that, a dream. (something that could happen, but probably not) Your original post made it look like you could expect to be someday possible to make an AAA game on your own. Which is just not true (if it is, there would be many people who already did it)
- You do know that COD and assasin creed are AAA games created by studios (hunderds of very experienced people)? Beginners already often have a surreal look on games. Your post makes it look like it's easy (or even doable) for 1 person to achieve something like this. I'm not saying indies can't make great games, nor that extremely talented people couldn't create something close to AAA. I'm just saying, you should stay realistic. Next, there is no best language. C++ is a choice, not THE only choice (ofcource if you want in the business, then you should know it) As a beginner you shouldn't really look at what is the fastest. Being able to take advantage of the actual speed, already takes an experienced programmer. Do note: I'm not saying you're wrong in any way. I'm prefer C++ myself.
OpenGL Opengl Linux
axel1994 replied to axel1994's topic in Graphics and GPU ProgrammingThanks for all the responses I'm using debian weezy. And yes, I tried to install manually. (so bad) Somehow I messed up my whole system. Everything was broken, I could barely login (even through recovery mode) I had to reinstall the system. I'm searching around the web how I could install the drivers. But each time I try something, x won't run.
OpenGL Opengl Linux
axel1994 posted a topic in Graphics and GPU Programming.
- You should have a file on your pc named Magamar.java In that file should be the code you wrote in the first post. Then in the command line you go to the folder that holds the file Magamar.java Then you type: javac Magamar.java (this will generate a Magamar.class file) Then you type: java Magamar
- The file name needs to be Magamar.java
- Advertisement
|
https://www.gamedev.net/profile/212093-theaxe/
|
CC-MAIN-2019-47
|
refinedweb
| 1,107
| 66.13
|
37566/multi-threading-program-in-python
Could you share an example of a multithreading program?
import threading
import os
def task1():
print("Task 1 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 1: {}".format(os.getpid()))
def task2():
print("Task 2 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 2: {}".format(os.getpid()))
if __name__ == "__main__":
# print ID of current process
print("ID of process running main program: {}".format(os.getpid()))
# print name of main thread
print("Main thread name: {}".format(threading.main_thread().name))
# creating threads
t1 = threading.Thread(target=task1, name='t1')
t2 = threading.Thread(target=task2, name='t2')
# starting threads
t1.start()
t2.start()
# wait until all threads finish
t1.join()
t2.join()
The GIL does not prevent threading. All ...READ MORE
Thread is the smallest unit of processing that ...READ MORE
lets say we have a list
mylist = ..
Try the below code
inputString = input("Enter a ...READ MORE
Here's the logic. You have to add ...READ MORE
OR
Already have an account? Sign in.
|
https://www.edureka.co/community/37566/multi-threading-program-in-python
|
CC-MAIN-2021-10
|
refinedweb
| 178
| 63.66
|
Answered by:
Create Word Documents By C#
Hello,
I would like to create a Word doc directly from C# Windows Form codes.
1) How to create and open the Word doc?
After creating the Word doc and Open it, ...
2) How to insert a text from a textbox to the Word doc that is already currently opened?
3) How to check the current Range.Selection location?
Please exlpain in full as I am a newbe in C# to create Word...
Thanks in advance.
Question
Answers
-
All replies
-
Hi,
Thank you very much, but I managed somehow and I have the answer to your question, because I had the same problem. (but I never give up :P)
SO, here is the code that inserts data from a textbox from my C# project into a Word document:
namespaceturism
{public partial class Form1 : Form
{private Microsoft.Office.Interop.Word.ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();//here I am declaring WordApp as a Word application
formIntrodNume f = new formIntrodNume(); //this is the form that has a textbox on it and where Iam introducing a string, and you have to declare the new instance here to be seen globally
public Form1()
{
InitializeComponent();
}
private void toolStripButton1_Click(object sender, EventArgs e) //this is the event that will open the form and I will have to introduce the string
{
if (f.ShowDialog(this) == DialogResult.OK)
{
this.Text = "Agentia de turism " + f.txtIntrodNume.Text;
this.Invalidate();
}
}private void voucherToolStripMenuItem_Click(object sender, EventArgs e) //and this is the event that will produce me what I want to do
{if (this.openFileDialog1.ShowDialog() == DialogResult.OK) // I am opening the file where I want to insert the string from my form
{//here I keep in variable filename the filename of my document I've just opened object filename = openFileDialog1.FileName; object savefile = filename + ".doc"; object readOnly = false; //these are some variables that you will need object isVisible = true; object isfalse = false; object istrue = true; object isdynamic = 2; object missing = System.Reflection.Missing.Value; //here I make visible the Word application
WordApp.Visible = true;
WordApp.Activate(); // and I activate it to use it
//I am opening the document I want to write in it, see the ref readOnly as a parametre here , it is declared false above
Microsoft.Office.Interop.Word.Document my_doc = WordApp.Documents.Open(ref filename,ref missing, ref readOnly, ref missing, ref missing, ref missing,ref missing,ref missing,ref missing,ref missing, ref missing, ref isVisible,ref missing,ref missing,ref missing,ref missing); object start = 0;// start and end are 2 objects that will help you to define the space where you are going to fill you string object end = 0; Range range = my_doc.Range(ref missing, ref missing); // and here I am declaring my range
start = 55; // now I am calculating the position of start and end(this means that you have to count every character and space in your document till the spot you want)
end = 70;my_doc.Range(ref start, ref end).Text = f.txtIntrodNume.Text; // and this is how I am filling the string in my document
}
This is how the beginning of my document looks like:
and after Agentia de turism (which means Tourism Agency I am filling that string)
VOUCHER Nr.
Agenţia de turism
I hope this was usefull to you
Regards,
Based on what you need to do this can be simple or complex, however, you DEFINITELY you need to start with VSTO first and foremost. There is no need at reinventing the wheel here.
Take a look at this:
Download the Visual Studio plugin for Visual Studio Tools for Office and get going there. There are tons of demos, web casts, samples, etc for you to review.
The nice thing about VSTO is you are writing managed code for Word, Excel or whatever. And you are doing it in C# which is awesome.
I hope this gets you going in the right direction.
-The Elder
Why would you not be able to use VSTO? It is a free download that plugs into Visual Studio.
The bottom line is either you use VSTO or you have to use the interop libraries and go the long route of learning the word apis. Refer to the post above with the links on where to get started going that route then.
-The Elder
There is a free solution to create exce, word,pdf document without ole automation.
Hi friends,
I have one question regarding this, I create the new word document file and copy the contents as per the needs.
1) I want to save the document with the name extension like Document.doc -(into)-> Documentfigures.doc
2) The new document (Documentfigures.doc) need to be saved in a same folder.
Any idea regarding this?
//This is to use your created word template.
Object oTemplatePath = "(path to your template file)"; //path should be like "D:\\NewFolder1\\NewFolder2\\txtFile.docx" oDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
//For saving the file with your extension name use some thing like this
object oDestLoc = "D:\\NewFolder1\\NewFolder2\\" +Documentfigures+ ".docx";
oDoc.SaveAs(ref oDestLoc, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
--Refer this for more;en-us;316384&spid=2530&sid=47
|
https://social.msdn.microsoft.com/Forums/vstudio/en-US/5b82c0b5-ecaf-40f2-a68a-c7c17c85414f/create-word-documents-by-c?forum=csharpgeneral
|
CC-MAIN-2016-30
|
refinedweb
| 894
| 62.27
|
2012-05-13T06:26:42Z
The Flask Mega-Tutorial, Part III: Web Forms (this article)
- defined a simple template for the home page and used fake objects as placeholders for things we don't have yet, like users or blog posts.
In this article we are going to fill one of those many holes we still have in our app, we will be looking at how to work with web forms.
Web forms are one of the most basic building blocks in any web application. We will be using forms to allow users to write blog posts, and also for logging in to the application.
To follow this chapter along you need to have the
microblog app as we left it at the end of the previous chapter. Please make sure the app is installed and running.. Here is what we will start with (file
config.py):
WTF_CSRF_ENABLED = True SECRET_KEY = 'you-will-never-guess'
Pretty simple, it's just two settings that our Flask-WTF extension needs. The
WTF_CSRF_ENABLED setting activates the cross-site request forgery prevention (note that this setting is enabled by default in current versions of Flask-WTF). In most cases you want to have this option enabled as it makes your app more secure.
The
SECRET_KEY setting is only needed when CSRF. We can do this right after the Flask app object is created, as follows (file
app/__init__.py):
from flask import Flask app = Flask(__name__) app.config.from_object('config') from app import views
The user login form
Web forms are represented in Flask-WTF as classes, subclassed from base class
Form. A form subclass simply defines the fields of the form as class variables.
Now we will create a login form that users will use to identify with the system. The login mechanism that we will support in our app is not the standard username/password type, we will have our users login using their OpenID. OpenIDs have the benefit that the authentication is done by the provider of the OpenID, so we don't have to validate passwords, which makes our site more secure to our users.
The OpenID login only requires one string, the so called OpenID. We will also throw a 'remember me' checkbox in the form, so that users can choose to have a cookie installed in their browsers that remembers their login when they come back.
Let's write our first form (file
app/forms.py):)
I believe the class is pretty much self-explanatory. We imported the
Form class, and the two form field classes that we need,
StringField and
BooleanField.
The
DataRequired import is a validator, a function that can be attached to a field to perform validation on the data submitted by the user. The
DataRequired validator simply checks that the field is not submitted empty. There are many more validators included with Flask-WTF, we will use some more in the future.
Form templates
We will also need a template that contains the HTML that produces the form. The good news is that the
LoginForm class that we just created knows how to render form fields as HTML, so we just need to concentrate on the layout. Here is our login template (file
app/templates/login.html):
<!-- %}
Note that in this template we are reusing the
base.html template through the
extends template inheritance statement. We will actually do this with all our templates, to ensure a consistent layout across all pages.
There are a few interesting differences between a regular HTML form and our template. This template expects a form object instantiated from the form class we just defined stored in a template argument named
form. We will take care of sending this template argument to the template next, when we write the view function that renders this template.
The
form.hidden_tag() template argument will get replaced with a hidden field that implements the CSRF prevention that we enabled in the configuration. This field needs to be in all your forms if you have CSRF enabled. The good news is that Flask-WTF handles it for us, we just need to make sure it is included in the form.
The actual fields of our form are rendered by the field objects, we just need to refer to a
{{form.field_name}} template argument in the place where each field should be inserted. Some fields can take arguments. In our case, we are asking the text field to generate our
openid field with a width of 80 characters.
Since we have not defined the submit button in the form class we have to define it as a regular field. The submit field does not carry any data so it doesn't need to be defined in the form class.
Form views
The final step before we can see our form is to code a view function that renders the template.
This is actually quite simple since we just need to pass a form object to the template. Here is our new view function (file
app/views.py):, instantiated an object from it, and sent it down to the template. This is all that is required to get form fields rendered.
Let's ignore for now the
flash and
redirect imports. We'll use them a bit later.
The only other thing that is new here is the
methods argument in the route decorator. This tells Flask that this view function accepts GET and POST requests. Without this the view will only accept GET requests. We will want to receive the POST requests, these are the ones that will bring in the form data entered by the user.
At this point you can try the app and see the form in your web browser. After you start the application you will want to open in your web browser, as this is the route we have associated with the login view function.
We have not coded the part that accepts data yet, so pressing the submit button will not have any effect at this time.
Receiving form data
Another area where Flask-WTF makes our job really easy is in the handling of the submitted form data. Here is an updated version of our login view function that validates and stores the form data (file
app/views.py):
@app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): flash('Login requested for OpenID="%s", remember_me=%s' % (form.openid.data, str(form.remember_me.data))) return redirect('/index') return render_template('login.html', title='Sign In', form=form)
The
validate_on_submit method does all the form processing work. If you call it when the form is being presented to the user (i.e. before the user got a chance to enter data on it) then it will return
False, so in that case you know that you have to render the template..
If at least one field fails validation then the function will return
False and that will cause the form to be rendered back to the user, and this will give the user a chance to correct any mistakes. We will see later how to show an error message when validation fails.
When
validate_on_submit returns True our login view function calls two new functions, imported from Flask. The
flash function is a quick way to show a message on the next page presented to the user. In this case we will use it for debugging, since we don't have all the infrastructure necessary to log in users yet, we will instead just display a message that shows the submitted data. The
flash function is also extremely useful on production servers to provide feedback to the user regarding an action.
The flashed messages will not appear automatically in our page, our templates need to display the messages in a way that works for the site layout. We will add these messages to the base template, so that all our templates inherit this functionality. This is the updated base template (file
app/templates/base.html):
>
The technique to display the flashed message is hopefully self-explanatory. One interesting property of flash messages is that once they are requested through the
get_flashed_messages function they are removed from the message list, so these messages appear in the first page requested by the user after the
flash function is called, and then they disappear.
The other new function we used in our login view is
redirect. This function tells the client web browser to navigate to a different page instead of the one requested. In our view function we use it to redirect to the index page we developed in previous chapters. Note that flashed messages will display even if a view function ends in a redirect.
This is a great time to start the app and test how the form works. Make sure you try submitting the form with the openid field empty, to see how the
DataRequired validator halts the submission process.
Improving field validation
With the app in its current state, forms that are submitted with invalid data will not be accepted. Instead, the form will be presented back to the user to correct. This is exactly what we want..
Here is our login template with field validation messages (file
app/templates/login.html):
<!-- %}
The only change we've made is to add a for loop that renders any messages added by the validators below the
openid field. As a general rule, any fields that have validators attached will have errors added under
form.field_name.errors. In our case we use
form.openid.errors. We display these messages in a red style to call the user's attention.
Dealing with OpenIDs
In practice, we will find that a lot of people don't even know that they already have a few OpenIDs. It isn't that well known that a number of major service providers on the Internet support OpenID authentication for their members. For example, if you have an account with Google, you have an OpenID with them. Likewise with Yahoo, AOL, Flickr and many other providers. (Update: Google is shutting down their OpenID service on April 15 2015).
To make it easier for users to login to our site with one of these commonly available OpenIDs, we will add links to a short list of them, so that the user does not have to type the OpenID by hand.
We will start by defining the list of OpenID providers that we want to present. We can do this in our config file (file
config.py):
WTF_CSRF_ENABLED = True SECRET_KEY = 'you-will-never-guess' OPENID_PROVIDERS = [ {'name': 'Google', 'url': ''}, {'name': 'Yahoo', 'url': ''}, {'name': 'AOL', 'url': '<username>'}, {'name': 'Flickr', 'url': '<username>'}, {'name': 'MyOpenID', 'url': ''}]'])
Here we grab the configuration by looking it up in
app.config with its key. The array is then added to the
render_template call as a template argument.
As I'm sure you guessed, we have one more step to be done with this. We now need to specify how we would like to render these provider links in our login template (file
app/templates/login.html):
<!-- %}
The template got somewhat long with this change. Some OpenIDs include the user's username, so for those we have to have a bit of javascript magic that prompts the user for the username and then composes the OpenID with it. When the user clicks on an OpenID provider link and (optionally) enters the username, the OpenID for that provider is inserted in the text field.
Below is a screenshot of our login screen after clicking the Google OpenID link:
Final Words
While we have made a lot of progress with our login form, we haven't actually done anything to login users into our system, all we've done so far had to do with the GUI aspects of the login process. This is because before we can do real logins we need to have a database where we can record our users.
In the next chapter we will get our database up and running, and shortly after we will complete our login system, so stay tuned for the follow up articles.
The
microblog application in its current state is available for download here:
Download microblog-0.3.zip.
Remember that the Flask virtual environment is not included in the zip file. For instructions on how to set it up see the first chapter of the series.
Feel free to leave comments or questions below. I hope to see you in the next chapter.
Miguel
#1 Alexander Manenko said 2012-05-14T07:32:28Z
Good job! I'm waiting for next articles. Is there any resources about Flask best practices? How to organize structure of the application with reusable sub-applications (blueprints?), etc.? Is there any open source Flask-based applications with good style?
#2 Miguel Grinberg said 2012-05-14T15:23:58Z
Thanks! The best resource for app structure in Flask that I've found is this:. The structure that I use is based on this, but a bit simpler, I don't use blueprints.
#3 drew said 2012-09-11T04:28:13Z
a small thing, i think microblog-03.zip - run.py is missing "#!/usr/bin/env python". I can't thank you enough for this tutorial.
#4 Miguel Grinberg said 2012-09-11T05:25:49Z
@drew: Yes, looks like I missed the shebang line on several of the zip files. They should all be fixed now. Thanks!
#5 Catherine said 2012-10-26T21:22:56Z
Hi, I'm working my way through the tutorial and can't get the first form to work, this is the error : Traceback (most recent call last): File "run.py", line 12, in <module> from app import app File "/Users/catherine_penfold/Sites/brownie/microblog/app/__init__.py", line 24, in <module> from app import views File "/Users/catherine_penfold/Sites/brownie/microblog/app/views.py", line 14, in <module> from forms import LoginForm File "/Users/catherine_penfold/Sites/brownie/microblog/app/forms.py", line 1, in <module> from flask.ext.wtf import Form, TextField, BooleanField File "/Library/Python/2.7/site-packages/flask/exthook.py", line 86, in load_module raise ImportError('No module named %s' % fullname) ImportError: No module named flask.ext.wtf any suggestions? Thanks Catherine PS the time travel film was awesome!
#6 Catherine said 2012-10-26T21:29:08Z
Is this comment box working?
#7 Miguel Grinberg said 2012-10-26T21:33:29Z
Hi Catherine, yes, the comments work, but I have to approve each comment before it is published. You won't believe the amount of spam I get on my little blog. Anyway, the problem seems to be that you don't have the WTForms extension installed, or it isn't accessible to the Python interpreter that you are using. Go back to the first article and review the virtual environment setup, the Python interpreter that you should be using (if you followed my installation method) is the one that is created as part of the virtual environment setup.
#8 Catherine Penfold said 2012-10-26T22:00:56Z
Hi, Yes I have followed all your instructions from the start. Any other suggestions?
#9 Miguel Grinberg said 2012-10-26T22:21:02Z
Did you check if you have WTForms installed in your virtual environment? If you followed my instructions you should have it in /Users/catherine_penfold/Sites/brownie/microblog/flask/site-packages. You should also be running your script via the virtual environment's python interpreter, which should be at /Users/catherine_penfold/Sites/brownie/microblog/flask/bin/python. You can achieve this by adding a shebang line to your run.py script that reads #!flask/bin/python. I hope this helps!
#10 Catherine Penfold said 2012-10-29T03:57:22Z
OK, I'll take it from the top tomorrow and let you know how it goes. Thanks
#11 Catherine Penfold said 2012-10-29T18:08:35Z
Hi Miguel, so taking it from the top there is no directory /Users/catherine_penfold/Sites/brownie/microblog/flask/site-packages ??? and I am still getting the same error: ImportError: No module named flask.ext.wtf run.py does have the #!flask/bin/python as the first line of the script. Do you know what is going wrong? Thanks, Catherine
#12 Miguel Grinberg said 2012-10-29T18:15:54Z
If you are using Windows, then go back to the first article and read the section on starting Python scripts on that OS. The method is different. See my reply to you on that article as well.
#13 Catherine said 2012-10-29T18:21:01Z
I tried moving the site-packages folder to the flask directory to give the path above and still does not work ...???
#14 Catherine Penfold said 2012-10-31T16:36:36Z
Hurray! Hey, so I worked it out, I cam back to your scripts this morning and did ./run.py and got the same error as before, i.e. ImportError: No module named flask.ext.wtf but then I did . flask/bin/activate and now everything is working fine. So between each terminal session the local installation must need activating. Will this conflict with having the site up later on? Thanks Catherine
#15 Miguel Grinberg said 2012-10-31T17:14:15Z
Catherine, glad that you figured it out, but the fact that by doing 'activate' works suggests that you were running the regular Python interpreter all this time, not the interpreter that was created for the virtual environment. The activate command just sets your path so that the Python inside the virtual environment becomes the default for your system. Instead of activating, you can achieve the same thing by having a shebang line in the run.py script that reads '#!flask/bin/python', as I indicate in the first article. Alternatively you can also run the script as follows: 'flask/bin/python run.py' (without the quotes of course). Do these options work as well? In the end it does not matter really, just keep in mind that the activate makes the Python interpreter in the virtual environment the default, so any other unrelated Python scripts that you run will go through that one as well.
#16 Leon Talbot said 2012-11-01T14:30:56Z
@Catherine : flask/bin/python run.py
#17 lovesh said 2012-11-06T14:36:34Z
well i had to change the route decorators from @app.route('/index') to @app.route('/index/') and @app.route('/login', methods = ['GET','POST']) to @app.route('/login/', methods = ['GET', 'POST']) (add a trailing slash) for them to work
#18 Miguel Grinberg said 2012-11-07T07:36:21Z
@lovesh: are you sure? Even the official Flask 0.9 tutorial has routes that don't end in a slash. I'm constantly running this application on Flask 0.9 and never had any issues.
#19 lovesh said 2012-11-07T15:28:28Z
@Miguel Grinberg whenever i go to in my browser it automatically redirects to which gives a 404 so i had to add a trailing slash to the routing rule. I got this from the quickstart section of the flask documentation where it talks about routing
#20 Miguel Grinberg said 2012-11-08T06:05:52Z
@lovesh, when you say "redirect", do you mean an HTTP redirect? Is Flask sending a redirect? Because I don't see that here, if I ask for that is exactly what the application gets, without any redirects. You should try to figure out where is this redirect to the version of the route that ends in a slash comes from. I don't think adding a trailing slash is a big deal, but aesthetically it doesn't look great, the URLs look better without a trailing slash (in my opinion).
#21 lovesh said 2012-11-08T08:56:33Z
Well i was mistaken. Its not a redirect. My browsers(Firefox and Chrome) both add a trailing slash to the urls so if i dont use the trailing slash in my route in views.py i get 404s.
#22 Miguel Grinberg said 2012-11-09T05:35:35Z
I haven't found a single mention of this behavior. I do not get slashes added, could this be caused by some configuration, or maybe an extension that you use?
#23 ricka said 2012-11-10T05:18:18Z
I have been following along in this series of posts and really appreciate everything here. Of note: I was running an older version of python (2.6.1) and was getting an error that had to do with a bug in that version of python (see). Python 2.6.5 should fix it, but I went ahead and upgraded to 2.7.3 and everything is running fine. Your first notes say 2.6 should work, but it should probably be 2.6.5 or greater.
#24 jimscafe said 2012-11-23T12:22:09Z
I don't see how form.errors.open_id gets populated when the user presses submit with an empty field.
#25 Miguel Grinberg said 2012-11-25T06:26:08Z
@jimscafe: could it be because the field is name 'openid' instead of 'open_id'? Try form.errors.openid, I just verified validation on this field is working fine.
|
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms
|
CC-MAIN-2016-07
|
refinedweb
| 3,524
| 72.97
|
and display of the components on the resulting page, as well object manages the page page was submitted back to server), the tree is restored with the appropriate state. If this is the initial rendering, the component tree is created and the lifecycle jumps to the Render Response phase.
Apply Request Values: Each component in the tree extracts new values from the request parameters (using its decode method) and stores the values locally. Most associated events are queued for later processing. If a component has its
immediate attribute set to
true, then the validation, the conversion, and the events associated with the component are processed during this phase. For more information, see Section 4.2, "Using the Immediate Attribute."
Process Validations: Local values of components are converted from the input type to the underlying data type. If the converter fails, this phase continues to completion (all remaining converters, validators, and required checks are run), but at completion, the lifecycle jumps to the Render Response phase.
If there are no failures, the
required attribute on the component is checked. If the value is
true, and the associated field contains a value, then any associated validators are run. If the value is
true and there is no field value, this phase completes (all remaining validators are executed), but the lifecycle jumps to the Render Response phase. If the value is
false, the phase completes, unless no value is entered, in which case no validation is run. For more information about conversion and validation, see Chapter the Process Validations phase is as follows:
If a converter fails, the required check and validators are not run.
If the converter succeeds but the required check fails, the validators are not run.
If the converter and required check succeed, all validators are run. Even if one validator fails, the rest of the validators are run. This is because when the user fixes the error, you want to give them as much feedback as possible about what is wrong with the data entered.
For example suppose you have a
dateTimeRange validator that accepted dates only in the year 2010, and you had a
dateRestrictionValidator validator that did not allow the user to pick Sundays. If the user entered
July 5, 2009 (a Sunday), you want to give the feedback that this fails both validators to maximize the chance the user will enter valid data.
Update Model Values: The component's validated local values are moved to the model, and the local copies are discarded.
Invoke Application: Application-level logic (such as event handlers) is executed.
Render Response: The components in the tree are rendered. State information is saved for subsequent requests and for the Restore View phase.
To help illustrate the lifecycle, consider a page that has a simple input text component where a user can enter a date and then click a 18 4-2 shows the code used for the two fields and two buttons.
Example 4-2 Input Component and Command Components Using Immediate
<af:form> <af:inputText <af:commandButton [.... tags to render search result ....] <af:inputText <af:convertDateTime </af:inputText> <af not available to the model until after the Update Model Values phase. If you have an immediate
actionSource component, and that component needs data, then set
immediate on the
editableValueHolder fields as well. Then, you can call the
getValue method on the
editableValueHolder component and the local value will be returned. It will not have been pushed into the model yet, but it will be available on the component.
If an immediate
editableValueHolder component fails validation, any immediate
actionSource component will still execute..
Also assume that you want the user to be able to select a radio button before entering the required text into the field. While you could set the radio button components to automatically trigger a submit action and also set their
immediate attribute to
true so that they are processed before the
inputText component, you would also have to add a
valueChangeEvent listener, and in it
<af:form> <af:inputText <af:selectBooleanRadio <af:selectBooleanRadio <af:panelGroupLayout <af:outputText </af:panelGroupLayout> </af:form>
Because the
autoSubmit attribute is set to
true on the radio buttons, when they are selected, a
SelectionEvent is fired, for which the radio button is considered the root. Because the
panelGroupLayout component is set to be a target to both radio components, when that event is fired, only the
selectOneRadio (the root), the
panelGroupLayout component (the root's target), and its child component (the
outputText component) are processed through the lifecycle. Because the
outputText component is configured to render only when the Show radio button is selected, the user is able to select that radio button and see the output text, without having to enter text into the required input field above the radio buttons. component), the target (the
panelGroupLayout component), and the target's child (the
inputText component). Validation will fail because the
inputText component is marked as required and there is no value, so an error will be thrown. Because of the error, the lifecycle will skip to the Render Response phase and the model the user clicks the search icon, the
inputText component will be validated because the lifecycle runs on both the root (the
inputListOfValues component) and the target (the
inputText component). Validation will fail because the
inputText component is marked as required and there is no value, is called. This is similar to server-side validation in that when validation fails on the server, the lifecycle jumps to the Render Response phase; the action event, though queued, will never be delivered; and the
actionListener handler method will never be called.
For example, ADF Faces provides the
required attribute for input components, and this validation runs on the client. When you set this attribute to
true, the framework will show an error on the page if the value of the component is
null, without requiring a trip to the server. Example </af:form>
When this page is run, if you clear the field of the value of the
inputText component and tab out of the field, the field will redisplay with a red outline. If you then click into the field, an error message will state that a value is required, as shown in Figure:Always use only a single
formtag per page. Use the
subformtag where you might otherwise be tempted to use multiple
formtags.
A subform will always allow the Apply Request Values phase to execute for its child components, even when the page was submitted by a component outside of the subform. However, the Process Validations and Update Model Values phases will be skipped (this differs from an ordinary form component, which, when not submitted, cannot run the Apply Request Values phase). To allow components in subforms to be processed through the Process Validations and Update Model Value phases when a component outside the subform causes a submit action, use the
default attribute. When a subform's
default attribute is set to
true, it acts like any other subform in most respects, but if no subform on the page has an appropriate event come from its child components, then any subform with
default set
to
true will behave as if one of its child components caused the submit. For more information about subforms, see Section 9.2, "Defining Forms."
At runtime, you pass data to pages by storing the needed data in an object scope where the page can access it. The scope determines the lifespan of an object. Once you place an object in a scope, it can be accessed from the scope using an EL expression. For example, you might create a managed bean named
foo, and define the bean to live in the Request scope. To access that bean, you would use the expression
#{requestScope.foo}.
There are three types of scopes in a standard JSF application:
application
Scope: The object is available for the duration of the application.
session
Scope: The object is available for the duration of the session.
request
Scope: The object is available for the duration between the time an HTTP request is sent until a response is sent back to the client.
In addition to the standard JSF scopes, ADF Faces provides the following scopes:
pageFlow
Scope: The object is available as long as the user continues navigating from one page to another. If the user opens a new browser window and begins navigating, that series of windows will have.
Note:Because these are not standard JSF scopes, EL expressions must explicitly include the scope to reference the bean. For example, to reference the
MyBeanmanaged bean from the
pageFlowScopescope, your expression would be
#{pageFlowScope.MyBean}.
Object scopes are analogous to global and local variable scopes in programming languages. The wider the scope, the higher the availability of an object. During their lifespan, these objects may expose certain interfaces, hold information, or pass variables and parameters to other objects. For example, a managed bean defined in
sessionScope scope will be available for use during multiple page requests. However, a managed bean defined in
requestScope scope will be available only for the duration of one page request.
Figure 4-11 shows the time period in which each type of scope is valid, and its relationship with the page flow.
When determining what scope to register a managed bean with or to store a value in, always try to use the narrowest scope possible. Use the
sessionScope scope only for information that is relevant to the whole session, such as user or context information. Avoid using the
sessionScope scope to pass values from one page to another.
Note information about passing values between pages in an ADF bounded task flow, or between ADF regions and pages, refer to the "Getting Started With ADF Task Flows" chapter of the Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework..
Like objects stored in any standard JSF scope, objects stored in the
pageFlow scope can be accessed through EL expressions. The only difference with the
pageFlow scope is that the object names must use the
pageFlow
Scope prefix. For example, to have a button's label provided by a managed bean stored in the
pageFlow scope, and to have a method on the bean called when the button is selected, you might use the following code on your page:
<af:commandButton
The
pageFlowScope is a
java.util.Map object that may be accessed from Java code. The
setPropertyListener tag allows you to set property values onto a scope, and also allows you to define the event the tag should listen for. For example, when you use the
setPropertyListener tag with the
type attribute set to
action, it provides a declarative way to cause an action source (for example,
commandButton) to set a value before navigation. You can use the
pageFlowScope scope with the
setPropertyListener tag to pass values from one page to another, without writing any Java code in a backing bean. For example, you might have one page that uses the
setPropertyListener tag and a command component to set a value in the
pageFlowScope scope, and another page whose text components use the
pageFlowScope scope to retrieve their values.
You can also use the
pageFlowScope scope to set values between secondary windows such as dialogs. When you launch secondary windows from, for example, a
commandButton component, you can use a
launchEvent event and the
pageFlowScope scope to pass values into and out of the secondary windows without overriding values in the parent process.
You can access
pageFlow scope from within any Java code in your application. Remember to clear the scope once you are finished.
Note:If your application uses ADF Controller, then you do not have to manually clear the scope.
To use pageFlowScope in Java code:
To get a reference to the
pageFlowScope scope, use the
org.apache.myfaces.trinidad.context.RequestContext. method.
getPageFlowScope()
For example, to retrieve an object from the
pageFlowScope scope, you might use the following Java code:
import java.util.Map; import org.apache.myfaces.trinidad.context.RequestContext; . . . Map pageFlowScope = RequestContext.getCurrentInstance().getPageFlowScope(); Object myObject = pageFlowScope.get("myObjectName");
To clear the
pageFlowScope scope, access it and then manually clear it.
For example, you might use the following Java code to clear the scope:
RequestContext afContext = RequestContext.getCurrentInstance(); afContext.getPageFlowScope().clear();
To use the
pageFlowScope scope without writing Java code, use a
setPropertyListener tag in conjunction with a command component to set a value in the scope. The
setPropertyListener tag uses the
type attribute that defines the event type it should listen for. It ignores all events that do not match its type. Once set, you then can access that value from another page within the page flow.
Tip:Instead of using the
setActionListen, to display the value.
Set the value of the component to be the same value as the
To value set on the
setPropertyListener tag.
For example, to have an
outputText component access the employee name, you would set the value of that component to be
#{pageFlowScope.empName}.
When a user clicks a command button that contains a
setPropertyListener tag, the listener executes and the
To value is resolved and retrieved, and then stored as a property on the
pageFlowScope scope. On any subsequent pages that access that property through an EL expression, the expression is resolved to the value set by the original page.
|
http://docs.oracle.com/cd/E25178_01/web.1111/b31973/af_lifecycle.htm
|
CC-MAIN-2014-35
|
refinedweb
| 2,230
| 50.06
|
Help on Hashcode
dhwani mathur
Ranch Hand
Joined: May 08, 2007
Posts: 621
posted
Jul 30, 2007 23:47:00
0
Hi! all
I have read some topics relevant to Hashcode but still
i am not getting the basic idea behind the method
Hashcode,i know it returns an integer value....but
still if anyone could explain me it will be realy
kinda of you....
1)What is Hashcode?
2)What is the use of HashCode?actualy can say why we
use hashcode in our program?
Thanks in Advance
Preparing
SCJP
1.5
Maurizio Nagni
Ranch Hand
Joined: May 29, 2004
Posts: 75
posted
Jul 31, 2007 03:14:00
0
Hashcode is a technique used to improve the search or an object (and obviously unce you have found you can modify or delete or just verify if it exist).
As you already understood the basic idea is that each object could be identified from a unique integer.
Lets make it easy.
You hava a collection of Dog class instances with three properties:
String
name;
String owner;
String color;
You already (must) know that to compare one object with another you can override the
equals(Object a)
method.
So for the Dog you could define that
dogFirst.equals(dogSecond) == TRUE
If they have the same name and the same owner, right?
Now suppose that you have a smart function (ok..ok... it is our hash function) that generate a different number for each two unique pair (name, owner).
In this case doing
dogFirst.hashcode == dogSecond.hashcode
should give the same result than the equal method.
Thats the basic idea. After this the things could became complex (the hashfunction is not so easy to write); but the basic idea is this:
you have a very complicated object but if you can hash it you can uniquely identifying in the middle of thousand of (same kind) of objects and you can easily create an index of int without looking everytime inside its properties.
ciao
Maurizio
dhwani mathur
Ranch Hand
Joined: May 08, 2007
Posts: 621
posted
Aug 01, 2007 02:42:00
0
Thanks a lot for such a great explanation Maurizio Nagni
,now i am clear with hashcode,but still
have some doubt if you could help me?
As you said it is used to compare objects,since each object
is now identified with a particular integer,in case of
wrapper classes value of equals method is TRUE bcoz
equals method is overriden in wrapper class....but
what if i try to compare objects of user class say A
it will return false since i have to override the equals method..
but
why it is said that if we want to override equals method
we have to write hashcode method for it?
what i think is we have to write hashcode so as
to assign integer value to objects isnt it?
but what the use of this integer value in equals method
as it returns boolean value
if you can explain it will be realy helpful....
Thanks in advance............
Preparing SCJP 1.5
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1710
posted
Aug 01, 2007 03:49:00
0
[dhwani mathur]
why it is said that if we want to override equals method
we have to write hashcode method for it?
The use of hashCode is to improve the performance in placing and retrieving
objects from the collection. It is ok to override equals(Object o) method for
your class so that you could compare two objects whether they are meaningfully
equal or not.
What if you use object of your class as a key to Map. Storing or retrieving
the object from the Map is two step process. We imagine the use of hashCode
as determining which bucket to place the object in. Your hashCode tells
that. As the unique distribution of hashCode is, as much efficient and
fast your search process will be. Before an object corresponding to the key
is stored in the map, hashCode is computed to find the bucket to place the
object in.
Let us talk about retrieving the object from the bucket given the key that
is object of your class. Again hashCode is computed, and bucket is found,
now the role of equals() method start comparing whether the object that is
in the bucket is the one that you are looking for. If not search fails.
If there are more than one object in the map, (that is the case when more
than one object's hashCode are same therefore they had been assigned the same bucket), now equals() starts the comparison in sequential order (not
known, it may apply any other method also, not of our concern).
You think, even if there is no unique distribution of the hashCode to the
objects, our search is limited to the given bucket instead of going through
all the objects in the Map and applying equals() method to compare two
objects.
hashCode is there to improve performance. If you don't override the
hashCode() method for the class, the objects you are using as key to the
Map, the default implementation of the hashCode works.
Let's see the scenario:
import java.util.HashMap; public class Employee{ private String name; public Employee(String name) { this.name =name; } public boolean equals(Object o) { return ((o instanceof Employee) && ((Employee)o).name.equals(name)); } public static void main(String... args) { Employee emp1 = new Employee("Amit"); Employee emp2 = new Employee("Amit"); HashMap<Employee,Integer> hm = new HashMap<Employee,Integer>(); hm.put(emp1,10); System.out.println(hm.get(emp1)); //10 System.out.println(hm.get(emp2)); //null // Line #1 } }
Line #1:
Why the second get() method returned null, we see both
object emp1 and emp2 are meaningfully equal because they are having same "Amit", then what heck went wrong in retrieval of object from the Map using
another same object reference emp2.
Reason :
That is because Map is using hashCode() version of Object
class. You may try this:
System.out.println((emp1.hashCode());
System.out.println(emp2.hashCode());
You will see the hashCodes for both are different. So the search process
fails at first round, before our equals() method could work. That is why
it is said you override the hashCode also.
After you override the hashCode, you should see that emp1.hashCode() and
emp2.hashCode() return the same value. It should be like that, I mean
equals() and hashCode() contract.
public int hashCode() { return name.length(); //an example what hashCode could be or like //some other computation. }
Thanks,
cmbhatt
Maurizio Nagni
Ranch Hand
Joined: May 29, 2004
Posts: 75
posted
Aug 01, 2007 05:47:00
0
it is always a pleasure when people took so much of their time to help the others. thanks Chandra
dhwani mathur
Ranch Hand
Joined: May 08, 2007
Posts: 621
posted
Aug 03, 2007 03:25:00
0
Hi!!Chandra
Superb !!!Explanation
I am now clear with the concept.
Thanks a lot for helping me soo much.
vin Hari
Ranch Hand
Joined: Nov 16, 2006
Posts: 161
posted
Sep 25, 2007 02:51:00
0
Hi chandra,
I saw your answers it was very good explanation my problem is also something related to this iam creating menu driven program for some keys iam getting there values for some it is null even i tried to write overriding equals and hashcode it did not work have a patience and check this code and please reply me
public class JALMenu{ public JMenuBar createMenuBar() { //Where the GUI is created: JMenuBar menuBar; JMenu menu, submenu; JMenu menu1,submenu1; JMenuItem menuItem; //create the menu bar. menuBar = new JMenuBar(); //Build the menu. menu = new JMenu("Toolchest"); menu.setVisible(true); _names = _menudata.keys(); //_na=_menudata11.keys(); //Collection col1=_submenu11.values(); Collection col=_menudata11.keySet(); Collection col1=_submenu11.keySet(); Iterator it=col1.iterator(); int size=_submenu11.size(); String FinalString=""; Object[] Keyval=_submenu11.entrySet().toArray(); Object[] Keyval2=_menudata11.entrySet().toArray(); int count=0; for(int i=0;i<size;i++) { Map.Entry ent=(Map.Entry)Keyval[i]; Map.Entry ent2=(Map.Entry)Keyval2[i]; //System.out.println("menukeys="+menukey+"menuvalue="+menuval); //final String Path=(String)ent2.getValue(); boolean flag=false; String Path1=""; String Path=""; System.out.println("pathvalue="+Path); String val1=""; String ht=""; String keyv1=""; String key=(String) ent.getKey(); String keyv=(String) ent2.getKey(); //flag=_submenu11.containsKey(key); String val=(String) ent.getValue(); Path1=(String) ent2.getValue(); System.out.println("Path1="+keyv); if(i!=size-1) { Map.Entry ent1=(Map.Entry)Keyval[i+1]; Map.Entry ent3=(Map.Entry)Keyval2[i+1]; val1=(String) ent1.getValue(); Path=(String)ent3.getValue(); keyv1=(String) ent3.getKey(); System.out.println("pppp="+Path); ht=(String)ent1.getKey(); } if(_submenu11.containsKey(key)) { if(key.equals(ht)){System.out.println("hai1");} else{ String sarr[]={}; String sarr1[]={}; Collection values =(Collection) _submenu11.get(key); String values1=values.toString(); char dd=values1.charAt(0); //values1.remove(dd); int pos=values1.lastIndexOf("]"); System.out.println("chatAt(0)"+dd+"pos="+pos); values1=values1.substring(0); values1=values1.substring(1,pos); menuItem=new JMenuItem(key, KeyEvent.VK_T); submenu=new JMenu(key); Pattern t=Pattern.compile("[,]"); // return ((values != null) && (values.size() != 0)); System.out.println("flag=="+flag+"size="+values.size()+"values"+ values1); for(int j=0;j<values1.length();j++){ sarr=t.split(values1); //System.out.println("contents"+sarr[0]+sarr.length); } for(int k=0;k<sarr.length;k++) { System.out.println("new values"+sarr[k]); menuItem=new JMenuItem(sarr[k], KeyEvent.VK_T); submenu.add(menuItem); //String getPath1(String); menuItem.addActionListener(new ActionListener( ) { //Get information from the action event public void actionPerformed(ActionEvent ae) { str_clicked = ae.getActionCommand(); if (ae.getActionCommand() != null) { try { str_clicked = ae.getActionCommand(); //path_exec = (String)_submenu1.get(str_clicked); path_exec=getPPath(str_clicked); System.out.println("str_clicked"+str_clicked+"path"+path_exec); JALThread currthread = new JALThread(path_exec); currthread.start(); } catch (Exception e) { //System.out.println("error in execution"); } } } }); } menu.add(submenu); }}} }
This class does not contain any main method because iam calling from other class.please help me.
It is sorta covered in the
JavaRanch Style Guide
.
subject: Help on Hashcode
Similar Threads
How to print reference of String Object ?
hashCode algorithm for integers
hashCode() doubt
hashCode..
Question about hashcode()
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton
|
http://www.coderanch.com/t/264188/java-programmer-SCJP/certification/Hashcode
|
CC-MAIN-2015-40
|
refinedweb
| 1,705
| 58.38
|
Sliders have become an essential part of nearly all the websites we browse through. Generally, they make the webpage appealing to the audience. Today, we’ll learn to build a small 3d slider in ReactJs using the
react-slick library. Documentation can be found here. It is easy to use, and we can create a very attractive slider in only a few minutes.
We use the below command to make a new react application:
npx create-react-app mySlider
Next, we’ll do the necessary cleanup in our application, which includes removing the
logo.svg and tests file from the
src folder.
Next, we need to install some dependencies to use the slick library. We’ll also install react icons, which we’ll use for the next/previous icons in our slider. We’ll run the following command in the terminal to install the packages:
npm i react-icons react-slick slick-carousel
or
yarn add react-icons react-slick slick-carousel
Let’s open the
App.js file and remove all the code in the header element because we’ll be writing our own code. For this application, we create an
assets folder in the
src folder, where we keep a few images to be used in the slider.
First, we’ll import the Slider component ( from ‘react-slick’) and our images from the
assets folder in
App.js, as shown below:
import Slider from "react-slick"; import pic1 from "./assets/Consulting-rafiki.png"; import pic2 from "./assets/Creative writing-rafiki.png"; import pic3 from "./assets/Football Goal-rafiki.png"; import pic4 from "./assets/Researchers-rafiki.png"; import pic5 from "./assets/User research-rafiki.png";
Also, import the previous and next arrows from react-icons library:
import { FaArrowRight, FaArrowLeft } from "react-icons/fa";
Next, we’ll store the images in an array to make it easy to map through them and display on screen:
const images = [pic1, pic2, pic3, pic4, pic5];
We’ll open the
Slider component and map through the images one by one using the
map method inside the return statement of
App.js, as shown below:
<div className="App"> <h1>React 3D Slider</h1> <Slider> {images.map((img, idx) => ( <div> <img src={img} alt={idx} /> </div> ))} </Slider> </div>
The
slick library requires us to initialize the
settings object, where we define some rules for our slider. We define the
settings object below and explain the values:
const settings = { infinite:true, //to allow the slides to show infinitely lazyLoad: true, speed: 300, //this is the speed of slider in ms slidesToShow:3, //number of slides to show up on screen centerMode: true, centerPadding: 0, nextArrow: <NextArrow />, //imported from 'react-icons' prevArrow: <PrevArrow />, //imported from 'react-icons' };
Now, in order to iterate through the images one by one we will create an image index and set it to zero initially:
const [imgIndex,setImgIndex] = useState(0)
and in the settings object we will setImgIndex to iterate on next slide:
beforeChange: (current, next) => setImgIndex(next),
We’ll also set the class, ‘active’, to an image if its index is same as the
imageIndex so that it pops up a little on the screen and perform a 3d effect:
return ( <div className="App"> <h1>React 3D Slider</h1> <Slider {...settings}> {images.map((img, idx) => ( <div className={idx === imgIndex ? "slide activeSlide" : "slide"}> <img src={img} alt={idx} /> </div> ))} </Slider> </div> );
Also, we need to define two methods, one for the previous arrow and one for the next arrow, to which we’ll specify the
onClick prop and give the class of
next and
prev for the slides to be shown.
const NextArrow = ({onClick}) => { return ( <div className="arrow next" onClick={onClick}> <FaArrowRight /> </div> ) } const PrevArrow = ({onClick}) => { return ( <div className="arrow prev" onClick={onClick}> <FaArrowLeft /> </div> ) }
In the
App.css file, we define the styles for the images in each slide and active slides to look bigger than the others. We do not include the
stylesheet here, because we want to keep the article simple. However, click here to view the complete code.
RELATED TAGS
CONTRIBUTOR
View all Courses
|
https://www.educative.io/answers/how-to-make-a-3d-carousel-using-react-slick
|
CC-MAIN-2022-33
|
refinedweb
| 675
| 58.82
|
Kayak Dirt Bike Motorcycle Price
US $700.0-790.0 / Piece
5 Pieces (Min. Order)
Newest 250CC Motorcycle GM250GY-13
US $700.0-790.0 / Piece
5 Pieces (Min. Order)
motocicletas kayak JD200GY-2
48 Units (Min. Order)
High quality motorcycle with pedals
US $1-9.9 / Pair
10 Pairs (Min. Order)
high quality kayak motorcycles 125cc in china
US $5.40 / Piece
100 Pieces (Min. Order)
Quality Precision CNC milling machine Aluminum/stainless ste...
US $3.0-3.0 / Pieces
50 Pieces (Min. Order)
Snowboard Kayak Carrier Boat Canoe Surf Ski Board Roof Top Mo...
US $20-50 / Piece
10 Pieces (Min. Order)
China motorcycle 50cc moped pedals
US $1-19.9 / Pair
10 Pairs (Min. Order)
import kayak motorcycles manufacturers in china
US $5.40 / Piece
100 Pieces (Min. Order)
Wall Mount Surfboard Kayak Rack Canoe Folding Ladder Heavy Du...
US $20-60 / Piece
10 Pieces (Min. Order)
New style motorcycle fishing kayak with pedals
US $1-9.9 / Pair
10 Pairs (Min. Order)
Universal Roof J-Bar Rack Kayak Boat Canoe Car SUV Top Mount ...
US $18-19 / Set
1000 Sets (Min. Order)
3.68 mtrs cheap price kayak motorcycles 125cc
US $101-105 / Piece
5 Pieces (Min. Order)
Wholesale China motorcycle cycle pedals
US $1-19.9 / Pair
10 Pairs (Min. Order)
OEM professional wholesale TC f1 short sleeve Motorcycle Raci...
US $5.5-20 / Piece
500 Pieces (Min. Order)
activated carbon carbon fibre wholesale cloth fabric for car...
US $5.5-20 / Meter
100 Meters (Min. Order)
HC Glove kayak motorcycles
US $1-4 / Pair
|
http://www.alibaba.com/showroom/kayak-motorcycles.html
|
CC-MAIN-2016-26
|
refinedweb
| 260
| 72.53
|
I'm happy to introduce a VMOD that collects metrics and stats from Varnish into a JSON file and presents it through a user interface. If you want to know how Varnish is doing and how your backends are working in real-time, then this is the VMOD for you. The neat thing is that this VMOD gives you an overview on some Varnish counters with particular attention to backends' metrics and stats per backend. This is great if you're using Varnish as load balancer because it allows you to know what kind of transactions are happening and how Varnish is performing in real-time. Checking your backends can prevent possible annoying situations and help you to understand how Varnish works.
The VMOD with examples and documentation can be found here:
The VMOD has two functions:
- rtstatus(REAL delta): this is the function responsible for collecting stats from Varnish and generating the JSON object. The param delta is used for hitrate and the request load calculations, they are evaluated on a differential basis.
- html(): this function is fed with the JSON object generated from the previous one and provide a nice UI.
Let me spend a couple of words on this function. This is c-wrapper around an HTML/Javascript application, basically this application is presented to Varnish as a big string, that will be used to generate a synthetic object. The UI provided by the VMOD is the default one, but this string is absolutely tunable: the JSON object gives you a lot of raw stats and these can be used to evaluate some other numbers and metrics. This is absolutely up to you. You wish to see the number of KB exchange between Varnish and the backend after every lock operation in your user interface? You can do that it.
In order to use the VMOD you have to write something like this in your VCL:
import rtstatus; sub vcl_recv { if (req.url ~ "/rtstatus.json") { return(synth(700, "OK")); } if (req.url ~ "/rtstatus") { return(synth(800, "OK")); } } sub vcl_synth { if (resp.status == 700){ set resp.status = 200; set resp.http.Content-Type = "text/plain; charset=utf-8"; synthetic(rtstatus.rtstatus(5)); return (deliver); } if (resp.status == 800) { set resp.status = 200; set resp.http.Content-Type = "text/html; charset=utf-8"; synthetic(rtstatus.html()); return (deliver); } }
|
https://info.varnish-software.com/blog/libvmod-rtstatus-realtime-stats-and-counters-varnish
|
CC-MAIN-2019-39
|
refinedweb
| 389
| 57.06
|
10,946,954 members (79,154 online)
Forgot your password?
articles
Chapters and Sections
>
Search
Latest Articles
Latest Tips/Tricks
Top Articles
Beginner Articles
Technical Blogs
Posting/Update Guidelines
Article Help Forum
Article Competition
Submit an article or tip
Post your Blog
quick answers
Ask a Question
View Unanswered Questions
View All Questions...
C# questions
ASP.NET questions
VB.NET questions
Javascript questions
SQL
Competitions
News
The Insider Newsletter
The Daily Build Newsletter
Newsletter archive
Surveys
Product Showcase
Research Library
CodeProject Stuff
community
Search within:
Articles
Quick Answers
Messages
Member's Profile
Messages posted
Articles submitted
Blog Feeds
Technical Blog Articles
Recommendations
Membership FAQ
Articles by Christian Graus (Articles: 48)
Articles: 48
Articles
Technical Blogs
Tips
Reference Articles
Average article rating: 4.32
Dialogs and Windows
Screensavers
Christian and James' Code Project Screensaver
Posted: 17 Apr 2002 Updated:
16 May 2002
Views: 317,079 Rating: 3.81/5 Votes: 36 Popularity: 5.86
Licence: Not specified
Bookmarked: 61
Downloaded: 671
Our attempt at a screen saver with a Code Project theme, written in C#.
Static & Panel Controls
General
CCheckStatic
Posted: 12 Mar 2001 Updated:
12 Mar 2001
Views: 89,082 Rating: 4.78/5 Votes: 32 Popularity: 7.19
Licence: Not specified
Bookmarked: 27
Downloaded: 1,621
A Static derived class which provides a check box to enable/disable items inside it
Toolbars & Docking windows
Toolbars
CGSToolBar
Posted: 20 Feb 2001 Updated:
20 Feb 2001
Views: 98,634 Rating: 3.29/5 Votes: 21 Popularity: 4.28
Licence: Not specified
Bookmarked: 26
Downloaded: 2,377
A flexible extension to the CToolBar class
Palm and WebOS
General
Your first Palm app - covering GUI components, alerts and forms.
Posted: 4 Nov 2002 Updated:
5 Nov 2002
Views: 113,165 Rating: 4.47/5 Votes: 11 Popularity: 4.63
Licence: The Code Project Open License (CPOL)
Bookmarked: 27
Downloaded: 102
Building on previous articles, we develop a simple application and discuss some of the components available for Palm GUI.
Palm databases - how to persist data on a Palm hand held
Posted: 6 Nov 2002 Updated:
6 Nov 2002
Views: 106,243 Rating: 4.43/5 Votes: 14 Popularity: 5.05
Licence: The Code Project Open License (CPOL)
Bookmarked: 30
Downloaded: 65
Continuing our series of articles, we discuss how to create databases, and create, modify and delete records
An introduction to the Palm platform
Posted: 7 Nov 2002 Updated:
7 Nov 2002
Views: 105,499: 8,821 Rating: 4.73/5 Votes: 7 Popularity: 3.69
Licence: The Code Project Open License (CPOL)
Bookmarked: 16
Downloaded: 148
Just a quick explanation of why it's not always a good idea to use DISTINCT
SQL Wizardry Part One - Joins
Posted: 21 Dec 2013 Updated:
23 Jan 2014
Views: 32,415 Rating: 4.85/5 Votes: 41 Popularity: 7.82
Licence: The Code Project Open License (CPOL)
Bookmarked: 67
Downloaded: 517
The first in a series of articles seeking to explain the intermediate to advanced features of T-SQL
SQL Wizardry Part 2 - Select, beyond the basics
Posted: 24 Dec 2013 Updated:
12 Mar 2014
Views: 12,766 Rating: 4.83/5 Votes: 16 Popularity: 5.81
Licence: The Code Project Open License (CPOL)
Bookmarked: 36
Downloaded: 255
The second in my series digs in to some of the different things you can do within a select statement.
SQL
Thinking in SQL - Working with dates
Posted: 12 Mar 2014 Updated:
14 Mar 2014
Views: 13,024 Rating: 4.48/5 Votes: 15 Popularity: 5.36
Licence: The Code Project Open License (CPOL)
Bookmarked: 35
Downloaded: 217
In this installment, I talk about working with dates and date functions in SQL Server
SQL Server
SQL Wizardry Part Four - passing lists of data to SQL Server
Posted: 3 Jan 2014 Updated:
12 Jan 2014
Views: 10,918 Rating: 4.63/5 Votes: 15 Popularity: 5.43
Licence: The Code Project Open License (CPOL)
Bookmarked: 30
Downloaded: 213
In which we talk of ways to pass an arbitrary list of values to SQL Server
SQL Wizardry Part Three - Common Table Expressions (CTEs)
Posted: 26 Dec 2013 Updated:
12 Jan 2014
Views: 8,912 Rating: 4.98/5 Votes: 15 Popularity: 5.85
Licence: The Code Project Open License (CPOL)
Bookmarked: 42
Downloaded: 186
In this third installment, we look at how Common Table Expressions can simplify your SQL and help you perform complex tasks
SQL Wizardry Part Six - Windowing Functions
Posted: 12 Jan 2014 Updated:
13 Jan 2014
Views: 7,249 Rating: 4.92/5 Votes: 8 Popularity: 4.52
Licence: The Code Project Open License (CPOL)
Bookmarked: 22
Downloaded: 139
A discussion of windowing functions, from sum to row_number(), to the new functions in SS2012
SQL Wizardry Part Seven - PIVOT and arbitrary lists of data
Posted: 16 Jan 2014 Updated:
16 Jan 2014
Views: 6,487 Rating: 5.00/5 Votes: 10 Popularity: 5.00
Licence: The Code Project Open License (CPOL)
Bookmarked: 25
Downloaded: 126
Discussion on pivot and other ways to turn columns of data in to rows in SQL Server
SQL Wizardry Part Eight - Tally Tables
Posted: 19 Jan 2014 Updated:
21 Jan 2014
Views: 7,848 Rating: 4.91/5 Votes: 9 Popularity: 4.65
Licence: The Code Project Open License (CPOL)
Bookmarked: 15
Downloaded: 123
A description of the best way to create tally tables, and how to use them
Thinking in SQL - Generating Random Numbers
Posted: 23 Jan 2014 Updated:
23 Jan 2014
Views: 7,160 Rating: 4.00/5 Votes: 1 Popularity: 0.00
Licence: The Code Project Open License (CPOL)
Bookmarked: 10
Downloaded: 108
A discussion of ways to create random number sequences in SQL Server
Thinking in SQL - Distribution Functions in SS 2012
Posted: 24 Mar 2014 Updated:
24 Mar 2014
Views: 4,213 Rating: 3.67/5 Votes: 3 Popularity: 1.67
Licence: The Code Project Open License (CPOL)
Bookmarked: 6
Downloaded: 44
Covering how to use the new Distribution functions in SQL Server 2012
Utilities
MSDEGUI - a GUI tool to help developers use the MSDE database
Posted: 18 Nov 2002 Updated:
27 Nov 2002
Views: 309,435 Rating: 4.81/5 Votes: 48 Popularity: 8.08
Licence: Not specified
Bookmarked: 127
Downloaded: 7,476
This tool uses ADO.NET to offer browsing of databases and tables, editing values and an SQL window to test queries.
Audio and Video
Video
A wrapper for the canon CDSDK and PRSDK for remote capture
Posted: 26 Jan 2007 Updated:
18 May 2007
Views: 421,328 Rating: 5.00/5 Votes: 29 Popularity: 7.31
Licence: Not specified
Bookmarked: 82
Downloaded: 3,203
A wrapper to allow remote capture of images with Canon cameras in C#
DirectX
Games
Grausteroids - an Asteroids game using DirectX and C++
Posted: 7 Apr 2002 Updated:
7 Apr 2002
Views: 173,702 Rating: 4.95/5 Votes: 30 Popularity: 7.30
Licence: Not specified
Bookmarked: 37
Downloaded: 3,612
An Asteroid's clone which needs some work but will illustrate some points about writing games.
General
Problems in the AudioVideoPlayback namespace of managed DirectX9
Posted: 13 Sep 2004 Updated:
13 Sep 2004
Views: 188,006 Rating: 4.67/5 Votes: 38 Popularity: 7.38
Licence: The Code Project Open License (CPOL)
Bookmarked: 39
Downloaded: 1,587
A guided tour of the many reasons NOT to use DirectX9 for your audio/video playback needs
GDI+
General
GDI+ Brushes and Matrices
Posted: 12 May 2001 Updated:
30 May 2001
Views: 271,115 Rating: 3.82/5 Votes: 36 Popularity: 5.91
Licence: Not specified
Bookmarked: 40
Downloaded: 1,271
Using GDI+ to draw solid/gradient filled and textured shapes
Doodle - a basic paint package in GDI+
Posted: 3 Jun 2001 Updated:
3 Jun 2001
Views: 311,731 Rating: 3.86/5 Votes: 37 Popularity: 6.02
Licence: Not specified
Bookmarked: 65
Downloaded: 1,899
Using GDI+ to create a paint program with soft brushes and loading/saving images.
GDI+ RoundedRect
Posted: 15 Feb 2002 Updated:
15 Feb 2002
Views: 79,736 Rating: 3.29/5 Votes: 18 Popularity: 4.06
Licence: Not specified
Bookmarked: 32
Downloaded: 935
Providing a RoundedRect function for GDI+
Image Processing for Dummies with C# and GDI+ Part 1 - Per Pixel Filters
Posted: 20 Mar 2002 Updated:
20 Mar 2002
Views: 1,149,350 Rating: 4.94/5 Votes: 227 Popularity: 11.64
Licence: Not specified
Bookmarked: 544
Downloaded: 15,079
The first in a series of articles which will build an image processing library in C# and GDI+
Image Processing for Dummies with C# and GDI+ Part 3 - Edge Detection Filters
Posted: 31 Mar 2002 Updated:
31 Mar 2002
Views: 454,334 Rating: 4.91/5 Votes: 77 Popularity: 9.29
Licence: The Code Project Open License (CPOL)
Bookmarked: 230
Downloaded: 10,242
The third in a series of articles which will build an image processing library in C# and GDI+
Image Processing for Dummies with C# and GDI+ Part 4 - Bilinear Filters and Resizing
Posted: 14 Apr 2002 Updated:
14 Apr 2002
Views: 397,094 Rating: 4.68/5 Votes: 62 Popularity: 8.38
Licence: The Code Project Open License (CPOL)
Bookmarked: 173
Downloaded: 4,142
The fourth installment covers how to write a filter that resizes an image, and uses bilinear filtering
Image Processing for Dummies with C# and GDI+ Part 5 - Displacement filters, including swirl
Posted: 23 Dec 2002 Updated:
25 Dec 2002
Views: 598,747 Rating: 4.89/5 Votes: 138 Popularity: 10.47
Licence: Not specified
Bookmarked: 273
Downloaded: 6,683
In the fifth installment, we build a framework for generating filters that work by changing a pixel's location, rather than colour.
Starting with GDI+
Posted: 12 May 2001 Updated:
12 Mar 2003
Views: 1,101,470 Rating: 4.78/5 Votes: 115 Popularity: 9.85
Licence: Not specified
Bookmarked: 206
Downloaded: 6,046
Getting started with the new Microsoft Graphics Libraries
Image Processing for Dummies with C# and GDI+ Part 6 - The HSL color space
Posted: 22 May 2004 Updated:
28 Jun 2004
Views: 293,515 Rating: 4.84/5 Votes: 54 Popularity: 8.39
Licence: The Code Project Open License (CPOL)
Bookmarked: 193
Downloaded: 5,229
A discussion of the HSL color space, including code for a color picker and image filters
Image Processing for Dummies with C# and GDI+ Part 2 - Convolution Filters
Posted: 23 Mar 2002 Updated:
7 Nov 2005
Views: 994,124 Rating: 4.91/5 Votes: 145 Popularity: 10.61
Licence: The Code Project Open License (CPOL)
Bookmarked: 310
Downloaded: 9,766
The second in a series of articles which will build an image processing library in C# and GDI+.
C / C++ Language
General
Koenig Lookup - a C++ primer
Posted: 15 Dec 2002 Updated:
15 Dec 2002
Views: 132,565 Rating: 4.35/5 Votes: 37 Popularity: 6.80
Licence: Not specified
Bookmarked: 25
Downloaded: 0
A discussion of Koenig namespace lookup, for those with VS.NET 2003
C#
Samples
Bottleneck - a tool for finding code bottlenecks in C#
Posted: 14 May 2002 Updated:
14 May 2002
Views: 71,450 Rating: 2.96/5 Votes: 16 Popularity: 3.47
Licence: Not specified
Bookmarked: 29
Downloaded: 1,288: 22,720 Rating: 4.38/5 Votes: 9 Popularity: 4.06
Licence: The Code Project Open License (CPOL)
Bookmarked: 44
Downloaded: 232
A .NET wrapper for Authorize
STL
Beginners
STL 101 Part A - Vector
Posted: 20 Feb 2002 Updated:
20 Feb 2002
Views: 207,675 Rating: 3.26/5 Votes: 44 Popularity: 5.37
Licence: Not specified
Bookmarked: 36
Downloaded: 6
The first in a series of articles on STL, this one covers vector and some common algorithms
STL101 Part B - List and Iterators
Posted: 24 Feb 2002 Updated:
24 Feb 2002
Views: 153,783: 148,597 Rating: 4.69/5 Votes: 35 Popularity: 7.25
Licence: Not specified
Bookmarked: 32
Downloaded: 1,611
Coverage of two more containers from the STL, namely set and map, and the functions provided for them.
STL101 Part C - Functors
Posted: 24 Feb 2002 Updated:
1 Apr 2002
Views: 161,347: 225,177 Rating: 4.64/5 Votes: 40 Popularity: 7.42
Licence: Not specified
Bookmarked: 39
Downloaded: 1,167
A typesafe alternative to sprintf from the std library
IOStream Inserters And Extractors
Posted: 16 Apr 2002 Updated:
16 Apr 2002
Views: 64,841 Rating: 3.43/5 Votes: 18 Popularity: 4.24
Licence: Not specified
Bookmarked: 22
Downloaded: 891
Showing how to extend iostreams in order to stream custom types
iostream modifiers
Posted: 14 Jul 2002 Updated:
14 Jul 2002
Views: 93,562 Rating: 4.31/5 Votes: 18 Popularity: 5.38
Licence: Not specified
Bookmarked: 21
Downloaded: 363
An exploration of extending the iostreams framework through stream modifiers
Deriving your own stream from the iostreams framework
Posted: 24 Jul 2002 Updated:
24 Jul 2002
Views: 75,486 Rating: 3.75/5 Votes: 19 Popularity: 4.75
Licence: Not specified
Bookmarked: 19
Downloaded: 889
An exploration of extending the iostreams framework through custom streams.
Windows Presentation Foundation
General
WPF Tutorial - Part 2 : Writing a custom animation class
Posted: 12 Apr 2007 Updated:
12 Apr 2007
Views: 132,745 Rating: 4.85/5 Votes: 51 Popularity: 8.28
Licence: The Code Project Open License (CPOL)
Bookmarked: 79
Downloaded: 4,462
This article covers how animations can be applied on properties that do not have an associated animation class
WPF Tutorial - Part 1 : Transformations
Posted: 21 Jul 2006 Updated:
28 Jun 2010
Views: 238,601 Rating: 4.39/5 Votes: 54 Popularity: 7.61
Licence: The Code Project Open License (CPOL)
Bookmarked: 122
Downloaded: 5,777
A brief introduction to using transformations with the WPF
Game Development
Games
Collision - A C# Game, part 3: pixel perfect collision detection
Posted: 16 Apr 2002 Updated:
16 Apr 2002
Views: 100,702 Rating: 4.42/5 Votes: 21 Popularity: 4.99
Licence: The Code Project Open License (CPOL)
Bookmarked: 37
Downloaded: 1,417
Finishing my attempt at a simple game in C#
Collision - A C# Game, part 1: parallax scrolling
Posted: 16 Apr 2002 Updated:
16 Apr 2002
Views: 93,723 Rating: 2.73/5 Votes: 8 Popularity: 2.47
Licence: Not specified
Bookmarked: 36
Downloaded: 939
In which I attempt to write a simple game in C#
Collision - A C# Game, part 2: tracking game elements and adding interaction
Posted: 16 Apr 2002 Updated:
16 Apr 2002
Views: 53,645 Rating: 2.78/5 Votes: 7 Popularity: 2.24
Licence: Not specified
Bookmarked: 33
Downloaded: 552
Continuing my attempt at a simple game in C#
Programming Tips
General
How to Use Google and Other Tips for Finding Programming Help
Posted: 8 Mar 2008 Updated:
8 Mar 2008
Views: 190,967 Rating: 4.69/5 Votes: 161 Popularity: 10.36
Licence: The Code Project Open License (CPOL)
Bookmarked: 128
Downloaded: 0
A primer for people looking to learn to help themselves find answers to programming questions
No blogs have been submitted.
No tips have been posted.
No reference articles
|
Mobile
Web04 | 2.8.141015.1 | Last Updated 20 Oct 2014
CodeProject
, 1999-2014
Layout:
fixed
|
fluid
|
http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=6556
|
CC-MAIN-2014-42
|
refinedweb
| 2,494
| 51.18
|
Beginning Haskell
An introduction to functional programming
Before you start
About this tutorial
This tutorial targets programmers of imperative languages wanting to learn about functional programming in the language Haskell.
In an introductory tutorial, many of Haskell's most powerful and complex features cannot be covered. In particular, the whole area of type classes and algebraic types (including abstract data types) is a bit much for a first introduction. For readers whose interest is piqued, I will mention that Haskell allows you to create your own data types, and to inherit properties of those data types in type instances. The Haskell type system contains the fundamental features of object-oriented programming (inheritance, polymorphism, encapsulation); but in a way that is almost impossible to grasp within a C++/Java/Smalltalk/Eiffel style of thinking.
The other significant element omitted in this tutorial is a discussion of monads, and therefore of I/O. It seems strange to write a tutorial that does not even start with a "Hello World!" program, but thinking in a functional style requires a number of shifts. While that "Hello World!" is quite simple, it also involves the mini "pseudo-imperative" world of monads. It would be easy for a beginner to be lulled by the pseudo-imperative style of I/O, and miss what is really going on. Swimming is best learned by getting in the water.
Prerequisites
This tutorial has no prerequisites. Programmers who have not used functional programming, or Haskell 98 in particular, will benefit most from this tutorial.
Haskell basics
About Haskell
Haskell is just one of a number of functional programming languages. Others include Lisp, Scheme, Erlang, Clean, Mercury, ML, OCaml, and others. The common adjunct languages SQL and XSL are also functional. Like functional languages, logical or constraint-based languages like Prolog are declarative. In contrast, both procedural and object-oriented languages are (broadly speaking) imperative. Some languages, such as Python, Scheme, Perl, and Ruby, cross these paradigm boundaries; but, for the most part, programming languages have a particular primary focus.
Among functional languages, Haskell is in many ways the most idealized language. Haskell is a pure functional language, which means it eschews all side effects (more later). Haskell has a non-strict or lazy evaluation model, and is strictly typed (but with types that allow ad hoc polymorphism). Other functional languages differ in each of these features -- for reasons important to their design philosophies -- but this collection of features brings one, arguably, farthest into the functional way of thinking about programs.
On a minor note, Haskell is syntactically easier to get a handle on than are the List-derived languages (especially for programmers who have used lightly punctuated languages like Python, TCL, and REXX). Most operators are infixed rather than prefixed. Indentation and module organization looks pretty familiar. And perhaps most strikingly, the extreme depth of nested parentheses (as seen in Lisp) is avoided.
Obtaining Haskell
Haskell has several implementations for multiple platforms. These include both an interpreted version called Hugs, and several Haskell compilers. The best starting place for all of these is Haskell.org. Links lead to various Haskell implementations. Depending on your operating system, and its packaging system, Haskell may have already been installed, or there may be a standard way to install a ready-to-run version. I recommend those taking this tutorial obtain Hugs for purposes of initial experimentation, and for working along with this tutorial, if you wish to do so.
Taking the vows
Giving things up
The most difficult part of starting to program with Haskell is giving up many of the most familiar techniques and ways of thinking within imperative programming. A first impression is often that it must simply be impossible to write a computer program if you cannot do X, Y, or Z, especially since X, Y, and Z are some of the most common patterns in "normal" imperative programming. In this section, let's review a few of the most "shocking" features of Haskell (and of functional programming in general).
No mutable variables
One of the most common programming habits in imperative programming is to assign a variable one value, then assign it a different value; perhaps along the way we test whether the variable has obtained certain key values. Constructs like the C examples below are ubiquitous (other imperative languages are similar):
if (myVar==37) {...} myVar += 2 for (myVar=0; myVar<37; myVar++) {...}
In Haskell, by contrast, variables of this sort do not exist at all. A name can be bound to a value, but once assigned, the name simply stands for that value throughout the program. Nothing is allowed to change.
In Haskell, "variables" are much like the variables in mathematical equations. They may need to satisfy certain rules, but they are not "counters" or "containers" in the style of imperative programming. Just to get headed in the right way of thinking, consider some linear equations like the ones below as an inspiration:
10x + 5y - 7z + 1 = 0 17x + 5y - 10z + 3 = 0 5x - 4y + 3z - 6 = 0
In this type of description, we have "unknowns," but the unknowns do not change their value while we are figuring them out.
Isolate side-effects
In Haskell, function computation cannot have side-effects within the program. Most of the side-effects in imperative programs are probably the sort of variable reassignment previously mentioned (whether global variables, or local, or dictionaries, lists, or other storage structures), but every I/O event is also a sort of side-effect. I/O changes the world rather than being part of a computation per se. Naturally, there are many times when what you want to do is change the world in some manner (if not, you cannot even know a program has run). Haskell circumscribes all such side-effects within a very narrow "box" called Monadic IO. Nothing in a monad can get out, and nothing outside a monad can get in.
Often, structured imperative programming approaches functional programming's goals of circumscribing I/O. Good design might require that input and output only happens in a limited set of appropriately named functions. Less structured programming tends to read and write to STDIO, files, graphic devices, etc., all over the place and in a way that is difficult to predict. Functional programming takes the circumscription to a much higher level.
No loops
Another interesting feature of Haskell is its lack of any loop construct. There is no
for and no
while. There is no
GOTO or
branch or
jmp or
break. One would almost think it impossible to control what a program does without such basic (imperative) constructs; but getting rid of these things is actually quite liberating.
The lack of loops is really the same as the matter of no side-effects. Since one pass through a loop cannot have variables with different values than another pass, there is nothing to distinguish them; and the need to branch is usually in order to do a different program activity. Since functional programming doesn't have activities, but only definitions, why bother branching.
However, I should try to stay honest about things. It actually proves possible to simulate almost all of the usual loop constructs, often using the same keywords as in other languages, and in a style that looks surprisingly similar to imperative constructs. Simon Thompson provides many examples of this in his book (see the Resources at the end of this tutorial).
No program order
Another thing Haskell lacks -- or does not need -- is program order. The set of definitions that make up a program can occur in any order whatsoever. This might seem strange when definitions look a great deal like assignments in imperative languages. For example, this might seem like a problem:
-- Program excerpt j = 1+i i = 5 -- Hugs session after loading above program -- Main> i -- 5 :: Integer -- Main> j -- 6 :: Integer
The thing to understand in a program like the one above is that
i and
j are not assigned values, but are rather defined in the manners given. In fact, even in the above,
i and
j are functions, and the examples above are of function definitions. In many imperative programming languages, you are also not allowed to define functions multiple times (at least in the same scope).
A new expressiveness
What's in a Haskell program?
A Haskell program consists, basically, of a set of function definitions. Functions are bound to names in a manner that looks very similar to variable assignment in other languages. However, it really is not the same thing; a Haskell bound name is much more similar to a binding in a mathematical proof, where we might say "Let tau refer to the equation . . .." A name binding just provides a shorthand for later use of an equation, but the name can only be bound a single time within a program -- trying to change it generates a program error.
myNum :: Int -- int myNum() { myNum = 12+13 -- return 12+13; } square :: Int -> Int -- int square(int n) { square n = n*n -- return = n*n; } double :: Int -> Int -- int double(int n) { double n = 2*n -- return 2*n; } dubSqr :: Int -> Int -- int dubSqr(int n) { dubSqr n = square (double n) -- return square(double(n)); }
Defining functions
There are (optionally) two parts to a function definition. The first part (conceptually, not necessarily within a listing) is the type signature of a function. In a function, the type signature defines all the types of the input, and the type of the output. Some analogous C definitions are given in the end-of-line comments in the example.
The second part of a function definition is the actual computation of the function. In this second part, often (but not always) some ad hoc variables are provided to the left of the equal sign that are involved in the computation to the right. Unlike variables in C, however -- and much like variables in mathematics -- the Haskell variables refer to the exact same "unknown quantity" on both sides of the equal sign (not to a "container" where a value is held).
example :: Int example = double (myNum - square (2+2)) dubSqr2 :: Int -> Int dubSqr2 = square . double -- Function composition
It is also often possible to bypass explicit naming of variables entirely in function definitions. In
dubSqr2, it is enough to say that we should
square whatever thing is
double'd. For this, there is no need to mention a variable name since the thing
dubSqr2'd is just whatever expression follows the bound name in later expressions. Of course,
double must itself take the same type of input
dubSqr2 expects, and in turn output the type of output
square needs as input.
More simple function definitions
Like C, Haskell is rigidly typed. The
averageThree is a good example of a function that requires type coercion in order to return the right value type. However, the
difSquare function shows something distinct to Haskell.
difSquare has no type signature, so Haskell will infer the appropriate type signature from the operations involved in the function definition. At first appearance this might seem to be the same thing that dynamically or loosely typed languages do; but what Haskell does is quite different.
difSquare is rigidly typed at compile time -- there is no runtime dynamism to this, but the type of
difSquare has a Type Class that includes both integers and floats (and also rationals, complex numbers, etc.). We can find the inferred type within Hugs:
Main> :type difSquare difSquare :: Num a => a -> a -> a
That is, both of the input arguments, as well as the output, are inferred to have the Type Class
Num. Had we explicitly declared a type like
Int, the function would operate over a narrower range of values (which is good or bad, depending on our needs).
-- Average of three Integers as floating point averageThree :: Int -> Int -> Int -> Float averageThree l m n = fromInt(l+m+n) / 3 -- float averageThree(int l, int m, int n) { -- return ((float)(l+m+n))/3; } difSquare x y = (x-y)^2 -- C lacks polymorphic type inference
Recursion
Absent loop structures, flow in Haskell programs is usually expressed as recursion. Thinking about all flow in terms of recursion takes some work, but it turns out to be just as expressive and powerful as the
while and
for constructs in other languages.
The trick to recursion is that we would like it to terminate eventually (at least we usually do). One way to guarantee termination of recursion is to use primitive recursion. This amounts to taking a "thing" to recurse on, and making sure that the next call is closer to a terminal condition than the call that got us here. In practice, we can assure this either by decrementing an integer for each call (and terminating at zero, or some other goal), or by taking only the
tail of a list for each successive call (and terminating at an empty list). Both versions of factorial listed in the example assume they will be passed an integer greater than zero (and will fail otherwise; exercise: how?).
Non-primitive recursion also exists, but it is more difficult to know for sure that a recursion will terminate. Also, mutual recursion between functions is allowed (and frequently encountered), but primitive recursion is still the safest and most common form.
-- Factorial by primitive recursion on decreasing num fac1 :: Int -> Int fac1 n = if n==1 then 1 else (n * fac1 (n-1)) -- Factorial by primitive recursion on list tail fac2 :: Int -> Int fac2 n = prodList [1 .. n] prodList lst = if (length lst)==1 then head lst else head lst*(prodList (tail lst))
Pattern matching
In functional programming, we are "more concerned with how something is defined than with the specifics of how it is calculated" (take this motto with a grain of salt, however, efficiency still matters in some cases). The idea is that it is a compiler or interpreter's job to figure out how to reach a solution, not the programmer's.
One useful way of specifying how a function is defined is to describe what results it will return given different types of inputs. A powerful way of describing "different types of inputs" in Haskell is using pattern matching. We can provide multiple definitions of a function, each having a particular pattern for input arguments. The first listed definition that succeeds in matching a given function call is the one used for that call. In this manner, you can pull out the head and tail of a list, match specific input values, identify empty lists as arguments (for recursion usually), and analyze other patterns. You cannot, however, perform value comparisons with pattern matching (for example, "
n <= 3" must be detected differently). An underscore is used in a position where something should match, but where the matched value is not used in the definition.
prodLst2 [] = 0 -- Return 0 as product of empty list prodLst2 [x] = x -- Return elem as prod of one-elem list prodLst2 (x:xs) = x * prodLst2 xs third (a,b,c,d) = c -- The third item of a four item tuple three = third (1,2,3,4) -- 'three' is 3 -- Is a sequence a sub-sequence of another sequence? isSubseq [] _ = True isSubseq _ [] = False isSubseq lst (x:xs) = (lst==start) || isSubseq lst xs where start = take (length lst) (x:xs)
Guards
Somewhat analogous to pattern matching, and also similar to
if .. then .. else, constructs (which we saw examples of earlier) are guards in function definitions. A guard is simply a condition that might obtain, and a definition of a function that pertains in that case. Anything that could be stated with pattern matching can also be rephrased into a guard, but guards allow additional tests to be used as well. Whichever guard matches first (in the order listed) becomes the definition of the function for the particular application (other guards might match also, but they are not used for a call if listed later).
In terms of efficiency, pattern matching is usually best, when possible. It is often possible to combine guards with pattern matching, as in the
isSublist example.
prodLst3 lst -- Guard version of list product | length lst==0 = 0 | length lst==1 = head lst | otherwise = head lst * prodLst3 (tail lst) -- A sublist is a string that occurs in order, but not -- necessarily contiguously in another list isSublist [] _ = True isSublist _ [] = False isSublist (e:es) (x:xs) | e==x && isSublist es xs = True | otherwise = sublist (e:es) xs
List comprehensions
One of the most powerful constructs in Haskell is list comprehensions (for mathematicians: this term comes from the "Axiom of Comprehension" of Zermelo-Frankel set theory). Like other functional languages, Haskell builds a lot of power on top of manipulation of lists. In Haskell, however, it is possible to generate a list in a compact form that simply states where the list elements come from and what criteria elements meet. Lists described with list comprehensions must be generated from other starting lists; but fortunately, Haskell also provides a quick "enumeration" syntax to specify starting lists.
-- Odd little list of even i's, multiple-of-three j's, -- and their product; but limited to i,j elements -- whose sum is divisible by seven. myLst :: [(Int,Int,Int)] myLst = [(i,j,i*j) | i <- [2,4..100], j <- [3,6..100], 0==((i+j) `rem` 7)] -- Quick sort algorithm with list comp and pattern matching -- '++' is the list concatenation operator; we recurse on both -- the list of "small" elements and the list of "big" elements qsort [] = [] qsort (x:xs) = qsort [y | y<-xs, y<=x] ++ [x] ++ qsort [y | y<-xs, y>x]
Lazy evaluation I
In imperative languages -- and also in some functional
languages -- expression evaluation is strict and immediate. If you write
x = y+z; in C, for example, you are telling the computer to make a computation and put a value into the memory called 'x' right now! (whenever the code is encountered). In Haskell, by contrast, evaluation is lazy -- expressions are only evaluated when, and as much, as they need to be (in fairness, C does include shortcutting of Boolean expressions, which is a minor kind of laziness). The definitions of
f and
g in the example show a simple form of the difference.
While a function like
g is somewhat silly, since
y is just not used, functions with pattern matching or guards will very often use particular arguments only in certain circumstances. If some arguments have certain properties, those or other arguments might not be necessary for a given computation. In such cases, the needless computations are not performed. Furthermore, when lists are expressed in computational ways (list comprehensions and enumeration ellipsis form), only as many list elements as are actually utilized are actually calculated.
f x y = x+y -- Non-lazy function definition comp1 = f (4*5) (17-12) -- Must compute arg vals in full g x y = x+37 -- Lazy function definition comp2 = g (4*5) (17-12) -- '17-12' is never computed -- Lazy guards and patterns -- Find the product of head of three lists prodHeads :: [Int] -> [Int] -> [Int] -> Int prodHeads [] _ _ = 0 -- empty list give zero product prodHeads _ [] _ = 0 prodHeads _ _ [] = 0 prodHeads (x:xs) (y:ys) (z:zs) = x*y*z -- Nothing computed because empty list matched comp3 = prodHeads [1..100] [] [n | n <- [1..1000], (n `rem` 37)==0] -- Only first elem of first, third list computed by lazy evaluation comp4 = prodHeads [1..100] [55] [n | n <- [1..1000], (n `rem` 37)==0]
Lazy evaluation II
A truly remarkable thing about Haskell -- and about lazy evaluation -- is that it is possible to work with infinite lists. Not just large ones, but actual infinities! The trick, of course, is that those parts of the list that are unnecessary for a particular calculation are not calculated explicitly (just the rule for their expansion is kept by the runtime environment).
A famous and ancient algorithm for finding prime numbers is the Sieve of Eratosthenes. The idea here is to keep an initial element of the list of integers, but strike off all of its multiples as possible primes. The example does this, but is performed only as far as needed for a specific calculation. The list
primes, however, really is exactly the list of all the prime numbers!
-- Define a list of ALL the prime numbers primes :: [Int] primes = sieve [2 .. ] -- Sieve of Eratosthenes sieve (x:xs) = x : sieve [y | y <- xs, (y `rem` x)/=0] memberOrd :: Ord a => [a] -> a -> Bool memberOrd (x:xs) n | x<n = memberOrd xs n | x==n = True | otherwise = False isPrime n = memberOrd primes n -- isPrime 37 is True -- isPrime 427 is False
First class functions (passing functions)
A powerful feature of Haskell (as with all functional programming) is that functions are first class. The first class status of functions means that functions are themselves simply values. Just as you might pass an integer as an argument to a function, in Haskell you can pass another function to a function. To a limited extent, you can do the same with function pointers in a language like C, but Haskell is far more versatile.
The power of Haskell's first class functions lies largely in Haskell's type checking system. In C, one might write a "quicksort" function that accepted a function pointer as an argument, much as in the Haskell example. However, in C you would have no easy way to make sure that the function (pointed to) had the correct type signature. That is, whatever function serves as an argument to
qsortF must take two arguments of the same type ("a" stands for a generic type) and produce a
Bool result. Naturally, the list passed as the second argument to
qsortF must also be of the same type "a." Notice also that the type signature given in the sample code is only needed for documentation purposes. If the signature is left out, Haskell infers all these type constraints automatically.
tailComp meets the right type signature, with the type
String being a specialization of the generic type allowed in
qsortF arguments (a different comparison function might operate over a different type or type class).
-- Quick sort algorithm with arbitrary comparison function qsortF :: (a -> a -> Bool) -> [a] -> [a] qsortF f [] = [] qsortF f (x:xs) = qsortF f [y | y<-xs, f y x] ++ [x] ++ qsortF f [y | y<-xs, not (f y x)] -- Comparison func that alphabetizes from last letter back tailComp :: String -> String -> Bool tailComp s t = reverse s < reverse t -- List of sample words myWords = ["foo", "bar", "baz", "fubar", "bat"] -- tOrd is ["foo","bar","fubar","bat","baz"] tOrd = qsortF tailComp myWords -- hOrd is ["bar","bat","baz","foo","fubar"] hOrd = qsortF (<) myWords
First class functions (function factories)
Passing functions to other functions is only half the power of first class functions. Functions may also act as factories, and produce new functions as their results. The ability to create functions with arbitrary capabilities within the program machinery can be quite powerful. For example, one might computationally produce a new comparison function that, in turn, was passed to the
qsortF function in the previous panel.
Often, a means of creating a function is with lambda notation. Many languages with functional features use the word "lambda" as the name of the operator, but Haskell uses the backslash character (because it looks somewhat similar to the Greek letter, lambda). A lambda notation looks much like a type signature. The arrow indicates that a lambda notation describes a function from one type of thing (the thing following the backslash) to another type of thing (whatever follows the arrow).
The example factory
mkFunc packs a fair amount into a short description. The main thing to notice is that the lambda indicates a function from
n to the result. By the type signature, everything is an
Int, although type inference would allow a broader type. The form of the function definition is primitive recursive. An empty list produces a result of zero. A non-empty list produces either the result given by its
head pair, or the result that would be produced if only its
tail is considered (and the tail eventually shrinks to empty by recursion).
-- Make an "adder" from an Int mkAdder n = addN where addN m = n+m add7 = mkAdder 7 -- e.g. 'add7 3' is 10 -- Make a function from a mapping; first item in pair maps -- to second item in pair, all other integers map to zero mkFunc :: [(Int,Int)] -> (Int -> Int) mkFunc [] = (\n -> 0) mkFunc ((i,j):ps) = (\n -> if n==i then j else (mkFunc ps) n) f = mkFunc [(1,4),(2,3),(5,7)] -- Hugs session: -- Main> f 1 -- 4 :: Int -- Main> f 3 -- 0 :: Int -- Main> f 5 -- 7 :: Int -- Main> f 37 -- 0 :: Int
Modules and program structure
Basic syntax
So far in this tutorial, we have seen quite a bit of Haskell code in an informal way. In this final section, we make explicit some of what we have been doing. In fact, Haskell's syntax is extremely intuitive and straightforward. The simplest rule is usually to "write what you mean."
Haskell and literate Haskell
The examples in this tutorial have used the standard Haskell format. In the standard format, comments are indicated with a double dash to their left. All comments in the examples are end-of-line comments, which means that everything following a double dash on a line is a comment. You may also create multi-line comments by enclosing blocks in the pair "{-" and "-}". Standard Haskell files should be named with the
.hs extension.
Literate scripting is an alternative format for Haskell source files. In files named with the
.lhs extension, all program lines begin with the greater than character. Everything that is not a program line is a comment. This style places an emphasis on program description over program implementation. It looks something like:
Factorial by primitive recursion on decreasing num > fac1 :: Int -> Int > fac1 n = if n==1 then 1 else (n * fac1 (n-1)) Make an "adder" from an Int > mkAdder n = addN where addN m = n+m > add7 = mkAdder 7
The offside rule
Sometimes in Haskell programs, function definitions will span multiple lines and consist of multiple elements. The rule for blocks of elements at the same conceptual level is that they should be indented the same amount. Elements that belong to a higher level element should be indented more. As soon as an outdent occurs, further lines are promoted back up a conceptual level. In practice, it is obvious, and Haskell will almost always complain on errors.
-- Is a function monotonic over Ints up to n? isMonotonic f n = mapping == qsort mapping -- Is range list the same sorted? where -- "where" clause is indented below "=" mapping = map f range -- "where" definition remain at least as range = [0..n] -- indented (more would be OK) -- Iterate a function application n times iter n f x | n == 0 = x -- Guards are indented below func name | otherwise = f (iter (n-1) f x)
I find that two spaces is a nice looking indentation for a subelement, but you have a lot of freedom in formatting for readability (just don't outdent within the same level).
Operator and function precedence
Operators in Haskell fall into multiple levels of precedence. Most of these are the same as you would expect from other programming languages. Multiplication takes precedence over addition, and so on (so "
2*3+4" is 10, not 14). Haskell's standard documentation can provide the details.
There is, however, one "gotcha" in Haskell precedence where it is easy to make a mistake. Functions take precedence over operators. The result is that the expression "
f g 5" means "apply
g (and 5) as arguments to f" not "apply the result of
(g 5) to
f." Most of the time, this sort of error will produce a compiler error message, since, for example,
f will require an
Int as an argument rather than another function. However, sometimes the situation can be worse than this, and you can write something valid but wrong:
double n = n*2 res1 = double 5^2 -- 'res1' is 100, i.e. (5*2)^2 res2 = double (5^2) -- 'res2' is 50, i.e. (5^2)*2 res3 = double double 5 -- Causes a compile-time error res4 = double (double 5) -- 'res4 is 20, i.e. (5*2)*2
As with other languages, parentheses are extremely useful in disambiguating expressions where you have some doubt about precedence (or just want to document the intention explicitly). Notice, by the way, that parentheses are not used around function arguments in Haskell; but there is no harm in pretending they are, which just creates an extra expression grouping (as in
res2 above).
Scope of names
You might think there is a conflict between two points in this tutorial. On the one hand, we have said that names are defined as expressions only once in a program; on the other hand, many of the examples use the same variable names repeatedly. Both points are true, but need to be refined.
Every name is defined exactly once within a given scope. Every function definition defines its own scope, and some constructs within definitions define their own narrower scopes. Fortunately, the "offside rule" that defines subelements also precisely defines variable scoping. A variable (a name, really) can only occur once with a given indentation block. Let's see an example, much like previous ones:
x x y -- 'x' as arg is in different scope than func name | y==1 = y*x*z -- 'y' from arg scope, but 'x' from 'where' scope | otherwise = x*x -- 'x' comes from 'where' scope where x = 12 -- define 'x' within the guards z = 5 -- define 'z' within the guards n1 = x 1 2 -- 'n1' is 144 ('x' is the function name) n2 = x 33 1 -- 'n2' is 60 ('x' is the function name)
Needless to say, the example is unnecessarily confusing. It is worth understanding, however, especially since arguments only have a scope within a particular function definition (and the same names can be used in other function definitions).
Breaking down the problem
One thing you will have noticed is that function definitions in Haskell tend to be extremely short compared to those in other languages. This is partly due to the concise syntax of Haskell, but a greater reason is because of the emphasis in functional programming of breaking down problems into their component parts (rather than just sort of "doing what needs to be done" at each point in an imperative program). This encourages reusability of parts, and allows much better verification that each part really does what it is supposed to do.
The small parts of function definitions may be broken out in several ways. One way is to define a multitude of useful support functions within a source file, and use them as needed. The examples in this tutorial have mostly done this. However, there are also two (equivalent) ways of defining support functions within the narrow scope of a single function definition: the
let clause and the
where clause. A simple example follows.
f n = n+n*n f2 n = let sq = n*n in sq+n f3 n = sq+n where sq = n*n
The three definitions are equivalent, but
f2 and
f3 chose to define a (trivial) support function
sq within the definition scope.
Importing/exporting
Haskell also supports a module system that allows for larger scale modularity of functions (and also for types, which we have not covered in this introductory tutorial). The two basic elements of module control are specification of imports and specification of exports. The former is done with the
import declaration; the latter with the
module declaration. Some examples include:
-- declare the current module, and export only the objects listed module MyNumeric ( isPrime, factorial, primes, sumSquares ) where import MyStrings -- import everything MyStrings has to offer -- import only listed functions from MyLists import MyLists ( quicksort, findMax, satisfice ) -- import everything in MyTrees EXCEPT normalize import MyTrees hiding ( normalize ) -- import MyTuples as qualified names, e.g. -- three = MyTuples.third (1,2,3,4,5,6) import qualified MyTuples
You can see that Haskell provides considerable, fine-grained control of where function definitions are visible to other functions. This module system helps build large-scale componentized systems.
Downloadable resources
Related topics
- Get Haskell at the Haskell home page. Haskell has several implementations for multiple platforms. These include both an interpreted version called Hugs, and several Haskell compilers.
- Learn more about Haskell in Haskell: The Craft of Functional Programming (Second Edition) by Simon Thompson (Addison-Wesley, 1999).
- Find more tutorials for Linux developers in the developerWorks Linux zone.
- Download IBM trial software directly from developerWorks.
|
https://www.ibm.com/developerworks/linux/tutorials/l-hask/
|
CC-MAIN-2019-04
|
refinedweb
| 5,449
| 58.32
|
Community.
See the Spring Framework Web MVC section on form tags for examples:-...
In order for you to use Spring form tags in your portlet, you need to include the library in your portlet JSP:
<%@ taglib prefix="form" uri="" %>
The prefix 'form' will be used to precede the Spring form tag names. This is how the JSP page knows which tag library to use. See the code snippets below to see the 'form' prefix in use. Spring form tags are only valid when contained with the Spring Form tag:
<form:form>...</form:form>
Now that the form is defined, input fields can be added, as shown below. In this example, taken from the Spring reference, there are two input fields, one for a first name and the second for a last name.
<form:form> <table> <tr> <td>First Name:</td> <td><form:input</td> </tr> <tr> <td>Last Name:</td> <td><form:input</td> </tr> </table></form:form>
Again, the 'form' in '<form:input ...' is from the taglib prefix at the top of the JSP page. The path attribute in the input tag binds the data entered in the input field to a property in the data backing object of the controller used for the JSP.
The data backing object in this case would have both of these fields along with accessor methods defined as shown:
public class UserInfo{ ...; } ...}
See the Spring Form TLD reference for details on valid tag attributes:...
|
https://community.teradata.com/t5/Viewpoint/How-to-Use-Spring-Form-Tags/m-p/64412
|
CC-MAIN-2019-09
|
refinedweb
| 241
| 77.98
|
Hello":)
I have code and I wont your help in telling its right or wrong and what missing....
This is the question ::
If the user chooses 1, then the program asks the user: “Please enter a new dictionary file name”. The program creates a new file with this file name, then it asks the user: “Please enter a word and its meaning separated by a comma”. After the user enters the word and its meaning, the program asks the user “would you like to enter another word?” if the answer is yes, then the user is asked to enter another word. If the answer is no, the file is saved to disk and the user is presented with the original menu.
the code::
public class Dictionary { private static void Dictionary() { File file = new File("dictionary.txt"); boolean success = false; try { // Create file on disk (if it doesn't exist) success = file.createNewFile(); } catch (IOException e) { } if (success) { System.out.println("File did not exist and was created.\n"); } else { System.out.println("File already exists.\n"); } }
I have this Question also;;;;
The chooses when the user select 1,2,3 I do it in the main class yes or no??
Here in this "if the answer is yes, then the user is asked to enter another word.." it means using if statment yes or no??
Thank you....
Edited 3 Years Ago by Reverend Jim: Fixed formatting
|
https://www.daniweb.com/programming/software-development/threads/321110/help-in-i-o-file
|
CC-MAIN-2016-50
|
refinedweb
| 236
| 74.29
|
I have 2 html files linked to eachother and have different css files for each of them , but meteor merges them automatically.
How do I stop this ?
You cannot. Meteor merges CSS to optimize its network delivery.
If you want to choose the order your stylesheets have in the merged CSS you may need to :
- Use a language as SASS, LESS or Stylus which allow to generate css so you could do
@import 'imports/ui/yourstylesheet.scss' to
@import files in the order you want. Note that if you choose to use a language as SASS or LESS you need to put your sass/less files that you want to import into /imports so you manually import them (puting files anywhere else than in /imports makes your files automatically imported). And
import these files via a SASS/LESS/stylus file in the
/client folder.
OR
- Put your css in
/client folder and understand the Meteor's rules to choose in which order your css get loaded :
The JavaScript and CSS files in an application are loaded according to these rules:
Files in subdirectories are loaded before files in parent directories, so that files in the deepest subdirectory are loaded first, and files in the root directory are loaded last.
Within a directory, files are loaded in alphabetical order by filename.
After sorting as described above, all files under directories named lib are moved before everything else (preserving their order).
Finally, all files that match main.* are moved after everything else (preserving their order).
OR
- You put your
.css in the
/imports directory (so Meteor doesn't import them automatically so you can choose in which order you load css files). And you import your
css via a
.js (javascript) file put into
/client (as files into
/client are loaded on your browser). In the
.js file you do
import '/imports/ui/mystylesheet.css' to import your css.
The cons of the three methods are respectively :
- You have to learn a language if you don't know any of these languages : stylus less or sass.
- Relying on complex rules to choose the order your css get loaded is probably not maintainable and oblige you to have specific names for your css
-
css files loaded within a
.js file are put in a
<style> tag inside the DOM instead of being loaded in a separate
.css file (which is not recommended). Besides the css loaded this way doesn't use the toolchain offered by Meteor plugins (compression of CSS, add pre-vendor prefixed to maximize the compatibility of your css and whatever the plugin you have offers you).
|
https://codedump.io/share/9KhUYcWSqOsg/1/how-to-stop-meteor-from-auto-merging-my-css-files
|
CC-MAIN-2018-26
|
refinedweb
| 436
| 61.36
|
[SOLVED] Crash right at instancing QMainWindow inheriting class
Hey guys,
so I've written a program with Qt, c++ and openGL and wanted to add support for my Oculus Rift DK. To get an overview, I used "this code":, rewrote parts of it and tried to get my application to run.
Since I did that, it just crashes on startup. For debugging purposes, I'm calling qDebug() everytime I enter and leave any function and between steps.
My main.cpp file looks like this:
@#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
qDebug() << "main.cpp Start!";
QApplication a(argc, argv);
qDebug() << "vor MainWindow w";
MainWindow w;
qDebug() << "vor w.show()";
w.show();
return a.exec(); qDebug() << "main.cpp Ende";
}@
It just runs up to the "vor MainWindow w" message before crashing (with an access violation).
My question is: where might that violation be? In the MainWindow constructor? Because that one also has qDebug() messages in it which are never even reached. Could it still be responsible or has it got to be something in my header file (mainwindow.h) or something?
Thanks a lot in advance!
Could you show MainWindow constructor.
what about starting your app in debug mode, if it crashes your should see a full backtrace where exactly the crash happens!?
If your have some member variables that are created on the stack in your main window it might also crash there, so hard to say without the code.
Unfortunately, my code is a huge mess (and at work, had to leave early today). I will get back to that on monday.
Starting in debug mode means having a debugger set up? I couldn't do that so far since I have no rights on my work computer. I'll see to get one though.
Thanks so far!
yeah of course you need a c++ debugger to start in debug mode, but that depends on the platform and compiler your are using.. usually you can use the default debugger unless you are using the MSVC compiler, I never figured out how to install a debugger for that. In that case I just switched to MinGW on windows there is a debugger included.
- Jeroentjehome
It's the constructor or the call to the constructor.
Because the MainWindow is also a QObject subclass and when using Designer it also includes some ui derived classes.
You might want to show the constructor?
Jeroentje: As far I know the crash can also happen in the class' member initialization.
e.g.
@
class ABC {
public:
ABC() {} // may crash here
private:
XYZ xyz; // or constructor call of XYZ here may also crash
}
@
if the constructor of a member variables crashes the body of the own constructor is never called. OP said he had debug messages in his constructor and if they never get printed that might be the issue!?
Xander84: Yes I'm using the MSVC compiler. Couldn't get a debugger to work with it too.
Anyway, solution to my problem was an error in the Oculus SDK - if you try to instanciate a sensorfusion object without calling system::init first or instanciate a system object, you're gonna have a bad time. :)
|
https://forum.qt.io/topic/40175/solved-crash-right-at-instancing-qmainwindow-inheriting-class
|
CC-MAIN-2018-30
|
refinedweb
| 532
| 74.39
|
Did you ever wonder how to quickly test online code examples? Did you ever see a code example and thought “I would love to try that right away”?
V-Play got you covered! With the V-Play Web Editor, you can run code examples on your Android or iOS phone, right from your desktop browser. It’s a Cloud IDE for editing, running and debugging QML Code. You don’t need to install any native SDKs or development environment like Qt Creator on your computer. You don’t even need to install the V-Play SDK or Qt SDK. All you need is to download the V-Play Live Scripting app for Android or iOS.
1. Download the V-Play Live Scripting App
The V-Play Live Scripting app is available on Android and iOS. Download it to use Live Code Reloading from your browser or desktop.
2. Run Code Examples from Documentation and Blog with the V-Play Web Editor
You can find the V-Play Web Editor for Qml code at.
For convenience you can also find a button above all code examples in our documentation and on the blog. Click on it to open the example in the Web Editor. Here is an example that you can try right away (make sure you read this post on your desktop!):
import VPlayApps 1.0 import VPlay 2.0 import QtQuick 2.8 App { NavigationStack { Page { title: "My First App" AppButton { anchors.centerIn: parent text: "Celebrate" onClicked: { nativeUtils.displayAlertDialog("Yay", "That is so cool!") } } } } }
There are some more cool examples at the end of this post, make sure to give them a try!
3. Test on Android and iOS at the Same Time
You can connect all your mobile phones to the Web Editor at the same time. This means you can test how an example looks on different platforms simultaneously.
The Web Editor also displays log output of your connected devices.
4. Live Code Reloading in your Browser
You would like to change the example code a bit? No problem!
You can edit the code in the Web Editor and click the run button, or hit CTRL+S (CMD+S on macOS). The code reloads on your mobile phone immediately and shows the new result.
It is also possible to write your own code, or copy/paste any example to the Web Editor. You get the full log output of any connected mobile phone, to find possible errors in your code.
Cloud IDE Benefits for You
The biggest benefit was already highlighted in the introduction of this post. You can test code examples right away on your mobile phone from the browser. This works without installing any SDK on your desktop.
Besides that, it is also useful for developers that already have everything installed. You save the effort to create a new project to test an example. You can explore the documentation and test any interesting example with only a button click.
With Live Code Reloading, you can tweak the example within your browser until it fits for you.
Live Code Reloading on Desktop, Android and iOS
You can also use the V-Play Live Scripting app for development on desktop. You can find more info about V-Play Live Code Reloading in this post.
What’s Next for the V-Play Cloud IDE for QML
Currently the run button might also be displayed for code examples in the documentation that will not run successfully.
The majority of examples and code snippets from the V-Play Apps documentation is working fine already, and while you’re reading this the games documentation is finalized as well. This means you can already start working with the Web Editor and start saving development time!
We will update the V-Play Live Scripting app next week with an improved user interface and a project cache. You will be able to open your projects on your mobile phone also when not connected to your desktop, to show it to friends, customers or to yourself.
The next steps are then support for autocompletion, integrated help and Git support. This allows you to work on the same project on Desktop (with Qt Creator or any other IDE you prefer) and the web, with the V-Play Cloud IDE for QML code.
More QML Code Examples
QML Map Example
Displays a map using the MapBox service.
import VPlayApps 1.0 import QtLocation 5.5 App { NavigationStack { Page { title: "Map Example" // show the map AppMap { anchors.fill: parent }] } } } } }
QML List Example
Shows a simple list with a button to add new list items.
import VPlayApps 1.0 App { NavigationStack { Page { id: page title: "Add List Items" // the data model for the list property var dataModel: [ { text: "Item 1" }, { text: "Item 2" }, { text: "Item 3" } ] // button to add an item AppButton { id: button anchors.horizontalCenter: parent.horizontalCenter text: "Add Row" onClicked: { // create and add new item var itemNr = page.dataModel.length + 1 var newItem = { text: "Item "+itemNr } page.dataModel.push(newItem) // signal change in data model to trigger UI update (list view) page.dataModelChanged() } } // list view AppListView { id: listView anchors.top: button.bottom anchors.bottom: parent.bottom width: parent.width model: page.dataModel delegate: SimpleRow {} } } } }
QML AdMob Ad Banner Example
Shows the easy integration of a native AbMob ad banner.
import QtQuick 2.0 import VPlayApps 1.0 import VPlayPlugins 1.0 App { NavigationStack { Page { title: "AdMob" AdMobBanner { adUnitId: "ca-app-pub-3940256099942544/6300978111" } } } }
QML Physics Example
Simple game example where gravity pulls a ball downwards.
import VPlay 2.0 import QtQuick 2.8 GameWindow { Scene { EntityManager { id: entityManager } // gravity will pull the ball down PhysicsWorld { gravity.y: 9.81 } // just a simple ball shaped entity EntityBase { id: entity width: 20 height: 20 x: 160 y: 240 Rectangle { anchors.fill: parent color: "red" radius: 10 } // the collider enables physics behavior BoxCollider { id: collider anchors.fill: parent } } // this timer resets the ball after 3 seconds Timer { running: true interval: 3000 repeat: true onTriggered: { entity.x = 160 entity.y = 240 collider.linearVelocity = Qt.point(0,0) } } } }
You can find more code examples everywhere in our documentation.
The code snippets page is a compilation of several useful code examples for apps.
Go to Code Snippets Page
More Posts Like This
Release 2.14.0: Live Code Reloading for Desktop, iOS & Android
How to Make Cross-Platform Mobile Apps with Qt – V-Play Apps
|
https://v-play.net/cross-platform-development/web-editor-test-online-code-examples-on-android-and-ios-with-live-code-reloading
|
CC-MAIN-2018-39
|
refinedweb
| 1,062
| 66.54
|
23 October 2009 17:17 [Source: ICIS news]
By Nigel Davis
LONDON (ICIS news)--If you have sought direction from the first flush of third-quarter financial results from the sector majors or, recently, from chemicals markets themselves, then you may not have been disappointed.
The talk has been of recovery, although globally the picture remains depressed. DuPont on Tuesday said it was almost sold out of the white pigment titanium dioxide but continued to struggle in its high-strength materials businesses.
Dow on Thursday talked of “early cycle growth in emerging geographies”.
CEO Andrew Liveris identified Greater China, s?xml:namespace>
This is welcome, sequential growth although chemicals demand remains well down on last year. Plant operating rates have been forced down. Dow’s average in the quarter was 78%, three percentage points higher than in the second quarter of the year.
The story is still that of coming off the bottom of the trough with demand growth driven principally by
But, while
“Challenges certainly remain,” Liveris said in a conference call, “particularly in the mature economies such as those of the
Such a message is likely to be repeated as this earnings season progresses. It is not so much a question of chemical industry executives being conservative in outlook – as suggested by one investment analyst this month. They see very little in the way of ‘green shoots’ on the economic horizon in either the
DuPont’s European businesses were dragged down in the third quarter by a poor showing from operations in c
The
In sharp contrast, statistics showed this week that China’s GDP grew by 8.9% in the third quarter compared with growth of 7.9% in the second quarter.
For the big western chemicals producers and their counterparts in
DuPont makes a great deal of its new product introductions. Dow is focusing more on closer to end-use market businesses following its takeover of specialty materials maker Rohm and Haas.
The drive to specialise, or rather to push the higher margin businesses, and to get closer to the customer, has been accelerated by the recession. It is changing the faces of the latest chemicals producers.
Lower margin, and in broad terms, basic commodity businesses have been more starkly exposed by the recession. Some are struggling to make a comeback.
Dow’s chloralkali business, for instance, remains under pressure, both, Liveris says, on the vinyl chloride monomer (VCM) side related to construction and on caustic soda because of weak fundamentals in the alumina and pulp and paper industries.
In such businesses companies have to move fast to match their manufacturing capabilities with expected ongoing levels of market demand. This is where it really hurts as operating rates remain low and plants eventually are shuttered or closed.
Dow and other companies clearly feel that the global economy is now on firmer ground. Trade is beginning to pick up, Liveris said this week. The good news is that exports from
“Market stability has improved,” he added, “but we continue to remain cautious about the ability of some economies to sustain growth. This is especially true of the
Liveris says that Dow’s 2009/10 operating plans still “do not count on material improvements in market conditions”.
For more on Dow Chemical and DuPont visit ICIS company intelligence
Read
|
http://www.icis.com/Articles/2009/10/23/9257741/INSIGHT-Dont-expect-much-from-US-and-Europe.html
|
CC-MAIN-2014-49
|
refinedweb
| 551
| 51.28
|
In this assignment, you will explore three classic puzzles from the perspective of uninformed search.
A skeleton file
homework2 cases where you find yourself reinventing the wheel. If you are unsure where to start, consider taking a look at the data structures and functions defined in the
collections,
itertools,
math, this section, you will develop a solver for the $n$-queens problem, wherein $n$ queens are to be placed on an $n \times.
[5 points] Rather than performing a search over all possible placements of queens on the board, it is sufficient to consider only those configurations for which each row contains exactly one queen.
Therefore, without taking any of the chess-specific constraints between queens into account, we want to first consider the number of possible placements of $n$ queens on an $n \times n$ board without or with the restriction that each row contains exactly one queen.
Implement the function
num_placements_all(n), which returns the number of all possible placements of $n$ queens on an $n \times n$ board, and the function
num_placements_one_per_row(n) that calculates the number of possible placements of $n$ queens on an $n \times n$ board such that each row contains exactly one queen.
Think carefully about why this restriction is valid, and note the extent to which it reduces the size of the search space. You should assume that all queens are indistinguishable for the purposes of your calculations.
[5 points] With the answer to the previous question in mind, a sensible representation for a board configuration is a list of numbers between $0$ and $n - 1$, where the $i$th number designates the column of the queen in row $i$ for $0 \le i \lt, 2]) True
>>> n_queens_valid([0, 1]) False >>> n_queens_valid([0, 3, 1]) True
[15 points] Write a function
n_queens_solutions(n) that returns a list of all valid placements of $n$ queens on an $n \times n$ board, using the representation discussed above. The output may be in any order you see fit. Your solution should be implemented as a depth-first search, where queens are successively placed in empty rows until all rows have been filled. You may find it helpful to define a helper function
n_queens_helper(n, board) that yields all valid placements which extend the partial solution denoted by
board.
>>> n_queens_solutions(6) [[1, 3, 5, 0, 2, 4], [2, 5, 1, 4, 0, 3], [3, 0, 4, 1, 5, 2], [4, 2, 0, 5, 3, 1]] >>> len(n_queens_solutions(8)) 92
The Lights Out puzzle consists of an $m \times last section for more details.
.
>>> b = [[True, False], [False, True]] >>> p = LightsOutPuzzle(b) >>> p.get_board() [[True, False], [False, True]]
>>> b = [[True, True], [True, True]] >>> p = LightsOutPuzzle(b) >>> p.get_board() [[True, True], [True, True]]
. After importing the
random module with the statement
import random, the expression
random.random() < 0.5 generates the values
True and
False with equal probability.
]]
>>> for i in range(2, 6): ... p = create_puzzle(i, i + 1) ... print(len(list(p.successors()))) ... 6 12 20 30
GUI provided.
In this section, you will investigate the movement of disks on a linear grid. if another disk is located on the intervening square. cell
from to the cell
to. $\ell$, then a desired solution moves the first disk from cell $0$ to cell $\ell - 1$, the second disk from cell $1$ to cell $\ell - 2$, $\cdots$, and the last disk from cell $n - 1$ to cell $\ell -)]
>>> solve_distinct_disks(4, 3) [(1, 3), (0, 1), (2, 0), (3, 2), (1, 3), (0, 1)] >>> solve_distinct_disks(5, 3) [(1, 3), (2, 1), (0, 2), (2, 4), (1, 2)]
[1 point] Approximately how long did you spend on this assignment?
[2 point] Which aspects of this assignment did you find most challenging? Were there any significant stumbling blocks?
[2 point] Which aspects of this assignment did you like? Is there anything you would have changed?
Once you’ve filled in the functions for any of the problems (
N-Queens,
Lights Out &
Linear Disk Movement), you can test out your implementation using the
homework2_gui.py file provided. Simply run the script using
python homework2_gui.py. Once you run this command, Mac users should see a window pop up that is completely white. On the menu bar, go to New and select the problem you are trying to test out. If your implementation is correct, you should be able to obtain solutions for the problem.
|
http://artificial-intelligence-class.org/homeworks/hw2/homework2.html
|
CC-MAIN-2021-49
|
refinedweb
| 731
| 68.1
|
NAME
VOP_RENAME - rename a file
SYNOPSIS
#include <sys/param.h> #include <sys/vnode.h> int VOP_RENAME(struct vnode *fdvp, struct vnode *fvp, struct componentname *fcnp, struct vnode *tdvp, struct vnode *tvp, struct componentname *tcnp);
DESCRIPTION
This renames a file and possibly changes its parent directory. If the destination object exists, it will be removed first. Its arguments are: fdvp The vnode of the old parent directory. fvp The vnode of the file to be renamed. fcnp Pathname information about the file’s current name. tdvp The vnode of the new parent directory. tvp The vnode of the target file (if it exists). tcnp Pathname information about the file’s new name.
LOCKS
The source directory and file are unlocked but are expected to have their ref count bumped on entry. The VOP routine is expected to vrele(9) both prior to returning. The destination directory and file are locked as well as having their ref count bumped. The VOP routine is expected to vput(9) both prior to returning.
ERRORS
[EPERM] The file is immutable. [EXDEV] It is not possible to rename a file between different file systems. [EINVAL] An attempt was made to rename . or .., or to perform an operation which would break the directory tree structure. [ENOTDIR] An attempt was made to rename a directory to a file or vice versa. [ENOTEMPTY] An attempt was made to remove a directory which is not empty.
SEE ALSO
vnode(9)
AUTHORS
This manual page was written by Doug Rabson.
|
http://manpages.ubuntu.com/manpages/maverick/man9/VOP_RENAME.9freebsd.html
|
CC-MAIN-2015-40
|
refinedweb
| 249
| 59.9
|
Understanding data access
This topic has been updated for the Orchard 1.9 release.
Data access in an Orchard project is different than data access in a traditional web application, because the data model is built through code rather than through a database management system. You define your data properties in code and the Orchard framework builds the database components to persist the data. If you need to change the data structure, you write code that specifies the changes, and those changes are then propagated by that code to the database system. This code-centric model includes layers of abstraction that permit you to reuse components in different content types and to add or change behaviors without breaking other layers.
The key concepts of data access are the following:
- Records
- Data migrations
- Content handlers
- Content drivers
Records
A record is a class that represents the database schema for a content part. To create a record, you define a class that derives from
ContentPartRecord and add the properties that you need in order to store data for the content part. Each property must be virtual. For example, a
Map part might include the following record:
namespace Map.Models { public class MapRecord : ContentPartRecord { public virtual double Latitude { get; set; } public virtual double Longitude { get; set; } } }
Typically, the record class resides in a folder named Models. The parent class,
ContentPartRecord, also includes a property named
id and a reference to the content item object. Therefore, an instance of the
MapRecord class includes not just
Latitude and
Longitude but also the
id property and the content item object that is used to maintain the relationships between the part and other content.
When you define a content part, you use the record as shown below:
namespace Maps.Models { public class MapPart : ContentPart<MapRecord> { [Required] public double Latitude { get { return Retrieve(r => r.Latitude); } set { Store(r => r.Latitude, value); } } [Required] public double Longitude { get { return Retrieve(r => r.Longitude); } set { Store(r => r.Longitude, value); } } } }
Notice that only data that's relevant to the part is defined in the
MapPart class. You do not define any properties that are needed to maintain the data relationships between
MapPart and other content.
For a complete example of the MapPart, see Writing a Content Part.
Data Migrations
Creating the record class does not create the database table; it only creates a model of the schema. To create the database table, you must write a data migration class.
A data migration class enables you to create and update the schema for a database table. The code in a migration class is executed when an administrator chooses to enable or update the part. The update methods provide a history of changes to the database schema. When an update is available, the site administrator can choose to run the update.
You can create a data migration class by running the following command from the Orchard command line:
codegen datamigration <feature_name>
This command creates a Migrations.cs file in the root of the feature. A
Create method is automatically created in the migration class.
In the
Create method, you use the
SchemaBuilder class to create the database table, as shown below for the
MapPart feature.
In the
Uninstall method you can implement destructive operations that will be executed when the module is uninstalled. Keep in mind that when a module is re-added and enabled after it was uninstalled it will be installed again, thus the
Create method of migrations will also run. void Uninstall() { // Dropping tables can potentially cause data loss for users so be sure to warn them in your module's documentation about the implications. SchemaBuilder.DropTable("MapRecord"); ContentDefinitionManager.DeletePartDefinition(typeof(MapPart).Name); } } }
By including
.ContentPartRecord() with your properties in the definition of the database schema, you ensure that other essential fields are included in the table. In this case, an
id field is included with
Latitude and
Longitude.
The return value is important, because it specifies the version number for the feature. You will use this version number to update the schema.
You can update the database table by adding a method with the naming convention
UpdateFromN, where N is the number of the version to update. The following code shows the migration class with a method that updates version by adding a new column. int UpdateFrom1() { SchemaBuilder.AlterTable("MapRecord", table => table .AddColumn("Description", DbType.String) ); return 2; } } }
The update method returns 2, because after the column is added, the version number is 2. If you have to add another update method, that method would be called
UpdateFrom2().
After you add the update method and run the project the module will be silently & automatically upgraded.
Content Handlers
A content handler is similar to a filter in ASP.NET MVC. In the handler, you define actions for specific events. In a simple content handler, you just define the repository of record objects for the content part, as shown in the following example:
namespace Map.Handlers { public class MapHandler : ContentHandler { public MapHandler(IRepository<MapRecord> repository) { Filters.Add(StorageFilter.For(repository)); } } }
In more advanced content handlers, you define actions that are performed when an event occurs, such as when the feature is published or activated. For more information about content handlers, see Understanding Content Handlers.
Content Drivers
A content driver is similar to a controller in ASP.NET MVC. It contains code that is specific to a content part type and is usually involved in creating data shapes for different conditions, such as display or edit modes. Typically, you override the Display and Editor methods to return the ContentShapeResult object for your scenario.
For an example of using a content driver, see Accessing and Rendering Shapes.
|
http://docs.orchardproject.net/Documentation/Understanding-data-access
|
CC-MAIN-2015-14
|
refinedweb
| 945
| 54.73
|
31 October 2012 06:34 [Source: ICIS news]
By Clive Ong
?xml:namespace>
SINGAPORE
Lacklustre demand for ABS, which usually commands a premium of $200-300/tonne (€154-231/tonne) to HIPS given a stronger resistance quality, saw the price gap narrowing since August, they said.
“The usual spread between ABS and PS is less than $100/tonne currently, and maybe prices of the resins could reach parity soon,” said a China-based ABS trader.
On 26 October, ABS prices were assessed unchanged at $1,920-1,960/tonne CFR (cost and freight) NE (northeast)
“Perhaps more HIPS users will start to switch to ABS since it has higher impact strength,” said a Hong Kong-based trader.
The ABS-HIPS price spread has been narrowing since mid-August, when it fell below $200/tonne from the peak of $390/tonne on 17 February, according to ICIS.
A number of traders expect ABS makers to try raising prices, but it would be difficult given the current lull season and declining values of main feedstocks acrylonitrile (ACN) and butadiene (BD).
“ABS demand is very weak this year as the Chinese exports sector was sluggish,” another Hong Kong-based trader said.
Weak economic conditions in the
ABS - which is made up of 25% ACN, 15% BD and 60% styrene monomer (SM) - is used in making toys, appliances, consumer electronics and office equipment.
Falling prices of feedstocks ACN and BD compound the pressure for ABS.
BD tumbled to $1,775/tonne in late October from around $2,450/tonne CFR NE Asia in mid-July. ACN, on the other hand, shed $200/tonne from mid-September to $1,750/tonne in late October because of poor demand, ICIS data showed.
“The weak performance in ACN and BD prices since late September has caused ABS prices to stagnate,” said an ABS producer.
HIPS, on the other hand, is being buoyed up by firm values of feedstock SM as the product has a higher 90% content of the monomer compared with ABS.
SM prices have gained more than $300/tonne from early June to $1,625/tonne CFR China on 19 October because of strained availability of spot cargoes in
($1 = €0
|
http://www.icis.com/Articles/2012/10/31/9609047/asia-abs-demand-may-pick-up-as-premium-over-hips-thins-down.html
|
CC-MAIN-2014-35
|
refinedweb
| 366
| 64.04
|
Raspberry Pi Cluster Node – 01 Logging Liveness
This post describes how to make a simple python script that logs the node is alive every 10 seconds.
Why we are going to log each node is alive
As discussed in the previous post on Distributed Computing on the Raspberry Pi Cluster there will be many slaves and a single master in the first stage.
The image reproduced opposite shows the process each slave will go through. They will repeatedly ask for work, then perform the action given to them.
If there is no work then they will idle for a period of time and then ask the master again for work.
This cycle will form the basis of running distributed work on the cluster. Any live node will be able to come online and request work. Once the work is done it will report back to the master with the result.
Then the loop will continue again requesting more work.
What we are going to use
This first script will create the event loop to check if there is work to do and add logging to keep track of what the node is doing.
I am going to use the standard python logger to keep track of the work the node is doing. I will be configuring this to log data to both the console and a file. This will mean that I can view what the process is doing by observing the running console and ensure this data is saved to a file.
Another really useful feature that the python logger has is that it is inherently thread safe. For the moment we are only using a single thread so this won’t matter. However in the future I plan to move towards making this applicable multi-threaded and having logging that handles this will be very useful.
Setting up the python logger
The python logging module can be simply imported using
import logging. Once we have imported this we have access to all the logging features needed for our Raspberry Pi Cluster.
To start with I am going to set up a formatter for the logs.
logFormatter = logging.Formatter( "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
This formatter will be used to define the format of the logs produced. This includes all the important information including the time, thread, level and the message logged. As discussed above while the current program is not multi-threaded this will be in the future so it will be helpful to keep track of which thread is writing to the log.
Now that I have a formatter I can start to get the base logger object. This can be obtained using the below code.
logger = logging.getLogger() logger.setLevel(logging.DEBUG)
Here I am getting the base logger and setting the level of messages that will be logged. By setting it to
DEBUG I ensure that all messages will be logged. This base level set is inherited by all child loggers and output handlers.
To actually save print out or save the log I need to attach handlers to the log. The most basic type of handler is the console handler. This works by printing all the information out to the console. I create one using the following code.
consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logFormatter) consoleHandler.setLevel(logging.INFO) logger.addHandler(consoleHandler)
Once the handler has been created with
logging.StreamHandler() I attach the formatter I created earlier. For the console output I have also set the logging level to
INFO. This means only messages of
INFO and higher will be printed to the console. The final but most important line attaches the handler to the logger we created earlier. This will receive the messages sent to the logger and will print them to the console.
In addition to logging to the console I want to keep a store of all messages in case I need to review what has been occurring. I am able to do this with the following code by creating a file handler.
fileHandler = logging.FileHandler("mainlogger.log") fileHandler.setFormatter(logFormatter) logger.addHandler(fileHandler)
Here as I am creating a logger to save to a file I supply a filename
mainlogger.log. This will be the file that is written to each time the logger runs. By default each time this code runs the file will have log data appended to it. This means if the script is stopped and rerun old log data won’t be lost. Again like above we use our custom log formatter to format our logs in a specific way.
Now we have created our logger and various handlers to display the data we are ready to use it.
Using the Python Logger
The logger object has a number of methods to allow us to log a message and data. The basic log function is
logger.log(level, message, args)
Here you log a specific message at a specific error level. This error level is an integer representing the severity of the message. The message along with any additional arguments will be used by your formatter to display and store the message. With log you have to specify a specific error level, the basic logging levels, as taken from the python site are:
This means that a logger set to a default level of
DEBUG will log any messages set at level 10 and above. So that you don’t have to remember these values you can use the helper methods
logger.debug(message, args) logger.info(message, args) logger.warning(message, args) logger.error(message, args) logger.critical(message, args)
These work identically to
logger.log() except they have preset the log level to the respective integer (based on the above table). For ease of use I will be using the specific logger functions defined above.
Creating the basis of a Raspberry Pi Cluster worker
Now I have the logger set up I can create a really basic Raspberry Pi Cluster worker. For this example it won’t perform any jobs but this structure will be used in the future.
I will define a function that will eventually be used to find work to perform. In this case I will just use my logger to log that there is no work to be done.
def find_work_to_do(): logger.info("Node slave still alive") logger.info("Looking for work to run") return None
This function also returns
None so that the calling function knows that there is nothing to do. The next and most crucial piece of code is the worker loop.
while True: work = find_work_to_do() if work is None: logger.info("Found no jobs to perform, going to sleep again") time.sleep(10) else: pass # we will do work in the future but not at the moment
Here we run forever checking to see if there is any work. If there is no work found, as determined by getting
None back from the
find_work_to_do function then it will log this and sleep for 10 seconds.
For the moment we will ignore the case that work has been found as this is just to set up a basic work loop.
Summary of work towards the Raspberry Pi Cluster
Today I have gone over the basics of the python logger and set up the initial code for our cluster project. In addition, I have created the template function that will be used to get work for our nodes. The next lessons will focus on creating a basic system to talk to a master node and send messages.
The full code for this first example is available on the Github Repository for this project.
|
https://chewett.co.uk/blog/741/raspberry-pi-cluster-node-01-logging-liveness/
|
CC-MAIN-2020-05
|
refinedweb
| 1,280
| 63.8
|
1 /* $Id: RegexMatcher.java 155412 2005-02-26 12:58:36Z dirkv .commons.digester;19 20 21 /**22 * Regular expression matching strategy for RegexRules.23 *24 * @since 1.525 */26 27 abstract public class RegexMatcher {28 29 /** 30 * Returns true if the given pattern matches the given path 31 * according to the regex algorithm that this strategy applies.32 *33 * @param pathPattern the standard digester path representing the element34 * @param rulePattern the regex pattern the path will be tested against35 * @return true if the given pattern matches the given path36 */37 abstract public boolean match(String pathPattern, String rulePattern);38 39 }40
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/org/apache/commons/digester/RegexMatcher.java.htm
|
CC-MAIN-2017-30
|
refinedweb
| 117
| 56.25
|
Today's programming challenge is to implement."
First, some imports:
USING: command-line formatting io io.encodings.binary io.files kernel math math.functions namespaces sequences ;
Short Version
A quick file-based version might look like this:
: sum-file. ( path -- ) [ binary file-contents [ sum 65535 mod ] [ length 512 / ceiling ] bi ] [ "%d %d %s\n" printf ] bi ;
You can try it out:
( scratchpad ) "/usr/share/dict/words" sum-file. 19278 4858 /usr/share/dict/words
The main drawbacks to this version are: loading the entire file into memory (which might be a problem for big files), not printing an error if the file is not found, and not supporting standard input.
Full Version
A more complete version might begin by implementing a function that reads from a stream, computing the checksum and the number of 512-byte blocks:
: sum-stream ( -- checksum blocks ) 0 0 [ 65536 read-partial dup ] [ [ sum nip + ] [ length + nip ] 3bi ] while drop [ 65535 mod ] [ 512 / ceiling ] bi* ;
The output should look like
CHECKSUM BLOCKS FILENAME:
: sum-stream. ( path -- ) [ sum-stream ] dip "%d %d %s\n" printf ;
We can generate output for a particular file (printing
FILENAME: not found if the file does not exist):
: sum-file. ( path -- ) dup exists? [ dup binary [ sum-stream. ] with-file-reader ] [ "%s: not found\n" printf ] if ;
And, to prepare a version of
sum that we can deploy as a binary and run from the command line, we build a simple MAIN: word:
: run-sum ( -- ) command-line get [ "" sum-stream. ] [ [ sum-file. ] each ] if-empty ; MAIN: run-sum
The code for this is on my Github.
|
http://re-factor.blogspot.com/2011/03/sum.html
|
CC-MAIN-2015-40
|
refinedweb
| 263
| 60.55
|
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.
On Tue, 20 Feb 2001, Benjamin Kosnik wrote: > >. I just haven't been able to get things to work on Solaris 8 when __cplusplus is set to 199711L for compliance with the C++ standard, and here's why. The system headers that come with out-of-the-box Solaris 8 are fully compliant with section D.1.5.2 of the C++ standard, that is they provide the required names in both global and std namespaces. They do this by declaring the names in the std namespace in a set of header files (in /usr/include/iso), and then injecting them into the global namespace via using declarations in the system headers. The Sun WS6 compiler supplies its own standard C++ header files which do nothing but include the /usr/include/iso header files directly. None of this is a problem for the WS6 compiler or for GCC 2.95.2 because neither compiler respects clause 7.3.3.1 of the C++ standard regarding the uniqueness of names in using declarations. GCC 3.x complies with this clause, causing all sorts of name clashes between various headers. By patching a couple of system headers I can manage to get a bootstrap of the 3.x complier (with the c_std headers), but simple test programs will not compile due to name clashes. Any attempt to use the "c" or "c_shadow" C++ headers instead of the "c_std" headers will not event bootstrap due to massive name clashes throughout the headers. The "c" headers won't work because they leave everything in std in the global namespace as well, so you can't include, say, <unistd.h> and <cstdio> in the same program. The "c_shadow" headers have other, more bizarre problems the cause of which I'm still trying to track, but I don't think they really do what we want (although they should, in theory, do what we need in a very roundabout way). I think what we need in the case of Soalris 8 is a fourth set of C++ headers that are designed to wrap the D.1.5.2-compliant headers and just let the std names show through. They would just do something like // for <cstring> namespace _system_header_ { # include <string.h> } namespace std { using namespace _system_header_::std; } // end of <cstring> Is this a good idea or should I continue to hack away at perhaps getting c_shadow headers to work? Stephen m. Webb
|
http://gcc.gnu.org/ml/libstdc++/2001-02/msg00311.html
|
crawl-001
|
refinedweb
| 423
| 70.43
|
◕ A new product.
Popular Google Pages:
This article is regarding sizeof Operator in C++.
Last updated on: 15th November 2016.
Choose your Language: English Bengali
◕ Let a simple program:
#include <iostream>
#include <climits>
using namespace std;
int main()
{
int man = 2;
cout << "int is a Type. The size of this Type is " << sizeof (int) << " Bytes." << endl;
cout << "man is a Variable. The size of this Variable is " << sizeof (int) << " Bytes." << endl;
return 0;
}
◕ This above program will produce the following answer:
int is a Type. The size of this Type is 4 Bytes.
int is a Variable. The size of this Variable is 4 Bytes.
◕ In the above example:
The sizeof is an Operator in the C++. We can say an Operator is a Built-in-Language Element that operates on one or more items. Such as addition ( + ), subtraction ( - ), multiplication ( x ) and divide ( / ).
When we use the sizeof operates then we have to include the climits header file.
The sizeof operator returns the size of a Type or size of a Variable in Bytes.
◕ Please note that:
- When we use sizeof operator to find the size of a Type such as int, then we enclose the Type in parentheses.
- And when we use sizeof operator to find the size of a Variable such as man, then parentheses is optional.
- The size of a Type may vary in different system due climits header file. Because different manufacturers make it differently.
Popular Google Pages:
Top of the page
|
http://riyabutu.com/c-plus-plus/size-of-operator.php
|
CC-MAIN-2017-51
|
refinedweb
| 246
| 76.62
|
Werner, Thanks for your post. Is very useful. I am using Guard so that might be one place to start looking although I personally didn't develop that part of the code. (Which kinda make me even more suspicious). The Manhole stuff looks interesting too. I will give that a go if I can't find anything by disabling the Guard code. Thanks again. AW On Tue, Dec 16, 2008 at 10:39 PM, Werner Thie <wthie at thiengineering.ch>wrot= e: > Hi > > I was bitten by the same problem and went so far to track down all the > fishy cycles which easily can be created. Most of the cycles I detected w= ere > multi-object cycles which were created by me just storing references to > objects to have them handy. Certain types of cycles cannot be broken by t= he > gc, you get a runaway situation either in Python24 or Python25. My code n= ow > runs without problems for months serving more than 10k users a day provid= ing > th= an > hints. > > I include some code which I wrote to peek into my running server with a > manhole connection. dumpobjects is loosely based on several Python snippe= ts > and might not win a contest in programming but it helps to track the numb= er > of objects of certain types in the running system when used on the > commandline from inside your server. > > HTH, Werner > > To create a manhole in the same process you started with your .tac file u= se > the following code: > > --------------------------------------------------------------- > def ManholeFactory(namespace, **passwords): > realm =3D manhole_ssh.TerminalRealm() > > def getManhole(_): > return manhole.Manhole(namespace) > > realm.chainedProtocolFactory.protocolFactory =3D getManhole > p =3D portal.Portal(realm) > > > p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse(**pass= words)) > f =3D manhole_ssh.ConchFactory(p) > return f > > console =3D ManholeFactory(globals(), admin=3D'admin') > internet.TCPServer(2222, console, > interface=3D'localhost').setServiceParent(application) > --------------------------------------------------------------- > > exc =3D [ > "function", > "type", > "list", > "dict", > "tuple", > "wrapper_descriptor", > "module", > "method_descriptor", > "member_descriptor", > "instancemethod", > "builtin_function_or_method", > "frame", > "classmethod", > "classmethod_descriptor", > "_Environ", > "MemoryError", > "_Printer", > "_Helper", > "getset_descriptor", > "weakreaf" > ] > > inc =3D [ > 'YourObject_One', > 'YourObject_Two' > ] > > prev =3D {} > > def dumpObjects(delta=3DTrue, limit=3D0, include=3Dinc, exclude=3D[]): > global prev > if include !=3D [] and exclude !=3D []: > print 'cannot use include and exclude at the same time' > return > print 'working with:' > print ' delta: ', delta > print ' limit: ', limit > print ' include: ', include > print ' exclude: ', exclude > objects =3D {} > gc.collect() > oo =3D gc.get_objects() > for o in oo: > if getattr(o, "__class__", None): > name =3D o.__class__.__name__ > if ((exclude =3D=3D [] and include =3D=3D []) or \ > (exclude !=3D [] and name not in exclude) or \ > (include !=3D [] and name in include)): > objects[name] =3D objects.get(name, 0) + 1 > ## if more: > ## print o > pk =3D prev.keys() > pk.sort() > names =3D objects.keys() > names.sort() > for name in names: > if limit =3D=3D 0 or objects[name] > limit: > if not prev.has_key(name): > prev[name] =3D objects[name] > dt =3D objects[name] - prev[name] > if delta or dt !=3D 0: > print '%0.6d -- %0.6d -- ' % (dt, objects[name]), name > prev[name] =3D objects[name] > > > > > > > > Abdul-Wahid Paterson wrote: > >> Hi, >> >> I am using Python 2.5. >> >> I will try to use guppy as suggested in another post to so if it will >> help. Otherwise yes, I will try to reduce it to the smallest possible co= de >> to demonstrate the leak. At the moment the code is a bit complex so is h= ard >> to track down. >> >> Thanks for the help. >> >> AW >> >> >> >> On Tue, Dec 16, 2008 at 6:23 PM, Phil Christensen <phil at bubblehouse.org<= mailto: >> phil at bubblehouse.org>> wrote: >> >> >> >> _______________________________________________ >> Twisted-web mailing list >> Twisted-web at twistedmatrix.com <mailto:Twisted-web at twistedmatrix.com> >> >> >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Twisted-web mailing list >> Twisted-web at twistedmatrix.com >> >> > > _______________________________________________ > Twisted-web mailing list > Twisted-web at twistedmatrix.com > > -------------- next part -------------- An HTML attachment was scrubbed... URL: d42b56/attachment.htm
|
http://twistedmatrix.com/pipermail/twisted-web/2008-December/004045.html
|
CC-MAIN-2013-48
|
refinedweb
| 633
| 58.99
|
Unable to change the qml property from c++
Here I have piece of code to change the qml color property from my c++ source.
QObject *object = QObject::findChild <QObject*>("colorBox"); if(object) { qDebug("found color_behaviour"); //object->setProperty("color","white"); QColor color(Qt::red); object->setProperty("color",color); }
But, the color property in my qml file is never changed. The above piece of code is inside a function in one of the cpp files. I also even tried the following way from main.cpp file.
QQmlEngine engine; QQmlComponent component(&engine,"qrc:/QML/Components/GTColorBox.qml"); QObject *rootObject = component.create(); QObject *object = rootObject->findChild <QObject * >("colorBox"); if(object) { qDebug("found color_behaviour"); object->setProperty("color","black"); QColor color(Qt::red); object->setProperty("color",color); qDebug("found black color"); }
- SGaist Lifetime Qt Champion last edited by
Hi,
You should also provide:
- your QML code.
- the Qt version you are using
- the platform you are running on
- KazuoAsano Qt Champions 2018 last edited by
In additional informations,
I try shot code. It's fine in Qt5.12 linux x64.
Is there a difference in those?
main.cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QColor>; QObject *rootObject = engine.rootObjects().first(); QObject *object = rootObject->findChild<QObject*>("colorBox"); if(object) { QColor color(Qt::red); object->setProperty("color",color); qDebug("change red color"); } return app.exec(); }
main.qml
import QtQuick 2.9 import QtQuick.Controls 2.2 ApplicationWindow { visible: true width: 100 height: 100 title: qsTr("test") Rectangle { objectName: "colorBox" width: parent.width height: parent.height anchors.fill: parent color: "blue" } }
- dheerendra Qt Champions 2017 last edited by dheerendra
What ever u tried will work only if the object is created and displayed. I am not sure about your first sample. Second sample shows your object is created in c++ and not displayed anywhere. I suspect that your qml object is not displayed. So you have nothing to visually check.
Unable to visually check, but the debug statements after setProperty line of code are executed successfully, will this link helps in doing visual change?
Yes, the property is succesfully changed but cannot visualize it in the view. Will setting context property help in visual change of the color property in my qml file? In my case, it is not like passing a data from model to qml file but should pass a color change to the qml file. Will this article helps?
There is nothing like passing property to qml file. Qml file is component. Please note what u r changing is object property. So you have to have object displayed.
Question for you - how are you telling property is not changed ?
I have my object being displayed already in my qml file as
objectName: "colorBox"
Show me your qml code. Also in the first code sample what happened ? Did it come to if condition ?
This post is deleted!
- dheerendra Qt Champions 2017 last edited by dheerendra
Are you loading this qml in main.cpp ? Can you tell me what is the meaning of the following statement in your code ?
QObject object = QObject::findChild <QObject>("colorBox");
For which object you are trying to find a child ?
@KazuoAsano has already given the sample example. Did you compare with your program ?
@dheerendra Yes I am loading the qml in my main.cpp but it is in the second case. In the first case iam finding the child from another class in cpp function.
If you are finding a object, then it should work. Please note you are loading item object. Item does not have color property. So nothing works. In fact setProperty(...) method should fail. Check the return value of setProperty.
if (!obj->setProperty("color","blue")) { qWarning() << " Failed to set the color Property" <<endl; return; }
@dheerendra The program is crashing during this check
I suspect that obj is null. Please check your program. Please check the sample given by @KazuoAsano & compare your program.
@dheerendra Yes, the object is null. it is not finding the child when i used QQml engine and not QQmlApplication engine from my main.cpp file.
Please show the main.cpp & how are you loading the qml file. Based on this we can suggest. I'm assuming that you are loading the qml which has 'colorBox' object.
I tried in this way the same way said by @KazuoAsano, i placed a rectangle in main.qml file and from main.cpp tried to set the property color as red and it remained in blue and here is my code.
main.qml file
Gui { id: MainView; objectName: "MainView" Rectangle{ objectName: "colorBox" width: 200 height: 100 anchors.horizontalCenter: parent.horizontalCenter anchors.verticalCenter: parent.verticalCenter //anchors.centerIn: parent.Center color: "blue" } Loader {
Here is my main.cpp file
QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/QML/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; QObject *rootObject = engine.rootObjects().first(); QObject *object = rootObject->findChild<QObject*>("colorBox"); if(object) { QColor color(Qt::red); object->setProperty("color",color); qDebug("Change red color"); }
The colorBox remained in the blue color.
Yes, setProperty will fail because, it is inside an item. And also when i try to print the object name and children count, it shows correct count for the children and also root object name. The actual children count is displayed as 2 with the
children().count();
whereas when i try to find the object names
using
QList<QObject*> list = rootObject->findChildren<QObject *>(); qDebug("list = %d",list.count()); int i; for(i=0;i<list.count();i++) { QObject *obj = list[i]; qDebug() << "Object" << i << obj->objectName(); }
it displays list count as 81 and among some object names some are empty and object 28 is my colorBox, but unable to set the color property from c++ file.
So it means that you are have object called a color box. So you should get the reference of this object when you do findChild. If you are getting this you should be able to set the color. When you say it does not work, what do you mean ? Your object is Item. Can you check whether value is set to color. I'm not sure what are you doing with this property in Item after wards.
- KazuoAsano Qt Champions 2018 last edited by
I seem to it is a difficult problem...
I wrote code based on this forum thread information,again,
Can you check the expected behavior of the software?
After that you confirm a difference in those and Let's solve this issue with everyone.
- GrecKo Qt Champions 2018 last edited by
An alternative would be to not do that, it's bad practice and not very maintainable.
Some links to coroborate my claim :
-
-
-
A proper alternative would be to set a QObject as a context property and expose properties in it.
Yes thankyou, i found a way. But not through qml but tried from two c++ files.
|
https://forum.qt.io/topic/98263/unable-to-change-the-qml-property-from-c/10
|
CC-MAIN-2019-43
|
refinedweb
| 1,129
| 59.9
|
#include <ne_request.h>
The ne_set_request_body_fd function can be used to include a message body with a request which is read from a file descriptor. The body is read from the file descriptor fd, which must be a associated with a seekable file (not a pipe, socket, or FIFO). count bytes are read, beginning at offset begin (hence, passing begin as zero means the body is read from the beginning of the file).
For all the above functions, the source of the request body must survive until the request has been dispatched; neither the memory buffer passed to ne_set_request_body_buffer nor the file descriptor passed to ne_set_request_body_fd are copied internally.
ne_request_create
Joe Orton <neon@lists.manyfish.co.uk>
|
http://www.makelinux.net/man/3/N/ne_set_request_body_fd64
|
CC-MAIN-2014-49
|
refinedweb
| 116
| 57.4
|
Advanced Java Interview Questions -14
1 Does Java support multiple inheritance ?
This is the trickiest question in Java, if C++ can support direct multiple inheritance than why not Java is the argument Interviewer often give. See Why multiple inheritance is not supported in Java to answer this tricky Java question.
2 What will happen if we put a key object in a HashMap which is already there ?. See How HashMap works in Java for more tricky Java questions from HashMap..
4 What is the issue with following implementation of compareTo() method in Java?
public int compareTo(Object o){
Employee emp = (Employee) emp;
return this.id – o.id;
}
5 that’s called method hiding. See Can you override private method in Java or more details.
6 What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept.
7 where id is an integer number ?
Well three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can not guaranteed id is positive or negative. If id is negative than subtraction may overflow and produce incorrect result. See How to override compareTo method in Java for complete answer of this Java tricky question for experienced programmer.
8.
9.
10.
11 Can you access non static variable in static context?
Another tricky Java question from Java fundamentals. No you can not access static variable in non static context in Java. Read why you can not access non-static variable from static method to learn more about this tricky Java questions.
12.
13. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.
14. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java
15. What will be the problem if you don’t override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
See here How HashMap works in Java for detailed explanation.
16. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)
17. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
18. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.
19. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.
20. amout of processing
21. Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap,.
22. Where does these two method comes in picture during get operation?
This core Java interview question is follow-up of previous Java question and candidate should know that once you mention hashCode, people are most likely ask How its used in HashMap. See How HashMap works in Java for detailed explanation.
23..
24..
25..
26..
27..
28. Does all property of immutable object needs to be final?
Not necessary as stated above you can achieve same functionality by making member as non final but private and not modifying them except in constructor.
29..
30..
31.
32.
33.
34 What does intern() method do in Java
As discussed in previous String interview question, String object crated by new() operator is by default not added in String pool as opposed to String literal. intern() method allows to put an String object into pool.
35.
36.
37 Why String is final in Java
String is final by design in Java, some of the points which makes sense why String is final is Security, optimization and to maintain pool of String in Java. for details on each of this point see Why String is final in Java.
38.
39.
40.
41.
42 Why there are no global variables in Java?
Global variables are globally accessible and hence can create collisions in namespace.
43 What is the Java API?
It a large collection of software components that provide capabilities, such as graphical user interface (GUI) widgets.
44 Explain StringTokenizer.
It is utility class that are used to break up string.
Example:
StringTokenizer str = new StringTokenizer(“Welcome”);
while (str.hasMoreTokens()) {
System.out.println(st.nextToken());
}
45.
46 Does Java support pointers?
Java doesn’t support the usage of pointers. Improper handling of pointers leads to memory leaks which is why pointer concept hasn’t found place in Java.
Swing and Awt
47 AWT are heavy-weight componenets.
Swings are light-weight components and this is reason why swing works faster than AWT.
48 Pass by reference and passby value
Pass By Reference is the passing the address itself rather than passing the value.
Passby Value is passing a copy of the value to be passed.
49 Abstract class
It must be extended or subclassed.
It acts as a template.
It may contain static data.
A class may be declared abstract even if it has no abstract methodsand this prevents it from being instantiated.
50 What()
51.
52.
53..
55.
56.
57.
58
59. Which make clear that by default String constants are interned?
60.
61.
62.
What is JPA in java?
The Java Persistence API is enabling us to create the persistence layer for desktop and web applications. Java Persistence deals in following:
Java Persistence API
Query language
Java Persistence Criteria API
Object mapping metadata
63
}
64.
65.
66.
67.
68.
69.
70 What is the difference between applications and applets?.
71.
72.
73>
74 Explain the usage of serialization.
Objects are serialized when need to be sent over network.
They are serialized when the state of an object is to be saved.
75.
76 Define Method overriding. Explain its uses.
Method overriding is the process of writing functionality for methods
77);
78
79 This.
80.
81
82 Static class loading vs. dynamic class loading..
83.
84 What is the purpose of the File class?
The File class provides access to the files and directories of a local file system.
85 Define inner class in Java
Class that is nested within a class is called as inner class. The inner class can access private members of the outer class. It is mainly used to implement data structure and some time called as a helper class.
86.
87 Difference between Swing and Awt.
AWT are heavy-weight components. Swings are light-weight components. Thus, swing works faster than AWT.
88.
89”);
f.setName(request.getParameter(“name”));
f.setAddr(request.getParameter(“addr”));
f.setAge(request.getParameter(“age”));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .” scope=”request”
/ jsp:getProperty name=”fBean” property=”name”
/ jsp:getProperty name=”fBean” property=”addr”
/ jsp:getProperty name=”fBean” property=”age”
/ jsp:getProperty name=”fBean” property=”personalizationInfo” /
90” %>
91)% >” >
92 what is a JSP Page?
A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML, WML, XML, etc), and JSP elements, which construct dynamic content.JSP is a technology that lets you mix static content with dynamically-generated content.
93.
94 How are the JSP requests handled?
The following sequence of events happens on arrival of jsp request:
a. Browser requests a page with .jsp file extension in web server.
b. Web server reads the request.
c. Using jsp compiler, webserver converts the jsp into a servlet class that implement the javax.servletjsp.jsp page interface. The jsp file compiles only when the page is first requested or when the jsp file has been changed.
e. The response is sent to the client by the generated servlet.
95 what are the advantages of JSP?
The following are the advantages of using JSP:
a. JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content.
b. JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired.
c. JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the complexity of application logic.
d. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.
e. Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly, developers can make logic changes at the component level without editing the individual pages that use the logic.
96.
97 What are the implicit objects?
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.
98 Is JSP technology extensible?
Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
99.
100.
101
%>
102.>
103
**/
%>
Q-13 id=”foo” >
<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>”/ >
<%– scriptlets calling bean setter methods go here –%>
</jsp:useBean >
104 Briefly explain about Java Server Pages technology?.
105);
%>
106.
For example:
<%
session.setMaxInactiveInterval(300);
%>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.
107 How can I enable session tracking for JSP pages if the browser has disabled cookies?, interac
t>
hello2.jsp
<%@ page session=”true” %>
<%
Integer i= (Integer )session.getValue(“num”);
out.println(“Num value in session is “+i.intValue());
|
https://www.lessons99.com/advanced-java-interview-questions-14.html
|
CC-MAIN-2020-05
|
refinedweb
| 1,736
| 58.48
|
Mango From Scratch
As noted in earlier posts, Mango represents a move from Silverlight 3+ to Silverlight 4, and
with that comes ICommand on ButtonBase and Hyperlink (and classes that derive from these two).
This is a significant breakthrough, especially if you are programming with MVVM.
ICommand allows you to bind an action as a property, thus keeping a clean separation from the controlling class (typically the view model) to the presentation class (typically the view).
To see this at work, we’ll create a program that retrieves data from a (pseudo-) web service, and displays that data when a button is pushed.
To do this, I created a new program in Mango. The Xaml consists of a button (Load) and a list box (initially empty). I opted to put a white border on the list box so that it acts as a placeholder.
The heart of the program sits in DelegateCommand.cs where I implement ICommand.
In his excellent article on ICommand John Papa describes 5 steps for Commanding in Silverlight, and I followed the five steps exactly to do the same in Windows Phone. What worked in Silverlight now works in the Phone.
John says, Step 1: Implement ICommand – that is, implement the interface, which I do in the DelegateCommand class.
using System; using System.Windows.Input; namespace ICommandPhone { public class DelegateCommand : ICommand { Func<object, bool> canExecute; Action<object> executeAction; bool canExecuteCache; public DelegateCommand( Action<object> executeAction, Func<object, bool> canExecute ) { this.executeAction = executeAction; this.canExecute = canExecute; } ); } } }
Key here is that the Silverlight code works as is. In fact, that is true throughout this program. The only changes for the phone have to do with layout on the MainPage.
The ViewModel class is named BookViewModel, which derives ViewModelBase, which, in turn, implements INotifyPropertyChanged.
Step 2 – Define the Command
In the ViewModel I define the ICommand that I’ll be implementing
public ICommand LoadBooksCommand { get; set; }
Step 3 – Create The Command
Again, I do this in the ViewModel, this time in the constructor.
LoadBooksCommand = new DelegateCommand( LoadBooks, CanLoadBooks );
While I’m in the constructor, I also mimic the creation of data that would normally be retrieved from, e.g., a web service,
public BookViewModel() { Books = new ObservableCollection<Book>(); AllBooks = new ObservableCollection<Book>(); AllBooks.Add( new Book { ID = 1, Name = "Programming Rx and Linq" } ); AllBooks.Add( new Book { ID = 2, Name = "Migrating Windows Phone" } ); AllBooks.Add( new Book { ID = 3, Name = "Programming C#" } ); AllBooks.Add( new Book { ID = 4, Name = "Learning C#" } ); AllBooks.Add( new Book { ID = 5, Name = "Visual C# Notebook" } ); AllBooks.Add( new Book { ID = 6, Name = "Learning VB.Net" } ); AllBooks.Add( new Book { ID = 7, Name = "Programming .NET" } ); AllBooks.Add( new Book { ID = 8, Name = "Programming ASP.NET" } ); AllBooks.Add( new Book { ID = 9, Name = "TY C++ In 21 Days" } ); AllBooks.Add( new Book { ID = 10, Name = "TY C++ In 24 Hours" } ); AllBooks.Add( new Book { ID = 11, Name = "TY C++ In 10 Minutes" } ); AllBooks.Add( new Book { ID = 12, Name = "Clouds To Code" } ); AllBooks.Add( new Book { ID = 13, Name = "Beginning OOAD" } ); AllBooks.Add( new Book { ID = 14, Name = "XML Web Classes From Scratch" } ); AllBooks.Add( new Book { ID = 15, Name = "C++ From Scratch" } ); AllBooks.Add( new Book { ID = 16, Name = "Web Classes Fronm Scratch" } ); }
Step 4 – Create the VM
We are now ready to bind the Command property of the Button to the LoadBooksCommand shown above (which in turn, will invoke the LoadBooks method). To do this, we must tell the View what its ViewModel is. Still following John, I took the expedient of using a Resource in the View,
<phone:PhoneApplicationPage.Resources> <local:BookViewModel x: </phone:PhoneApplicationPage.Resources>
I then set this ViewModel to be the DataContext for the StackPanel that holds the Button,
<StackPanel DataContext="{StaticResource vm}"
Step 5 – Bind the Command
Finally, in the button itself, I make the link to the LoadBooksCommand,
<Button Name="LoadButton" Content="Load" Margin="5" Command="{Binding LoadBooksCommand}" />
With that, when the button is pressed, the LoadBooksCommand is invoked through the ICommand mechansim, causing the LoadBooks method in the VM to be invoked,
private void LoadBooks( object param ) { string filter = param as string ?? string.Empty; Books.Clear(); var query = from p in this.AllBooks where p.Name.ToLower().StartsWith( filter.ToLower() ) select p; foreach ( var item in query ) { this.Books.Add( item ); } }
As you can see from the illustration at the top of this posting, it works exactly as expected; the view contains a button, the codebehind for that view is empty, and we’ve bound the clicking of that button to the Command property in the View Model.
Pingback: Coming In Mango – ICommand –
Will the ApplicationBar buttons and menu items support commands?
@Stefan: Prism 4 for Windows Phone already provides a way to use a ICommand as an action in the ApplicationBar buttons and menu items.
|
http://jesseliberty.com/2011/05/02/coming-in-mangoicommand/
|
CC-MAIN-2016-36
|
refinedweb
| 800
| 55.64
|
Haskell programming tips ["ThingsToAvoid trying to find a more declarative implementation using higher order functions.
Don't define {{{#!syntax haskell raise :: Num a => a -> [a] -> [a] raise _ [] = [] raise x (y:ys) = x+y : raise x ys }}} because it is hard for the reader to find out, how much of the list is processed and on which values the elements of the output list depend. Just write {{{#!syntax haskell raise x ys = map (x+) ys }}} or even {{{#!syntax haskell raise x = map (x+) }}} and the reader knows that the complete list is processed and that each output element depends only on the corresponding input element.
If you don't find appropriate functions in the standard library, extract a general function. This helps you and others
p x = 1 + count p xs
which you won't like any longer if you become aware of {{{#!syntax haskell count p = length . filter p }}} .
Only introduce identifiers you need
Here is some advice that is useful for every language, including scientific prose (): Introduce only identifiers you use. The compiler will check that you if you pass an option like {{{-Wall}}} for GHC.
In an expression like
i <- [1..m]]
where {{{a}}} might be a horrible complex expression it is not easy to see, that {{{a}}} really does not depend on {{{i}}}. {{{#!syntax haskell. {{{#!syntax haskell. {{{#!syntax haskell {{{#!syntax haskell tuples 0 _ = [[]] }}} but then we can also omit the pattern for 1-tuples.
{{{#!syntax haskell tuples :: Int -> [a] -> a tuples 0 _ = [[]] tuples r l =
if r == length l then [l] else let t = tail l in map (head l :) (tuples (r-1) t) ++ tuples r t
}}} What about the case {{{r > length l}}}? Sure, no reason to let {{{head}}} fail - in that case there is no tuple, thus we return an empty list. Again, this saves us one special case. {{{#!syntax haskell tuples :: Int -> [a] -> a tuples 0 _ = [[]] tuples r l =
if r > length l then [] else let t = tail l in map (head l :) (tuples (r-1) t) ++ tuples r t
}}}
We have learnt above that {{{length}}} is evil! What about {{{#!syntax haskell]}}}!
You can even save one direction of recursion by explicit computation of the list of all suffixes provided by {{{tails}}}. You can do this with do notation {{{#!syntax haskell}}}. {{{#!syntax haskellCasesAndIdentities
Don't overuse lambdas
Like explicit recursion, using explicit lambdas isn't a universally bad idea, but a better solution often exists. For example, Haskell is quite good at currying. Don't write {{{#!syntax haskell zipWith (\x y -> f x y)
map (\x -> x + 42) }}}
instead, write {{{#!syntax haskell zipWith f
map (+42) }}}
also, instead of writing {{{#!syntax haskell -- sort a list of strings case insensitively sortBy (\x y -> compare (map toLower x) (map toLower y)) }}}
write {{{#!syntax haskell comparing p x y = compare (p x) (p y)
sortBy (comparing (map toLower)) }}} which is both clearer and re-usable. Actually, in a future version of GHC you may not even have to define {{{comparing}}}, as it's already defined in Data.Ord in the CVS version.
(Just a remark for this special example: We can avoid multiple evaluations of the conversions. {{{#!syntax haskell sortKey :: (Ord b) => (a -> b) -> [a] -> [a] sortKey.): {{{#!syntax haskell foreach2 xs ys f = zipWithM_ f xs ys
linify :: [String] -> IO () linify lines
= foreach2 [1..] lines $ \lineNr line -> do unless (null line) $ putStrLn $ shows lineNr $ showString ": " $ show line
}}}
Bool is a regular type
Logic expressions are not restricted to guards and {{{if}}} statements. Avoid verbosity like in
mod n 2 == 0 = True
since it is the same as {{{#!syntax haskell isEven n = mod n 2 == 0 }}} .
Use syntactic sugar wisely
People who employ SyntacticSugar extensively argue that their code becomes more readable by it.?
list comprehension
List comprehension let you remain in imperative thinking, that is it let you think in variables rather than transformations. Open your mind, discover the flavour of the PointFreeStyle!
Instead of
c <- s]
write {{{#!syntax haskell map toUpper s }}} .
Consider
s <- strings, c <- s]
where it takes some time for the reader to find out which value depends on what other value and it is not so clear how many times the interim values {{{s}}} and {{{c}}} are used. In contrast to that {{{#!syntax haskell map toUpper (concat strings) }}} can't be clearer.
When using higher order functions you can switch easier to data structures different from {{{List}}}.
Compare {{{#!syntax haskell map (1+) list }}} and {{{#!syntax haskell mapSet (1+) set }}} . If there would be a standard instance for the {{{Functor}}} class you could use the code {{{#!syntax haskell.
Instead of {{{#!syntax haskell do
text <- readFile "foo" writeFile "bar" text
}}} one can write {{{#!syntax haskell readFile "foo" >>= writeFile "bar" }}} .
The code {{{#!syntax haskell do
text <- readFile "foo" return text
}}} can be simplified to {{{#!syntax haskell readFile "foo" }}} by a law that each Monad must fulfill.
You certainly also agree that {{{#!syntax haskell do
text <- readFile "foobar" return (lines text)
}}} is more complicated than {{{#!syntax haskell liftM lines (readFile "foobar") }}} . Btw.
Guards look like
n == 0 = 1
which implements a factorial function. This example, like a lot of uses of guards, has a number of problems.
The first problem is that it's nearly impossible for the compiler to check if guards like this are exhaustive, as the guard conditions may be arbitrarily complex (Ghc will warn you if you use the {{{-Wall}}} option). To avoid this problem and potential bugs through non exhaustive patterns you should use an {{{otherwise}}} guard, that will match for all remaining cases:
n == 0 =}}}, {{{#!syntax haskell --}}}s are difficult to read. See ["Case"] how to avoid nested {{{if}}}s.
But in this special case, the same can be done even more easily with pattern matching: {{{#!syntax haskell -- Good implementation: fac :: Integer -> Integer fac 0 = 1 fac n = n * fac (n-1) }}}
Actually, in this case there is an even more easier to read version, which (see above) doesn't use Explicit Recursion: {{{#!syntax haskell -- Excellent implementation: fac :: Integer -> Integer fac n = product [1..n] }}} returns 1.
Guards don't always make code clearer. Compare
not (null xs) = bar (head xs)
and {{{#!syntax haskell foo (x:_) = bar x }}}
or compare the following example using the advanced PatternGuards ()
Left err <- parse cmd "Commands" ln = BadCmd $ unwords $ lines $ show err
with this one with NoPatternGuards: {{{#!syntax haskell parseCmd ln = case parse cmd "Commands" ln of
Left err -> BadCmd $ unwords $ lines $ show err Right x -> x
}}} or, if you expect your readers to be familiar with the {{{either}}} function: {{{#!syntax haskell: {{{#!syntax haskell data Foo = Foo deriving (Eq, Show)
instance Num Foo where
fromInteger = error "forget it"
f :: Foo -> Bool f 42 = True f _ = False }}}
{{{#!syntax haskell
- Main> f 42
- Exception: forget it
}}}
Only use guards if you need to, in general you should stick to pattern matching whenever possible.
n+k patterns
In order to allow pattern matching against numerical types, Haskell 98 provides so-called n+k patterns, as in {{{#!syntax haskell take :: Int -> [a] -> [a] take (n+1) (x:xs) = x: take n xs take _ _ = [] }}} However, they are often critizised for hiding computational complexity and producing ambiguties, see ["ThingsToAvoid, if you don't need it
Don't write {{{#!syntax haskell {{{#!syntax haskell x == [] }}} is faster but it requires the list {{{x}}} to be of type {{{[a]}}} where {{{a}}} is a type of class {{{Eq}}}.
The best to do is {{{#!syntax haskell null x }}}
Additionally, many uses of the length function can be replaced with an {{{atLeast}}} function that only checks to see that a list is greater than the required minimum length. {{{#!syntax haskell atLeast :: Int -> [a] -> Bool atLeast 0 _ = True atLeast _ [] = False atLeast n (_:ys) = atLeast (n-1) ys }}} or non-recursive, but less efficient because both {{{length}}} and {{{take}}} must count {{{#!syntax haskell atLeast :: Int -> [a] -> Bool atLeast n x = n == length (take n x) }}} or non-recursive but fairly efficient {{{#!syntax haskell atLeast :: Int -> [a] -> Bool atLeast n =
if n>0 then not . null . drop (n-1) else const True
}}} or {{{#!syntax haskell atLeast :: Int -> [a] -> Bool atLeast 0 = const True atLeast n = not . null . drop (n-1) }}}
The same problem arises if you want to shorten a list to the length of another one by {{{#!syntax haskell take (length x) y }}} since this is inefficient for large lists {{{x}}} and fails for infinite ones. But this can be useful to extract a finite prefix from an infinite list. So, instead {{{#!syntax haskell zipWith const y x }}} works well.
It should be noted that {{{length}}}, {{{take}}} and others wouldn't cause headache if they would count using PeanoNumbers as shown below.
Don't ask for the minimum if you don't need it
The function {{{isLowerLimit}}} checks if a number is a lower limit to a sequence. {{{#!syntax haskell isLowerLimit :: Ord a => a -> [a] -> Bool isLowerLimit x ys = x <= minimum ys }}} It fails definitely if {{{ys}}} is infinite. Is this a problem?
Compare it with {{{#!syntax haskellOverflow for advice on which fold is appropriate for your situation.
Choose types properly
Lists are not good for everything
Lists are not arrays
Lists are not arrays, so don't treat them as such. Frequent use of {{{(!!)}}} should alarm you. Accessing the {{{n}}}th list element requires to traverse through the first {{{n}}} nodes of the list. This is very inefficient.
If you access the elements progressively like in
i <- [0..n]]
you should try to get rid of indexing like in {{{#!syntax haskell zipWith (-) x [0..n] }}} .
If you really need random access like in the Fourier Transform you should switch to {{{Array}}}s. {{{FiniteMap a Int}}}.
Lists are not finite maps
Similarly, lists are not finite maps, as mentioned on EfficiencyHints.}}}. Clear what it does? No? The code is probably more understandable {{{#!syntax haskell removeEach :: (Eq a) => [a] -> a removeEach xs = map (flip List.delete xs) xs }}} but it should be replaced by {{{#!syntax haskell removeEach :: [a] -> a removeEach xs =
zipWith (++) (List.inits xs) (tail (List.tails xs))
}}} since this works perfectly for function types {{{a}}} and for equal elements in {{{xs}}}.
Don't use Int if you don't consider integers
Before using integers for each and everything (C style) think of more specialised types. If only the values {{{0}}} and {{{1}}} are of interest, try the type {{{Bool}}} instead. If there are more choices and numeric operations aren't needed try an enumeration. If an enumeration is not appropriate you can define a {{{newtype}}} carrying the type that is closest to what you need.
Instead of {{{#!syntax haskell type Weekday = Int }}} write
Tuesday
It allows all sensible operations like {{{==}}}, {{{<}}}, {{{succ}}} and forbids all nonsensical ones like {{{+}}}, {{{*}}}. You cannot accidentally mix up weekdays with numbers and the signature of a function with weekday parameter clearly states what kind of data is expected.
Miscellaneous. You can easily benefit from lazy evaluation if you process data purely functionally and output it by a short IO interaction.
{{{#!syntax haskell -- import Control.Monad (replicateM_) replicateM_ 10 (putStr "foo") }}} is certainly worse than {{{#!syntax haskell putStr (concat $ replicate 10 "foo") }}}
{{{#!syntax haskell do
h <- openFile "foo" WriteMode replicateM_ 10 (hPutStr h "bar") hClose h
}}} can be shortened to {{{#!syntax haskell writeFile "foo" (concat $ replicate 10 "bar") }}} which also safes you from proper closing of the handle {{{h}}} in case of failure.
A function which computes a random value with respect to a custom distribution ({{{distInv}}} is the inverse of the distribution function) can be defined via IO {{{#!syntax haskell {{{#!syntax haskell randomDist :: (RandomGen g, Random a, Num a) => (a -> a) -> State g a randomDist distInv = liftM distInv (State (randomR (0,1))) }}} ?
Forget about quot and rem
They complicate handling of negative dividends. {{{div}}} and {{{mod}}} are almost always the better choice. If {{{b>0}}} then it always holds {{{#!syntax haskell}}}
- Conversion from a day counter to a week day: {{{mod n 7}}}
- Pacman runs out of the screen and re-appears at the opposite border: {{{mod x screenWidth}}}
|
https://wiki.haskell.org/index.php?title=Haskell_programming_tips&oldid=6937
|
CC-MAIN-2021-31
|
refinedweb
| 1,987
| 72.46
|
IRC log of tagmem on 2002-04-22
Timestamps are in UTC.
12:55:09 [RRSAgent]
RRSAgent has joined #tagmem
12:55:15 [Zakim]
Zakim has joined #tagmem
13:41:47 [DanCon]
DanCon has joined #tagmem
14:17:24 [Norm]
Norm has joined #tagmem
14:22:12 [Stuart]
Stuart has joined #tagmem
14:25:20 [DanCon]
that was *almost* suggested text. But it wasn't actual suggested text.
14:25:57 [DanCon]
folks seem to feel free to spout whatever opinion comes to mind, with no obligation to contribute to an architecture document.
14:26:17 [DanCon]
not your posting, Stuart.
14:26:20 [DanCon]
but most of the others.
14:26:42 [DanCon]
RRSAgent, pointer?
14:26:42 [RRSAgent]
See
14:26:46 [Stuart]
yep... it's a big thread...
14:26:57 [Stuart]
What is RRSAgent?
14:27:08 [DanCon]
a log-to-http-space service
14:27:34 [DanCon]
it does a few other things... tracks action items, I think. try: /msg RRSAgent help
14:30:24 [Norm]
zakim, list conferences
14:30:25 [Zakim]
I see VB_Multi()10:00AM, Team_Comm()9:30AM, T&S_()10:00AM, TAG_Weekly()10:00AM
14:30:35 [DanCon]
Zakim, this will be TAG
14:30:36 [Zakim]
ok, DanCon, I see TAG_Weekly()10:00AM already started
14:30:44 [Norm]
Dan beat me to it
14:32:57 [Zakim]
+DanC
14:33:41 [Zakim]
+Ian
14:34:00 [Ian]
zakim, who's here?
14:34:01 [Zakim]
I see ??P32, ??P34, ??P2, DanC, Ian
14:34:12 [Ian]
zakim, ??P32 might be Paul
14:34:13 [Zakim]
I don't understand '??P32 might be Paul', Ian. Try /msg Zakim help
14:34:19 [Ian]
zakim, ??P32 may be Paul
14:34:20 [Zakim]
+Paul?; got it
14:34:32 [Ian]
zakim, ??P34 may be Stuart
14:34:33 [Zakim]
+Stuart?; got it
14:34:39 [Ian]
zakim, ??P2 may be Norm
14:34:40 [Zakim]
+Norm?; got it
14:34:49 [Zakim]
+TBray
14:35:10 [Ian]
zakim, mute Norm
14:35:11 [Zakim]
Norm? should now be muted
14:35:35 [Ian]
zakim, Norm is Paul
14:35:36 [Zakim]
+Paul; got it
14:35:43 [Ian]
zakim, who's here?
14:35:44 [Zakim]
I see Paul?, Stuart?, Paul (muted), DanC, Ian, TBray
14:35:54 [Ian]
zakim, unmute Paul
14:35:55 [Zakim]
'Paul' is ambiguous, Ian
14:36:05 [Ian]
zakim, mute Paul?
14:36:07 [Zakim]
Paul? should now be muted
14:36:15 [Norm]
zakim, who's here?
14:36:17 [Zakim]
I see Paul? (muted), Stuart?, Paul (muted), DanC, Ian, TBray
14:36:24 [Ian]
zakim, Paul? is Stuart
14:36:25 [Zakim]
+Stuart; got it
14:36:26 [Stuart]
can you hear me
14:36:30 [Norm]
no
14:36:34 [Ian]
zakim, Stuart? is Norm
14:36:35 [Zakim]
+Norm; got it
14:36:40 [Stuart]
then I'm muted
14:36:43 [Ian]
zakim, unmute Paul
14:36:44 [Zakim]
Paul should no longer be muted
14:36:47 [Ian]
zakim, who's here?
14:36:49 [Zakim]
I see Stuart (muted), Norm, Paul, DanC, Ian, TBray
14:36:54 [DanCon]
ack Stuart
14:36:56 [Ian]
zakim, unmute Stuart
14:36:57 [Zakim]
Stuart was not muted, Ian
14:37:07 [Norm]
zakim, who's here
14:37:10 [Zakim]
Norm, you need to end that query with '?'
14:37:15 [Ian]
Regrets: TBL
14:37:18 [DanCon]
Stuart: not here yet: DaveO, RoyF, TimBL
14:37:22 [Norm]
zakim, who's here?
14:37:23 [Zakim]
I see Stuart, Norm, Paul, DanC, Ian, TBray
14:37:27 [DanCon]
Stuart: not here yet: DaveO, RoyF, TimBL, ChrisL
14:37:59 [Ian]
--------------------
14:38:07 [Ian]
Minutes of previous meeting? No objections.
14:38:17 [Ian]
14:38:23 [Zakim]
+DOrchard
14:38:32 [Ian]
SW: I've put time allotments on the agenda; I hope it's useful.
14:38:53 [Ian]
Agenda:
14:39:35 [Ian]
SW: Additions? None.
14:39:45 [Ian]
Action item review:
14:39:56 [Ian]
DO: Write text about "Web as information space", to be integrated by IJ. Status - not done.
14:40:07 [Ian]
IJ: Integrate/combine one-page summaries. Status - not done
14:40:48 [Ian]
TBL Actions not done.
14:40:56 [Ian]
RF: Write up discussion of RFC3205 based on www-tag input.
14:41:02 [Ian]
Status Done:
14:41:53 [Ian]
DC: I propose to withdraw the action.
14:42:16 [Ian]
DC: Correction - RF's message is a proposal to withdraw the action.
14:42:38 [Ian]
SW: Action hereby withdrawn; we'll pick up when we address HTTPSubstrate-16.
14:42:43 [Ian]
================
14:42:50 [Ian]
Prioritization of issues list.
14:42:55 [Ian]
Strawman from SW:
14:43:45 [Ian]
DC: For me the priority is whatever goes first in the arch doc. I find it hard to address these issues without context.
14:43:53 [Zakim]
+??P0
14:43:55 [TBray]
TBray has joined #tagmem
14:43:57 [Ian]
SW: So, order by doc order, not urgency/sense of importance.
14:44:12 [Ian]
DC: Doc order is not arbitrary; things earlier should depend on fewer other things.
14:44:15 [TBray]
Hah... figured out my IRC client
14:44:17 [Ian]
zakim, ??P0 is Roy
14:44:17 [Zakim]
+Roy; got it
14:44:19 [DanCon]
Zakim, ??P0 is RoyF
14:44:22 [Zakim]
sorry, DanCon, I do not recognize a party named '??P0'
14:45:30 [Ian]
TB: Two thoughts:
14:45:41 [Ian]
a) Agree with DC about starting from points of few dependencies outward.
14:45:58 [Ian]
b) Also order based on urgency relative to work going on in w3c.
14:46:16 [Ian]
(e.g., GET in SOAP)
14:47:33 [Ian]
TB: I like SW's list; it seems to meet both criteria (a) and (b).
14:47:45 [Ian]
(with exception of *-13 first).
14:48:30 [Ian]
TB: I propose 7 first, then the rest of the list as is.
14:48:40 [Ian]
TB: 7, 13, 15, 6, 14, 16, 8
14:48:58 [Ian]
SW records no dissent.
14:49:01 [Ian]
===============
14:49:10 [DanCon]
is 13 really supposed to be in that list?
14:49:26 [Ian]
Correction:
14:49:52 [Ian]
Handle issues in this order: 7, 15, 6, 14, 16, 8, 13
14:49:53 [Dave]
Dave has joined #tagmem
14:49:55 [Ian]
==================
14:50:06 [Ian]
1. Draft Finding on Media-Types how do we progress this finding - is it done?
14:50:12 [Ian]
14:50:24 [Ian]
SW: Where are we on this? Perilously close to done?
14:50:30 [Ian]
TB, DC: I thought we were done.
14:50:54 [Chris]
Chris has joined #tagmem
14:51:29 [Ian]
Resolved: Accept finding on Media-Types.
14:51:32 [Ian]
DC: Was resolved 8 April.
14:51:33 [DanCon]
" Resolved:
14:51:33 [DanCon]
* Accept TAG finding uriMediaType-9 (as amended)." --
14:51:48 [Ian]
Action IJ: Publish this as accepted finding.
14:51:58 [Ian]
SW: Correction on DC's comment, that was uriMediaType-9 findings.
14:52:01 [Zakim]
+ChrisL
14:52:03 [TBray]
14:53:08 [Ian]
DC: This thing needs another title.
14:53:36 [Ian]
DC: But I'm not clear we're done with this since I was thinking about something else.
14:53:44 [Ian]
TB: There were grumblings on www-tag, but no loud voices in TAG.
14:53:56 [Ian]
SW: My recollection - three issues tied together. I thought we got closure on 2/3.
14:54:20 [Ian]
NW: I bet grumbling on Namespace-Based Dispatching.
14:55:03 [Chris]
status says "being written" should be "under review" surely
14:55:23 [Ian]
DC: Note that resources don't have mime types, response headers do.
14:55:51 [Norm]
q+
14:56:26 [Ian]
TB: Right, you're not talking about resource here, but message back from server.
14:57:01 [Norm]
q-
14:57:07 [Ian]
NW: I propose removing contentious bit (namespace-based dispatching) and moving to "what does a namespace mean"?
14:57:13 [Ian]
TB, CL: Seconded.
14:57:17 [Chris]
ok, agreed
14:57:19 [Ian]
Resolved:
14:58:04 [Ian]
- Publish as accepted fixing charset sentence, and move to mixedNamespaceMeaning issue.
14:58:08 [Ian]
PC: Agreed.
14:58:09 [DanCon]
PROPOSED: nuke NS section, tweak charset (s/resource/response), accept findings on media types.
14:58:24 [Ian]
Action IJ: Publish finding, move dispatching bit to other issue.
14:58:28 [DanCon]
so RESOLVED.
14:58:35 [Ian]
==================
14:58:41 [Ian]
* "Guidelines For The Use of XML in IETF Protocols" IETF best practices draft requiring URNs for XML namespaces in IETF documents
14:58:45 [Ian]
14:58:55 [Ian]
CL: I sent notes on this:
14:59:22 [Ian]
14:59:33 [Ian]
CL: I said:
15:00:04 [Chris]
"In the case of namespaces in IETF standards-track documents, it would be useful if there were some permanent part of the IETF's own web space that could be used for this purpose. "
15:00:04 [Chris]
Yes, great. Wish we could assign them an action to go do that and say what the base URI is?
15:00:28 [Chris]
for HTTP, that is
15:00:58 [Ian]
TB: Has this draft changed recently?
15:01:03 [DanCon]
"W3C recommended practice" should cite "URIs for W3C namespaces"
15:01:05 [Ian]
SW: I have 15 April on it.
15:01:25 [Ian]
TB: I would bet $100 that when I first read this, pro URN slant was stronger. I may be wrong, though. This version is hard to object to as is.
15:01:48 [Zakim]
-Paul
15:02:04 [Ian]
SW: Is the IETF wrong to mandate URNs for namespace names?
15:02:10 [Ian]
(section 4.5).
15:02:38 [TBray]
q+
15:02:41 [Ian]
DO: I've read through CL's summary. In general, I would say that most of CL's comments are good personal comments but not required to be TAG comments.
15:02:52 [Ian]
DO: I think the TAG should highlight the particular namespace issue.
15:03:14 [Ian]
TB: This has *clearly* been rewritten since I see that some things have been fixed since I first read it.
15:03:16 [Chris]
TB notes this has *clearly* been rewritten yet still says 01.txt
15:03:32 [Ian]
TB: It would be nice if IETF kept around previous versions.
15:03:53 [Ian]
CL: This isn't the primary source.
15:04:02 [Ian]
DC: They start with "00".
15:04:23 [Chris]
dc notes numbering stats at 00.txt
15:04:29 [Chris]
All: Aha!
15:04:39 [Ian]
Resolved: Postponed to allow TAG to reread.
15:04:45 [Ian]
Homework: Read version 01.
15:05:35 [Ian]
CL: I will resort and prioritize my comments for next week.
15:05:37 [Ian]
============================
15:05:42 [Ian]
When to use GET?
15:05:43 [Chris]
ACTION CL to re-sort notes into priority order for next week
15:06:07 [Ian]
whenToUseGet-7:
15:06:15 [Ian]
See SW proposal on when to use Post:
15:06:42 [Ian]
DC: Demoralizing to get hundreds of comments without a proposal for alternative.
15:06:55 [Ian]
SW comments:
15:07:16 [Ian]
DC: I didn't hear disagreement about bad idea to subscribe someone to mailing list as result of GET.
15:07:22 [Stuart]
q?
15:07:35 [Ian]
DO: I proposed s/should/may, or to use GET for browser-centric applications.
15:07:59 [Ian]
NW: I am disappointed if we get down to application level in an arch document.
15:08:40 [Ian]
CL: I agree that in general, we should go for generality. But if we can't get agreement on general points, let's consider important specifics (e.g., browsers).
15:08:45 [Ian]
TB: I proposed a solution:
15:08:52 [Ian]
15:09:13 [Dave]
q+
15:09:23 [Ian]
TB: "
15:09:25 [Ian]
"I propose that for those proportion of SOAP requests that consist of a
15:09:25 [Ian]
service name plus a sequence of name-value-pair arguments, we devise a
15:09:25 [Ian]
simple url encoding.
15:09:25 [Ian]
"
15:09:52 [Ian]
TB: I made this proposal in good faith, even if it had been suggested before.
15:09:58 [Stuart]
ack TBray
15:10:03 [Ian]
DO: I find the suggestion interesting, but I don't think it addresses most peoples' issues.
15:10:26 [Ian]
DO: I think that people who want to use GET for safe methods won't be satisfied. People who are adamantly for POST won't be happy either.
15:10:34 [Zakim]
+??P18
15:10:46 [DanCon]
hmm... as to whether the case when SOAP stuff can be url-encoded being a small number of cases... seems to me it's the big part of the 80/20 bucket. e.g. the hello-world SOAP app, getStockQuote, fits quite neatly
15:10:46 [Ian]
zakim, ??P18 is Paul
15:10:47 [Zakim]
+Paul; got it
15:10:51 [Ian]
zakim, who's here?
15:10:52 [Zakim]
I see Stuart, Norm, DanC, Ian, TBray, DOrchard, Roy, ChrisL, Paul
15:10:59 [Stuart]
q?
15:11:07 [Ian]
ack dave
15:11:09 [Chris]
ack Dave
15:11:10 [TBray]
q+
15:11:22 [Ian]
DC: URL-encoding hasn't picked up any steam.
15:11:38 [Ian]
DC: See comments from Mark Nottingham -
15:11:47 [Ian]
...WG not excited by this before.
15:11:55 [Ian]
TB: But if the TAG is expressing interest in this, that might help.
15:12:52 [Ian]
DO: There are a couple of people in XMLP WG who are interested in this topic. Why is there such a clean disconnect between these two polar views?
15:13:08 [Ian]
DO: I don't think that just saying "you're doing it wrong" addresses the gap in understanding.
15:13:39 [Ian]
DC: I've talked to 5 people XMLP WG and all of them said "Yes, GET would be the more straightforward method for simple applications like stock quotes."
15:13:56 [Ian]
DC: And I hear XMLP WG participants saying "We're not interested in the simple applications."
15:14:06 [Ian]
DO: But we hate the stock quote example.
15:14:19 [Ian]
DO: I'd like to hear how use of POST is actively harmful and how GET would be better.
15:14:27 [Ian]
DC: Paul Prescod, TB gave reasons.
15:14:51 [Ian]
PP's email:
15:14:52 [Chris]
q+
15:15:08 [Stuart]
ack DanCon
15:15:10 [Ian]
DO: Reasons for certain styles of applications have been given. But there are other classes of applications where it's not clear.
15:15:19 [Ian]
DO: I don't think it comes up in practice.
15:15:33 [Ian]
RF: Paul is describing Web applications. The Web Services community is not dealing with Web applications.
15:15:37 [Ian]
DO: I liked RF's posting:
15:16:00 [DanCon]
"urls for everything"??? execpt information available via SOAP services.
15:16:32 [Ian]
RF: Web Services doesn't use URLs for everything. That's the problem. If something uses a URL to identify something makes it a Web application.
15:16:42 [TBray]
q?
15:16:57 [Ian]
RF: Here's the exact principle involved: "URIs should be used to identify all important resources." Web services doesn't do this.
15:17:17 [Ian]
RF: The reason you want to use GET is that it requires URI for identification; that makes it available to other applications on the Web.
15:17:37 [Ian]
DO: I lobbied that part of definition of a Web Service was that it be addressable by URI. That's been accepted as a draft definition.
15:17:44 [Ian]
DC: The price of the stock is not addressable.
15:17:46 [Ian]
q?
15:17:52 [Ian]
ack TBray
15:18:02 [Ian]
TB: DO and I drawing 2 conclusions from same facts.
15:18:24 [DanCon]
hmm... reviewing
looking for what's now considered the meat-and-potatoes applications of SOAP.
15:18:45 .
15:19:12 [Ian]
RF: If the same naming authority, that server can define any URI for that service; better than a service with no URIs into it.
15:19:57 [Ian]
TB: I agree that a large proportion of Web Services transactions may be densely structured, unsafe, etc. I don't see the benefit of going after those. But for the subset of request/response that are safe, let's use URL-encoding.
15:20:21 [Ian]
DO: Did you see MN's response on URL length?
15:20:35 [Ian]
TB: I've been doing this for years; never seen an application break due to URL length.
15:21:13 [Ian]
RF: The overall issue - if URLs tend to be long in a service, then all of the technology between them and the client improves over time. I think it's been at least six years since 256 char limits on URLs.
15:21:31 [Dave]
q+
15:21:34
15:21:39 [Ian]
TB: Any anything you can't pack into a reasonable URL length is probably not good candidate for GET anyway.
15:22:11 [DanCon]
I considered writing up this "if it's long, it's not addressable" and Larry has already given counter-examples: "validation result for this (appended) document?" or... "images like this one?"
15:22:42 [Ian]
q?
15:22:48 [Ian]
ack Chris
15:22:53 [DanCon]
(not counter-examples, exactly, but... er... nevermind)
15:22:55 [Stuart]
Q+
15:23:30 [Ian]
RF: There's no basis for "everything must use GET" in Web architecture. There is for "use an URI for everything that's important".
15:23:42 [Stuart]
ack Dave
15:24:30 [Ian]
DO: I personally have gone to significant effort to harmonize Web services with the Web (use of URIs, use of XML, right use of HTTP). But to find out my efforts have been in vain (still doing the wrong thing) is disappointing.
15:24:51 [Ian]
DO: If we are using URIs wrong, a more problematic area of misunderstanding.
15:25:22 [Ian]
TB: I assert that there are classes of Web Services that are addressable by URI and accessible by GET. Web services (SOAP) today does not enable that. There is a low cost solution to address this.
15:25:58 [DanCon]
hmm... after scanning the SOAP primer, I don't see any discussion of mapping Java/Perl/python method calls to SOAP calls. did 'object access' go away somewhere?
15:25:59 [Ian]
DO: TB has said that to hit the 80/20 point, it would be useful to have this particular feature. I am not saying this is uninteresting. I just don't think it's a principle of the Web.
15:26:14 [Ian]
TB: I would argue that first principle of Web is that things have URIs and bet GETable.
15:27:05 [Ian]
Refer to finding -9:
15:27:11 [Ian]
" * All important resources should be identifiable by URI.
15:27:11 [Ian]
"
15:27:27 [Stuart]
ack Stuart
15:27:42 [Ian]
DO: I think we are allowing Web Services to be addressable by URI.
15:27:56 [Ian]
DC: The results are addressable in the case of GET but not of POST.
15:29:14 [Ian]
[DC talking about SOAP features]
15:29:22 [TBray]
Ian: DO: TB has said that to hit the 80/20 point, it would be useful to have this particular feature. I am not saying this is uninteresting. I just don't think it's a principle of the Web.
15:29:22 [TBray]
Ian: TB: I would argue that first principle of Web is that things have URIs and bet GETable.
15:29:22 [TBray]
Ian: Refer to finding -9:
15:29:22 [TBray]
Ian: " * All important resources should be identifiable by URI.
15:29:25 [TBray]
Ian: "
15:29:26 [TBray]
DanCon q+
15:29:29 [TBray]
Zakim sees Stuart, DanCon on the speaker queue
15:29:56 [TBray]
Oops... had a little IRC error there
15:29:56 [Ian]
[DC comments on Primer]
15:30:13 [Ian]
PC: I don't think that the primer has ever used the term "java" or described the scenario DC described.
15:30:46 [Ian]
DC: The scenario is there in the larger community [Scribe didn't get scenario, but about querying to find out about safe methods]
15:31:05 [TBray]
q+
15:31:44 [Ian]
PC:.
15:31:57 [Stuart]
ack DanCon
15:32:30 [Ian]
DO: I hear people saying coarse-grain interactions more useful; avoid a multitude of back-and-forth interactions.
15:32:57 [Ian]
PC: Most of these document-centered objects are synchronous. Typically you want your web service to be asynch.
15:32:59 [TBray]
q?
15:33:14 [Ian]
DC: Summarizing - taking your API and hitting the button to create a Web Service is apparently no longer the right thing to do.
15:34:04 [Ian]
TB: As an XML editor, I am profoundly uninterested in Web Service community's predictions about how the tools they are producing will be used.
15:34:17 [Norm]
"No one expects the Spanish Inquisition"
15:34:28 [Ian]
TB: My personal opinion is that a low-rent RPC request/response based on SOAP wrappers will be widely used.
15:34:35 [Dave]
norm, lol
15:34:45 [Ian]
TB: ...but whether widely used or not widely used, why isn't a good thing to expose as a URI.
15:35:20 [Ian]
SW: Are we going to say anything about the use of POST to do safe things?
15:35:24 [Ian]
DC: That seems in order.
15:35:58 [Ian]
Action DC: Write more on whenToUseGet.
15:36:12 [Ian]
DC: Look at it more as "make things addressable"
15:36:18 [Ian]
============================
15:36:21 [Chris]
to concentrate on "make things addressable"
15:36:36 [Ian]
------------------
15:37:00 [Ian]
Architecture Document, Status, Discussion
15:37:10 [Ian]
IJ: Not much progress due to ongoing work on Process Doc and UAAG 1.0.
15:37:54 [Ian]
PC: What about status of this doc at AC meeting?
15:38:06 [Ian]
IJ: TBL's slides point more to categorization than arch document.
15:38:21 [Ian]
PC: Should we get AC to read this before the meeting?
15:38:25 [Ian]
RF: Seems unlikely.
15:38:54 [Stuart]
q?
15:39:10 [Stuart]
ack TBray
15:40:01 [Ian]
IJ: AC agenda will be sent out soon.
15:40:23 [Ian]
PC: I think the agenda is too late.
15:41:34 [Ian]
SW: What about feedback on other pieces to go in arch document?
15:43:16 [Ian]
Looking at: Current State slide
15:44:04 [Ian]
PC: Point to arch doc IJ has been working on?
15:44:09 [Ian]
IJ: I don't think it's mature enough yet.
15:44:38 [Ian]
IJ: I intend to make progress on this this week.
15:44:55 [Ian]
[PC may not be at next week's meeting.]
15:45:10 [Ian]
PC: Will there be a monthly summary end of April?
15:45:13 [Ian]
IJ: Yes, I intend to.
15:46:08 [Ian]
Next meeting: 29 April.
15:46:42 [Ian]
Adjourned.
15:46:46 [Zakim]
-ChrisL
15:46:51 [Zakim]
-DanC
15:46:54 [Zakim]
-Paul
15:46:55 [Zakim]
-Ian
15:47:00 [Ian]
RRSAgent, stop
|
https://www.w3.org/2002/04/22-tagmem-irc
|
CC-MAIN-2016-18
|
refinedweb
| 3,997
| 82.75
|
i18l for buttons and labels, etc
i18l for buttons and labels, etc
I understand the following statement from the documentation on Localizing your own app
"Ext JS doesn't enforce any particular approach to localization. It's only the framework itself that uses the approach outlined here. Feel free to localize your app in whichever way feels best for you"
So, for example, lets say I have four buttons and in my SA, I have set the text for each as, "acknowledge", "bar", "clear", "refresh" for example.
When I deploy my application I see the specified text in the buttons. Now say I want to display the button text in German, French or Chinese.
At this point I at a complete loss as to how to do this since SA does not seem to have a config option or something that allows me to specify my own locale translations for text in buttons, labels, models, etc.
How might I go about doing this, is there a standard way to do this, any documentation or tutorials on this.
Hi,
I'll try to point you in the direction I took when localizing my project (that I am now porting to Ext JS 4.1 in SA). It's not a turn-key solution for your project.
The trick is to start localization from the very beginning. I put all my strings in a js-file (en.js) that lives in the same namespace as the application (app namespace UP8). The en.js file contains:
Code:
Ext.ns('UP8'); UP8.lang = { param: function(s, r) { return Ext.String.format(s, r); }, param2: function(s, r1, r2) { return Ext.String.format(s, r1, r2); }, param3: function(s, r1, r2, r3) { return Ext.String.format(s, r1, r2, r3); }, CertificateID: 'Certificate ID:', CertValidated: 'Validated on:', CertIssued: 'Certificate Issued:', TitleCertValFailed: 'Validation Failed', MsgCertValFailed: 'The Certificate ID could not be found in the database', Firstname: 'Firstname', Lastname: 'Lastname', Company: 'Company', City: 'City', Email: 'Email', Address1: 'Address (line 1)', Address2: 'Address (line 2)', PostalCode: 'Postal code', .... }
In SA I use the afterrender event in things to localize:
Code:
function onButtonAfterRender(abstractcomponent, options) { abstractcomponent.setText(UP8.lang.CRL_RedeemButton); }
Code:
abstractcomponent.columns[0].setText(UP8.lang.CRL_HeaderBalance); abstractcomponent.columns[1].setText(UP8.lang.CRL_HeaderDescription); abstractcomponent.columns[2].setText(UP8.lang.CRL_HeaderLatestTrans);
If you have additional specific questions, I'll try answer them.
Good luck,
/Mattias
|
http://www.sencha.com/forum/showthread.php?243452-i18l-for-buttons-and-labels-etc&s=13799b2472de06f690bcc1062ec568f2&p=893327
|
CC-MAIN-2014-15
|
refinedweb
| 396
| 55.44
|
Complex SQL IF statement for an SSIS package
I need to send letters to the primary member of a health club regarding the balances of each of the minors under their membership that are the age of 21 or under. There are some minors that have a different address than the primary member and there are some that don’t have any address listed in the table so I need the primary member's address for these minors. One of the tables that I am using has the gym membership numbers (the same membership number is issued to all names on an account) member names, relationship (primary member, secondary member(spouse), minors, dob, and age. The other table has the membership numbers and the addresses. I will use a Merge join in SSIS to combine the data of these two tables. Any suggestions are appreciated.
See also questions close to this topic
-.
- Microsoft SQL Server Login Stuck
I have a Microsoft server 2012 running a Microsoft SQL server 2017 express database. I am trying to log in through SQL Server Management on a remote machine but the log in loads forever and gives no error.
If I put in the wrong username and password I do get an error that the username and password is wrong and the error shows in the SQL server log so it does seem to be making some type of connection.
When I connect on the local server it connects right away. I have TCP enabled in the server configuration.
Does anyone know why this hang might be happening?
- Create Setup file for WPF Project
I have designed an application for my client in Visual Studio 2017 (.Net Framework 4.6.1.) using Sql Server Standard version and Crystal Reports. Now I want to create a setup file for client.
- Do I have to install Sql Server or Sql Server Express for client?
- Do I have to install Crystal Report Runtime for client?
I've read lots of similar questions. What is the best way for doing this? Thanks.
- How do I use DTS.Events.FireInformation() in SSIS Script Task while handling WinSCPnet.dll FileTransferProgress?
I have a Script Task in an SSIS (2008) package that downloads files from a remote FTP server to a local directory. The Script Task is written in C# 2008, and uses WinSCPnet.dll. Using examples from WinSCP's documentation, I came up with the script below. The script functions correctly to download the files, but all the file success/failure messages are held until the entire script completes, and then all the messages are dumped at once. File progress is not displayed at all using
Console.Write(), and trying to use
Dts.Events.FireInformation()in
SessionFileTransferProgressgives me
Error: "An object reference is required for the non-static field, method, or property Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase.Dts.get"
Is there a way I can use the DTS.events.Fire* events to display file progress information as it happens, and file completion status after each file?
Script:
/* Microsoft SQL Server Integration Services Script Task Write scripts using Microsoft Visual C# 2008. The ScriptMain is the entry point class of the script. */ using System; using Microsoft.SqlServer.Dts.Runtime; using Microsoft.SqlServer.Dts.Tasks.ScriptTask; using System.AddIn; using WinSCP; namespace ST_3a1cf75114b64e778bd035dd91edb5a1.csproj { [AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")] public partial class ScriptMain : VSTARTScriptObjectModelBase { public void Main() { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = (string)Dts.Variables["User::FTPServerName"].Value, UserName = (string)Dts.Variables["User::UserName"].Value, Password = (string)Dts.Variables["User::Password"].Value }; try { using (Session session = new Session()) { // Will continuously report progress of transfer session.FileTransferProgress += SessionFileTransferProgress; session.ExecutablePath = (string)Dts.Variables["User::PathToWinSCP"].Value; // Connect session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult = session.GetFiles( (string)Dts.Variables["User::ExportPath"].Value , (string)Dts.Variables["User::ImportPath"].Value , false , transferOptions ); // Throw on any error transferResult.Check(); // Print results bool fireAgain = false; foreach (TransferEventArgs transfer in transferResult.Transfers) { Dts.Events.FireInformation(0, null, string.Format("Download of {0} succeeded", transfer.FileName), null, 0, ref fireAgain); } } Dts.TaskResult = (int)DTSExecResult.Success; } catch (Exception e) { Dts.Events.FireError(0, null, string.Format("Error downloading file: {0}", e), null, 0); Dts.TaskResult = (int)DTSExecResult.Failure; } } private static void SessionFileTransferProgress(object sender, FileTransferProgressEventArgs e) { //bool fireAgain = false; // Print transfer progress Console.Write("\r{0} ({1:P0})", e.FileName, e.FileProgress); /*Dts.Events.FireInformation(0, null, string.Format("\r{0} ({1:P0})", e.FileName, e.FileProgress), null, 0, ref fireAgain);*/ // Remember a name of the last file reported _lastFileName = e.FileName; } private static string _lastFileName; } }
- SSIS - Possible to execute the same package multiple times simultaneously without variables clashing?
Using the SQL Server Business Intelligence Development Studio, I'm trying to execute a parent package( which calls a child package) 4 times, all at the same time and all with different parameters/variables.
The parent packages are in a ForEach loop container where different variables are being assigned. Once I run all 4 parent packages instances, I am running into the issue where the variables set for one of the instances "
clashes" with the other instances, causing the variables for one instance to be used in the other instances as well.
Is there any way to run the same parent package with different variables in parallel without having the variables "clash"?
- could not retrieve tables in OLE DB Source Editor while creating a new SSIS package
In a existing SSIS project I need to create a new package with existing OLEDB connection manager, when i create a OLE DB source editor i couldn't see the list of tables in that database as shown below.
things I done ;
checked the 'Test connection' in connection manager
I disabled 'Work offline' option under SSIS > Work Offline Still issue persist.
Please can someone shed some light on this, thanks in advance.
|
http://quabr.com/48757703/complex-sql-if-statembent-for-an-ssis-package
|
CC-MAIN-2018-34
|
refinedweb
| 983
| 50.23
|
In this video tutorial I will cover how to make menus and dialog popups. I’ll specifically cover laying out menus in main.xml, DialogFragment, AlertDialog, Action Bars, Option Menus and more.
If you missed the first videos they are here How to Make Android apps 1, 2, and 3. Definitely watch them first. All of the code follows the video below. It is heavily commented to help you learn.
If you like videos like this, it helps me if you share on Google Plus with a click here
Code from the Video
main.xml
<menu xmlns: <!-- The Options or Overflow menu is located in the upper right hand corner for devices running Android 4.0 and above. To make this menu use the menu element and define each option in an item element. orderInCategory defines the order of appearance showAsAction defines that the item should appear on the action bar if there is enough room or not. If you want to support the Action Bar for versions of Android below 2.1 use your apps name space instead of android so you can use import android.support.v7.app.ActionBarActivity; Use withText to show the title in the action bar icon defines a icon to use for the item checkableBehavior is used to allow the user to select a single or all items when the menu items are surrounded by group --> <group android: <item android: <item android: </group> </menu>
MainActivity.java
package com.newthinktank.menuexamples2.app; import android.app.DialogFragment; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // This method creates the menu on the app @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } // Called when a options menu item(); // We check what menu item was clicked and show a Toast if (id == R.id.action_settings) { // A DialogFragment is a Fragment you can place over top // the current Activity. A Fragment is like an interface // block that you can place into an Activity. // The FrgamentManager allows you to interact with the // Fragment DialogFragment myFragment = new MyDialogFragment(); myFragment.show(getFragmentManager(), "theDialog"); return true; // If exit was clicked close the app } else if (id == R.id.exit_the_app) { finish(); return true; } return super.onOptionsItemSelected(item); } }
MyDialogFragment.java
package com.newthinktank.menuexamples2.app; // This will be used to create a dialog window import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; // If you get an error that the minimum must be 11, change the minimum in the manifest // and also change it in build.gradle // To generate the onCreateDialog() right click on DialogFragment and Generate and // select onCreateDialog() public class MyDialogFragment extends DialogFragment{ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // We build the dialog // getActivity() returns the Activity this Fragment is associated with AlertDialog.Builder theDialog = new AlertDialog.Builder(getActivity()); // Set the title for the Dialog theDialog.setTitle("Sample Dialog"); // Set the message theDialog.setMessage("Hello I'm a Dialog"); // Add text for a positive button theDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getActivity(), "Clicked OK", Toast.LENGTH_SHORT).show(); } }); // Add text for a negative button theDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getActivity(), "Clicked Cancel", Toast.LENGTH_SHORT).show(); } }); // Returns the created dialog return theDialog.create(); } }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns: <uses-sdk android: <application android: <activity android: <intent-filter> <action android: <category android: </intent-filter> </activity> </application> </manifest>
Hi derek ,
you have posted so many android tutorials which are very greatly explained in details. I had seen some of them but as i am fresher i just want to know that is there sequence of those tutorials so that i can start it from the 1st tuts, if it is please tell me how the sequence is..?
thank you in advance. hope so you will reply asap.
thanks once again.
If you don’t think you are 100% ready for Java Android watch my Android for beginners tutorial. It starts simple, but it will get you comfortable with making Java Android apps by the end. I think it is one of the best tutorials I have ever made.
If you are 100% with Java and want to learn while making apps watch my Android Development tutorial.
if you want the most up to date tutorial and you’re willing to wait while I make it watch my how to make Android apps tutorial.
Hi Derek, I love your tutorial. But something happen when I tried to run the app in the kit kat version, the dialog appears without no text, and the buttons “OK” and “Cancel” don´t appear too. Do you know something about it? And what is the way to solve this problem. Thanks.
Hi Paula, I’m guessing there must me missing text. I’m running the apps with Kit Kat as well. Try comparing your code to mine using diffnow.com and you’ll find the error.
Hi Derek
In this tutorial I found these strange results hopefully you can shed some light on them:
1. When running this app on the emulator the fragment did not look right
Emulation Image
The emulator was running Android 4.2.2 ARM
2. When running this same code on my HTC One X i got the following result
Device Image
Thank you for these videos
Hi Kevin,
It looks like a strange emulator issue. I’m not sure why that would happen, since I’ve never experienced that. All I can suggest is a re-install.
Another great video.
I had the same problem as Paula (it must be a name thing) where the text and buttons wouldn’t show.
Changing:
return super.onCreateDialog(savedInstanceState);
to:
return theDialog.create();
in MyDialogFragment.java fixes this. This wasn’t shown in the video though.
Thanks Derek.
Thanks for helping out others 🙂
Thanks for your help, Paul. Great tutorials, Derek!
Thanks for your help, Paul. Great tutorials, Derek!
I had the same problem, this fixed it perfectly. Is this possibly because the Intended SDK was 21?
Android studio does that automatically for me so I’m just guessing.
Yes use version 19 for now.
Gracias Paul. Works perfectly
Hello Derek ,thank you so much for the tutorials..
I am using Max api verion of 21 (lollipop) and was having problems with getfragmentmanager , had to replace
with
in MainActivity.java
Ones again , thank you so much for all these wonderful tutorials and making new tutorials with latest updates – developing for anything with Intellij rocks ..It is just so much more efficient , more thinking less chore
You’re very welcome 🙂 I have only dabbled a bit with Lollipop. I’ll have to look into that. Thank you for telling me.
I face the same problem of blank dialog, despite all corrections the message in dialog doesn’t show. I tried both on Emulator and Device it doesn’t work. Code is exactly same as on this page. What might be missing, any help.
Thanks & regards,
TC
What errors are you seeing in the LogCat panel?
|
https://www.newthinktank.com/2014/06/make-android-apps-4/
|
CC-MAIN-2018-09
|
refinedweb
| 1,235
| 51.85
|
MATLAB Newsgroup
(roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson))
In article <g6vscv$91j$1@fred.mathworks.com>,
David Reed <dreed@mitre.org> wrote:
If you know exact line numbers, use counts on the textscan()
to read up to that point, then fgetl() to read the next
line (and discard it), then textscan() as much more as you can, etc..
If you don't know exact line numbers and can only tell by the
different formatting, you can either process a line at a time
(using fgetl to get the line and then one of the several parsing
routines), or you can read the entire file at once as a string,
delete the lines that give the problems, then textscan() the
string variable. (You can put a string in, in place of a fid).
--
"I was very young in those days, but I was also rather dim."
-- Christopher Priest
Hi,
I've a nice script for evaulation of such files.
%%%--------------------- START %%%%%%%%%%
fid=fopen('filename.dat') ; % the original file
fidd=fopen('new filename.dat') ; % the new file
while ~feof(fid) ; % reads the original till last line
tline=fgets(fid) ; %
if "CONDITION STATEMENT THAT REPRESENTS THE LINES YOU
WANT TO DELETE"
else
fprinft(fidd,tline) ;
end
end
fclose all
%%%--------------------- END %%%%%%%%%%
This is a simple script lets you to evaulate each line and
take action.
Ahmet Anil Dind
"David Reed" <dreed@mitre.org> wrote in message
<g6vscv$91j$1@fred.mathworks.com>...
>
I don't know if this applies to your problem, but just as a
hint:
txt2mat from the file exchange has the option to ignore
lines in the text file that can be identified by one or more
distinct strings ('BadLineString', see the doc). It can also
import the whole file line-by-line, letting you sort out the
critical lines afterwards. Note that it is made for an
import of data resulting in a single numeric matrix. If you
need advice with txt2mat, you may contact me (the author)
via the file exchange 'Contact author' button.
Regards
Andres
"AHMET ANIL DINDAR" <adindar@iku.edu.tr> wrote in message <g7139v$8mp$1@fred.mathworks
AAD,
GREAT JOB, thank you. This is exactly what I was looking.
|
http://www.mathworks.com/matlabcentral/newsreader/view_thread/173648
|
CC-MAIN-2015-22
|
refinedweb
| 365
| 71.95
|
PostLastCall
From SPARQL Working Group
Actions tracking for Post Last Call.
Contents
RDF-WG possible impact points
- Simple literals: simple literals are xsd:string in the abstract syntax
- Plain literals with language tags
- Graph identification
- Turtle syntax
Query
Necessary before 2LC
- Sort out scope rules and "BGP BIND"
- Grammar
- Consider ORDER BY count(*) (supported in SQL, just need to remove restriction in SPARQL)
- Change grammar note 13 (which wasn't in 1LC at all)
- "For each expression E in SELECT and each HAVING(E) in Q" ==> "For each expression E in SELECT and each HAVING(E) and each ORDER BY(E) in Q"
- Note in 2LC changes.
- Put "Aggregate" in BuiltInCall (HAVING requires unnecessary brackets at the moment)
- ConstructTemplate == TriplesTemplate
- See SPARQL_Namespaces : Update page at the namespace URI of SPARQL functions
- IRIs for all functions (namespace document ?)
- deal with escaping rules (red box)
- LC pub changes: msg
Not Andy:
- Check reformatting and edits in "17.4 Operator and Function Definitions"
Steve:
- Make sure it says functions and aggregates generating errors can be overridden (present in SPARQL 1.0 ; unclear in SPARQL 1.1 Query) (Steve)
Completed:
- Prepare for RDF 1.1
REGEX, REPLACE to take all string-like forms as first argument (includes literals with language tag). Check for others Datatype(?x) to return rdf:langString on literals with a language tag DATATYPE: Note change from SPARQL 1.0. (mark "at risk") Reformat function prototypes - reenable CSS Add STRAFTER, STRBEFORE, REPLACE Remove SHA224 Update OWL reference (from comment IH-2) Function SUBSTR says "xsd:integer" : should say including derived types of integer. Grammar fix : ASK with GROUP BY, HAVINGASK now takes solution modifiers. Grammar notes need to have a point about aggregates and location. check CONSTRUCT WHERE short form. Sections 11 and 12: remove algebra. See CommentResponse:IH-1 (Steve)
Desirable to do (may not happen ; time dependent)
- Move string literals argument type sections to near defn of simple literal.
- (unlikely) Query forms CONSTRUCT, ASK
Update
Use consistent presentation of GS in semantics 2011OctDec/0065DONE Bug fixes on Definition in 4.2.5 msg- DONE What to do with the sentence suggested by comment DB-12, see also: msgDONE: sentence included. Description and defn of LOAD differDONE: addressed with the rewording proposed in msg1, msg2. AP: I tend to interpret this change as non-LC critical, since the definitions haven't been changed, but only the inconsistent written text. Todo: remove @@@ at (editorial)
- LC pub changes: msg
Link to needs to be changed to also check for other links to the old spec! ( editorial) Olivier's review remove AT RISK note for COPY, ADD, MOVE
Service Description
- Edits in CommentResponse:DB-2
SPARQL 1.1 Graph Store HTTP Protocol
JSON result format
- The JSON Note used "typed-literal"; the spec change/fixed that but should explicitly note it.
|
http://www.w3.org/2009/sparql/wiki/index.php?title=PostLastCall&oldid=4112
|
CC-MAIN-2016-18
|
refinedweb
| 468
| 52.19
|
RE: Sorting lists in .Net - why it sucks
- From: Family Tree Mike <FamilyTreeMike@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 25 Jan 2008 07:26:00 -0800
"nightwatch77" wrote:
You should create your own class that encapsulates a DateTime object and
implements IComparable. You just need to handle the equals case as you see
fit. Here is an example of what I mean:
namespace SortedListTest
{
public class ComparableDateTime : IComparable
{
private DateTime mDT;
public int CompareTo ( object obj )
{
if (mDT.Ticks < ((ComparableDateTime) obj).mDT.Ticks) return -1;
return 1;
}
public ComparableDateTime ( long milliseconds )
{
mDT = new DateTime ( milliseconds );
}
}
class Program
{
static void Main ( string [ ] args )
{
SortedList<ComparableDateTime, string> msl;
msl = new SortedList<ComparableDateTime, string> ();
msl.Add ( new ComparableDateTime ( 123456786 ), "string one" );
msl.Add ( new ComparableDateTime ( 123456786 ), "string two" );
Console.Out.WriteLine ( );
foreach (string s in MySortedList.Values)
{
Console.WriteLine ( s );
}
Console.Out.WriteLine ( );
Console.ReadLine ();
}
}
}
..
- References:
- Sorting lists in .Net - why it sucks
- From: nightwatch77
- Prev by Date: Re: Sorting lists in .Net - why it sucks
- Next by Date: Re: Properties vs. Fields
- Previous by thread: Re: Sorting lists in .Net - why it sucks
- Next by thread: Re: Sorting lists in .Net - why it sucks
- Index(es):
|
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.general/2008-01/msg00392.html
|
crawl-002
|
refinedweb
| 191
| 60.51
|
26 August 2008
Flash designers show off your work
words by
flanture
at
4:16 AM
0
Links to this post
Labels: business, community, flash, flash jobs, web development, web services, web2.0
22 August 2008
Flex Delivers Video Microblogging App
You might have been in position to answer simple question "what are you doing" a few times? How about answering this question by recording a short 12 s video? This is exactly idea behind new video microblogging service 12seconds.tv.
Service is still in alpha, so few new features might lurking around the corner. For now, you are invited to record your video message via web cam, mobile phone or your washing machine if it supports this feature. You have an option to name your video, tag it, locate it and post it. You will also get a unique e-mail address to send video directly from your phone (or washing machine) and it will be published on your 12seconds page. You can also configure your Twitter account with it and service will twit for you any new uploaded message.
If you are familiar with my recent article about AIR based Twitter application TweetDeck and you are fan of same, you will love to read that this powerful Twitter desktop client will support 12Seconds service. And yes, like everything related to web video, this service is also Flex based app.
I have 10 invites for my precious readers, giving them away FIFO style :) Just leave a comment with your e-mail.
_____
words by
flanture
at
1:30 PM
0
Links to this post
Labels: air, flex, fun, links, news, RIA, twitter, video, web development, web services, web2.0
20 August 2008
AS3 code libraries list
I was just reading about degrafa framework and how it is really great when big boys support open source communities when run into this huge list of AS3 code libraries which includes:
- AS3 3D engines
- 3D Game Engines
- AS3 3D Physics (not phsics) engines
- AS3 Animation Tweening Kits
- AS3 2D Physics Engines
- AS3 Security
- AS3 Audio Libraries
- AS3 Particle Systems
- OOP Frameworks
- more APIs and Libraries
Extremely useful.
.
words by
flanture
at
6:31 AM
2
Links to this post
Labels: 3D flash, actionscript, AS3.0, code
12 August 2008
Adobe Flex Themes Cool Awards Contest
However, if you think it's too early for Gumbo and Flex SDK nightly builds, take a look at "Skin to Win Challenge" contest at ScaleNine, sponsored by Adobe and EffectiveUI. You are required to create a custom theme, compatible with Flex 3. Prizes are cool, MacBook Air, Adobe CS3 Master Suite, Adobe Flex Builder 3 Pro, tickets to Adobe MAX.
Themes will be judged for visual design (50%), overall quality (25%), innovation and uniqueness (25%). Deadline is October 10th 2008.
Can you do better than Darkroom?
words by
flanture
at
12:16 PM
0
Links to this post
Labels: adobe, competitions, examples, flex, fun, FXG, gumbo, themes
08 August 2008
Gumbo, FXG example
While Gumbo is still in active development, Flex 3.1 should be out this month and Flex 3.2 is planned for fall 2008. Gumbo will introduce new language features and different set of components that will make some existing Flex 3 components absolute. FXG is new document format and compiler will treat this format as external asset. New tags in FXG and MXML 2009 will be < Private >, < Library >, < Declarations >, < Definition >, < DesignLayer > and < Reparent >.
Instead of current namespace, Gumbo will introduce new language namespace, but Gumbo will also recognize old namespace too. Some older tags like Binding, Script, Style and others will loose mx: prefix. But, built-in types like Array, Number etc will also loose it’s prefix.
Full details on MXML 2009 and FXG, but also if you wish to see it, here is example : Skinning a button in Flex 4 using FXG.
words by
flanture
at
4:33 AM
Links to this post
Labels: adobe, code, components, examples, flex, flex examples, FXG, gumbo, mxml, news, open source
01 August 2008
AIR based Twitter application TweetDeck
There are tons of Twitter clients, good ones, but this new one is special in many ways. I’m talking about TweetDeck. It’s written in Adobe AIR, which is one of the reasons I’m writing about it. Still in deep beta, current version is v0.16.1 means that you can expect bugs and reduced functionality, but don’t let this turn you away. New updates are regular and improvements are really great. I think that it’s only a question of time when this client will become the must-have tool.
Last one and my favorite is SEARCH column. This one allows you to filter all global (all twitts) or local (of people you follow) based on search term. Not a revolutionary concept, but extremely useful when you can have few search columns inside single application. Consequences of this are very powerful. Imagine yourself watching trends in real time! Well, now you have the tool to do just that! Just for fun you can try few searches: web2.0, help needed, new book, etc. Cool, right?
To be honest, I was little scared when I saw that monolith black full screen of TweetDeck and right that minute I wished for second monitor. However, next version will include skins and int character support. There is more to this app, but I will mention just another cool feature. TweetDeck works both online and offline. App uses database to store messages when Twitter is down (no more whale image) and updates itself when available. Oh, yeah, just one more. It uses several short URL web services: bit.ly, eweri, is.gd, lin.cr, snipurl and tinyurl for now and have TwitPic integration. I could go on with features, but it’s only v0.16.1. Great job, Iain.
words by
flanture
at
1:06 PM
0
Links to this post
Labels: adobe, air, twitter, web development, web services, web2.0
|
http://flanture.blogspot.com/2008/08/
|
CC-MAIN-2019-04
|
refinedweb
| 995
| 71.55
|
0
Hi pros and experts. I am experiencing some trouble in doing up a code which could evaluate the input into the different data types.
What i managed to acheived is to read a file and its content.
I used strtok to break the string into various 'tokens'.
Now the problem is how do i differentiate the tokens into the different data types. I tried using 'isdigit' and 'atoi' to no avail. help pls.
For example contents of 'myfile.txt' as follow:
12 43 + - = / -9ya -300
the program should print the output as
12 is a number. 43 is a number. + is a operator. - is a operator. / is a operator. -9ya is invalid. -300 is a number.
The code i managed to acheived so far is as follows:
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int main() { FILE * pFile; char string [100]; char *tokenPtr; int i; pFile = fopen ("myfile.txt" , "r"); if (pFile == NULL) perror ("Error opening file"); else { fgets (string , 100 , pFile); puts (string); tokenPtr = strtok( string, " "); while( tokenPtr != NULL ){ printf("%s\n",tokenPtr ); tokenPtr = strtok( NULL, " "); } fclose (pFile); } return 0; }
Any help is deeply appreciated.
Edited by happygeek: fixed formatting
|
https://www.daniweb.com/programming/software-development/threads/30456/pls-help-with-c-code-evaluating-data-types
|
CC-MAIN-2018-13
|
refinedweb
| 197
| 79.77
|
Opened 8 years ago
Closed 8 years ago
#3850 closed Feature Requests (invalid)
[Boost.tracer] library request
Description
[Boost.tracer] library request is founded on a desire to trace some statistics about program execution.
The sample program below demonstrates these statistics.
Sample program file:
#include <tracer.h> void foo() { TRACE_LIFETIME; usleep(rand() % 100000); } int main() { TRACE_LIFETIME; for(int i = 0; i < 100; ++i) foo(); }
Produced log file:
All the program time: 05265686 us (micro secs) TRACE POINT: Function: int main() Calls: 0000000001 times Average T between calls: 0000000000 us Average life T: 0005264459 us File: main.cpp Line: 00000009 TRACE POINT: Function: void foo() Calls: 0000000100 times Average T between calls: 0000051665 us Average life T: 0000052606 us File: main.cpp Line: 00000004
Comment:
TRACE_LIFETIME is a MACRO that traces some scope statistics, namely:
"Function" - the function name where the scope is;
"Calls" - number of entries into this scope;
"Average T between calls" - average time period between "Calls";
"Average life T" - average time spent in this scope.
Conclusion:
I think it is reasonable to introduce this trace functionality into (for example) boost::tracer namespace. I had wrote tracer.h and tracer.cpp source files and I wish Boost community to consider them.
Thank You.
Attachments (0)
Change History (2)
comment:1 Changed 8 years ago by
comment:2 Changed 8 years ago by
I propose to close this ticket, as it is a feature request to no library.
Please bring this to the Boost developers mailing list. The trac system is intended for existing libraries.
|
https://svn.boost.org/trac10/ticket/3850
|
CC-MAIN-2018-26
|
refinedweb
| 255
| 63.49
|
parrot MIME::Base64 FixedIntegerArray: index out of bounds!
Ronaldxs created the following parrot ticket #813 4 months ago:
“Was playing with p6 MIME::Base64 and utf8 sampler page when I came across this. It seems that the parrot MIME Base64 library can’t handle some UTF-8 characters as demonstrated below.”
.sub go :main load_bytecode 'MIME/Base64.pbc' .local pmc enc_sub enc_sub = get_global [ "MIME"; "Base64" ], 'encode_base64' .local string result_encode result_encode = enc_sub(utf8:"\x{203e}") say result_encode .end
FixedIntegerArray: index out of bounds!
current instr.: 'parrot;MIME;Base64;encode_base64'
pc 163 (runtime/parrot/library/MIME/Base64.pir:147)
called from Sub 'go' pc 11 (die_utf8_base64.pir:8)
This was interesting, because parrot strings store the encoding information in the string. The user does not need to store the string encoding information somewhere else as in perl5, nor have to do educated guesses about the encoding. parrot supports ascii, latin1, binary, utf-8, ucs-2, utf-16 and ucs-4 string encodings natively.
So we thought we the hell cannot parrot handle simple utf-8 encoded strings?
As it turned out, the parrot implementation of MIME::Base64, which can be shared to all languages which use parrot as VM, stored the character codepoints for each character as array of integers. On multibyte encodings such as UTF-8 this leads to different data held in memory than a normal multibyte string which is encoded as the byte buffer and the additional encoding information.
Internal string representations
For example an overview of different internal string representations for the utf-8 string “\x{203e}”:
perl5 strings:
len=3, utf-8 flag, "\342\200\276" buf=[e2 80 be]
parrot strings:
len=1, bufused=3, encoding=utf-8, buf=[e2 80 be]
The Unicode tables:
U+203E ‾ e2 80 be OVERLINE
gdb perl5
Let’s check it out:
$ gdb --args perl -e'print "\x{203e}"' (gdb) start (gdb) b Perl_pp_print (gdb) c (gdb) n .. until if (!do_print(*MARK, fp)) (gdb) p **MARK $1 = {sv_any = 0x404280, sv_refcnt = 1, sv_flags = 671106052, sv_u = { svu_pv = 0x426dd0 "‾", svu_iv = 4353488, svu_uv = 4353488, svu_rv = 0x426dd0, svu_array = 0x426dd0, svu_hash = 0x426dd0, svu_gp = 0x426dd0, svu_fp = 0x426dd0}, ...} (gdb) p Perl_sv_dump(*MARK) ALLOCATED at -e:1 for stringify (parent 0x0); serial 301 SV = PV(0x404280) at 0x4239a8 REFCNT = 1 FLAGS = (POK,READONLY,pPOK,UTF8) PV = 0x426dd0 "\342\200\276" [UTF8 "\x{203e}"] CUR = 3 LEN = 16 $2 = void (gdb) x/3x 0x426dd0 0x426dd0: 0xe2 0x80 0xbe
We see that perl5 does store the utf-8 flag, but not the length of the string, the utf8 length (=1), only the length of the buffer (=3).
Any other multi-byte encoded string, such as UCS-2 is stored differently. We suppose as utf-8.
We are already in the debugger, so let’s try the different cmdline argument.
(gdb) run -e'use Encode; print encode("UCS-2", "\x{203e}")' The program being debugged has been started already. Start it from the beginning? (y or n) y Breakpoint 2, Perl_pp_print () at pp_hot.c:712 712 dVAR; dSP; dMARK; dORIGMARK; (gdb) p **MARK $3 = {sv_any = 0x404b30, sv_refcnt = 1, sv_flags = 541700, sv_u = { svu_pv = 0x563a50 " >", svu_iv = 5651024, svu_uv = 5651024, svu_rv = 0x563a50, svu_array = 0x563a50, svu_hash = 0x563a50, svu_gp = 0x563a50, svu_fp = 0x563a50}, ...} (gdb) p Perl_sv_dump(*MARK) ALLOCATED at -e:1 by return (parent 0x0); serial 9579 SV = PV(0x404b30) at 0x556fb8 REFCNT = 1 FLAGS = (TEMP,POK,pPOK) PV = 0x563a50 " >" CUR = 2 LEN = 16 $4 = void (gdb) x/2x 0x563a50 0x563a50: 0x20 0x3e
But we don’t see the UTF8 flag in encode(“UCS-2″, “\x{203e}”), just the simple ascii string ” >”, which is the UCS-2 representation of [20 3e].
Because ” >” is perfectly representable as non-utf8 ASCII string.
UCS-2 is much much nicer than UTF-8, is has a fixed size, it is readable, Windows uses it, but it cannot represent all Unicode characters.
Encode::Unicode contains this nice cheatsheet: ---------------+-----------------+------------------------------
gdb parrot
Back to parrot:
If you debug parrot with gdb you get a gdb pretty-printer thanks to Nolan Lum, which displays the string and encoding information automatically.
In perl5 you have to call
Perl_sv_dump with or without the
my_perl as first argument, if threaded or not. With a threaded perl, e.g. on Windows you’d need to call
p Perl_sv_dump(my_perl, *MARK).
In parrot you just ask for the value and the formatting is done with a gdb pretty-printer plugin.
The string length is called
strlen (of the encoded string), the buffer size is called
bufused.
Even in a backtrace the string arguments are displayed abbrevated like this:
#3 0x00007ffff7c29fc4 in utf8_iter_get_and_advance (interp=0x412050, str="utf8:� [1/2]", i=0x7fffffffdd00) at src/string/encoding/utf8.c:551 #4 0x00007ffff7a440f6 in Parrot_str_escape_truncate (interp=0x412050, src="utf8:� [1/2]", limit=20) at src/string/api.c:2492 #5 0x00007ffff7b02fb3 in trace_op_dump (interp=0x412050, code_start=0x63a1c0, pc=0x63b688) at src/runcore/trace.c:450
[1/2] means strlen=1 bufused=2
Each non-ascii or non latin-1 encoded string is printed with the encoding prefix.
Internally the encoding is of course a index or pointer in the table of supported encodings.
You can set a breakpoint to
utf8_iter_get_and_advance and watch the strings.
(gdb) r t/library/mime_base64u.t Breakpoint 1, utf8_iter_get_and_advance (interp=0x412050, str="utf8:\\x{00c7} [8/8]", i=0x7fffffffcd40) at src/string/encoding/utf8.c:544 (gdb) p str $1 = "utf8:\\x{00c7} [8/8]" (gdb) p str->bufused $3 = 8 (gdb) p str->strlen $4 = 8 (gdb) p str->strstart $5 = 0x5102d7 "\\x{00c7}"
This is escaped. Let’s advance to a more interesting utf8 string in this test, i.e. until str=”utf8:Ā [1/2]“
You get the members of a struct with tab-completion, i.e. press <TAB> after p str->
(gdb) p str-> _buflen _bufstart bufused encoding flags hashval strlen strstart (gdb) p str->strlen $9 = 8 (gdb) dis 1 (gdb) b utf8_iter_get_and_advance if str->strlen == 1 (gdb) c Breakpoint 2, utf8_iter_get_and_advance (interp=0x412050, str="utf8:Ā [1/2]", i=0x7fffffffcd10) at src/string/encoding/utf8.c:544 544 ASSERT_ARGS(utf8_iter_get_and_advance) (gdb) p str->strlen $10 = 1 (gdb) p str->strstart $11 = 0x7ffff7faeb58 "Ā" (gdb) x/2x str->strstart 0x7ffff7faeb58: 0xc4 0x80 (gdb) p str->encoding $12 = (const struct _str_vtable *) 0x7ffff7d882e0 (gdb) p *str->encoding $13 = {num = 3, name = 0x7ffff7ce333f "utf8", name_str = "utf8", bytes_per_unit = 1, max_bytes_per_codepoint = 4, to_encoding = 0x7ffff7c292b0 <utf8_to_encoding>, chr = 0x7ffff7c275c0 <unicode_chr>, equal = 0x7ffff7c252e0 <encoding_equal>, compare = 0x7ffff7c254e0 <encoding_compare>, index = 0x7ffff7c25690 <encoding_index>, rindex = 0x7ffff7c257a0 <encoding_rindex>, hash = 0x7ffff7c25a20 <encoding_hash>, scan = 0x7ffff7c29380 <utf8_scan>, partial_scan = 0x7ffff7c29460 <utf8_partial_scan>, ord = 0x7ffff7c297e0 <utf8_ord>, substr = 0x7ffff7c25de0 <encoding_substr>, is_cclass = 0x7ffff7c26000 <encoding_is_cclass>, find_cclass = 0x7ffff7c260e0 <encoding_find_cclass>, find_not_cclass = 0x7ffff7c26220 <encoding_find_not_cclass>, get_graphemes = 0x7ffff7c263d0 <encoding_get_graphemes>, compose = 0x7ffff7c27680 <unicode_compose>, decompose = 0x7ffff7c26450 <encoding_decompose>, upcase = 0x7ffff7c27b20 <unicode_upcase>, downcase = 0x7ffff7c27be0 <unicode_downcase>, titlecase = 0x7ffff7c27ca0 <unicode_titlecase>, upcase_first = 0x7ffff7c27d60 <unicode_upcase_first>, downcase_first = 0x7ffff7c27dc0 <unicode_downcase_first>, titlecase_first = 0x7ffff7c27e20 <unicode_titlecase_first>, iter_get = 0x7ffff7c29c40 <utf8_iter_get>, iter_skip = 0x7ffff7c29d60 <utf8_iter_skip>, iter_get_and_advance = 0x7ffff7c29eb0 <utf8_iter_get_and_advance>, iter_set_and_advance = 0x7ffff7c29fd0 <utf8_iter_set_and_advance>}
encode_base64(str)
$ perl -MMIME::Base64 -lE'$x="20e3";$s="\x{20e3}"; printf "0x%s\t%s=> %s",$x,$s,encode_base64($s)' Wide character in subroutine entry at -e line 1.
Oops, I’m clearly a unicode perl5 newbie. Does my term not understand utf-8?
$ echo $TERM xterm
No, it should. encode_base64 does not understand unicode.
perldoc MIME::Base64
“The base64 encoding is only defined for single-byte characters. Use the Encode module to select the byte encoding you want.”
Oh my! But it is just perl5. It just works on byte buffers, not on strings.
perl5 strings can be utf8 and non-utf8. Why on earth an utf8 encoded string is disallowed and only byte buffers of unknown encodings are allowed goes beyond my understanding, but what can you do. Nothing. base64 is a binary only protocol, based on byte buffers. So we decode it manually to byte buffers. The Encode API for decoding is called encode.
$ perl -MMIME::Base64 -MEncode -lE'$x="20e3";$s="\x{20e3}"; printf "0x%s\t%s=> %s",$x,$s,encode_base64(encode('utf8',$s))' Wide character in printf at -e line 1. 0x20e3 => 4oOj
This is now the term warning I know. We need -C
$ perldoc perluniintro $ perl -C -MMIME::Base64 -MEncode -lE'$x="20e3";$s="\x{20e3}"; printf "0x%s\t%s=> %s",$x,$s,encode_base64(encode('utf8',$s))' 0x20e3 => 4oOj
Over to rakudo/perl6 and parrot:
$ cat >m.pir << EOP .sub main :main load_bytecode 'MIME/Base64.pbc' $P1 = get_global [ "MIME"; "Base64" ], 'encode_base64' $S1 = utf8:"\x{203e}" $S2 = $P1(s1) say $S1 say $S2 .end EOP $ parrot m.pir FixedIntegerArray: index out of bounds! current instr.: 'parrot;MIME;Base64;encode_base64' pc 163 (runtime/parrot/library/MIME/Base64.pir:147)
The perl6 test, using the parrot library, from
$ git clone git://github.com/ronaldxs/perl6-Enc-MIME-Base64.git Cloning into 'perl6-Enc-MIME-Base64'... $ PERL6LIB=perl6-Enc-MIME-Base64/lib perl6 <<EOP use Enc::MIME::Base64; say encode_base64_str("\x203e"); EOP > use Enc::MIME::Base64; Nil > say encode_base64_str("\x203e"); FixedIntegerArray: index out of bounds! ...
The pure perl6 workaround:
$ PERL6LIB=perl6-Enc-MIME-Base64/lib perl6 <<EOP use PP::Enc::MIME::Base64; say encode_base64_str("\x203e"); EOP > use PP::Enc::MIME::Base64; Nil > say encode_base64_str("\x203e"); 4oC+
Wait. perl6 creates a different enoding than perl5?
What about coreutils base64 command.
$ echo -n "‾" > m.raw $ od -x m.raw 0000000 80e2 00be 0000003 $ ls -al m.raw -rw-r--r-- 1 rurban rurban 3 Dec 6 10:23 m.raw $ base64 m.raw 4oC+
[80e2 00be] is the little-endian version of
[e2 80 be], 3 bytes, flipped.
Ok, at least base64 agrees with perl6, and I must have made some encoding mistake with perl5.
Back to debugging our parrot problem:
parrot unlike perl6 has no debugger yet. So we have to use
gdb, and we need to know in which function the error occured. We use the parrot
-t trace flag, which is like the perl5 debugging
-Dt flag, but it is always enabled, even in optimized builds.
$ parrot --help ... -t --trace [flags] --help-debug ... $ parrot --help-debug ... --trace -t [Flags] ... 0001 opcodes 0002 find_method 0004 function calls $ parrot -t7 m.pir ... 009f band I9, I2, 63 I9=0 I2=0 00a3 set I10, P0[I5] I10=0 P0=FixedIntegerArray=PMC(0xff7638) I5=[2063] 016c get_results PC2 (1), P2 PC2=FixedIntegerArray=PMC(0xedd178) P2=PMCNULL 016f finalize P2 P2=Exception=PMC(0x16ed498) 0171 pop_eh lots of error handling ... 0248 callmethodcc P0, "print" P0=FileHandle=PMC(0xedcca0) FixedIntegerArray: index out of bounds!
We finally see the problem, which matches the run-time error.
00a3 set I10, P0[I5] I10=0 P0=FixedIntegerArray=PMC(0xff7638) I5=[2063]
We want to set I10 to the I5=2063′th element in the FixedIntegerArray P0, and the array is not big enough.
After several hours of analyzing I came to the conclusion that the parrot library MIME::Base64 was wrong by using ord of every character in the string. It should use a bytebuffer instead.
Which was fixed with commit 3a48e6. ord can return integers > 255, but base64 can only handle chars < 255.
The fixed parrot library was now correct:
$ parrot m.pir ‾ 4oC+
But then the tests started failing. I spent several weeks trying to understand why the parrot testsuite was wrong with the mime_base64 tests, the testdata came from perl5. I came up with different implementation hacks which would match the testsuite, but finally had to bite the bullet, changing the tests to match the implementation.
And I had to special case the tests for big-endian, as base64 is endian agnostic. You cannot decode a base64 encoded powerpc file on an intel machine, when you use multi-byte characters. And utf-8 is even more multi-byte than ucs-2. I had to accept the fact the big-endian will return a different encoding. Before the results were the same. The tests were written to return the same encoding on little and big-endian.
Summary
The first reason why I wrote this blog post was to show how to debug into crazy problems like this, when you are not sure if the core implementation, the library, the spec or the tests are wrong. It turned out, that the library and the tests were wrong.
You saw how easily you could use gdb to debug into such problems, as soon as you find out a proper breakpoint.
The internal string representations looked like this:
MIME::Base64 internally:
len=1, encoding=utf-8, buf=[3e20]
and inside the parrot imcc compiler the SREG
len=8, buf="utf-8:\"\x{203e}\""
parrot is a register based runtime, and a SREG is the string representation of the register value. Unfortunately a SREG cannot hold the encoding info yet, so we prefix the encoding in the string, and unquote it back. This is not the reason why parrot is still slower than the perl5 VM. I benchmarked it. parrot still uses too much sprintf’s internally and the encoding quote/unquoting counts only for a 4th of the time of the sprintf gyrations.
And parrot function calls are awfully slow and de-optimized.
The second reason is to explain the new decode_base64() API, which only parrot – and therefore all parrot based languages like rakudo – now have got.
decode_base64(str, ?:encoding)
“Decode a base64 string by calling the decode_base64() function.
This function takes as first argument the string to decode, as optional second argument the encoding string for the decoded data.
It returns the decoded data.
Any character not part of the 65-character base64 subset is silently ignored.
Characters occurring after a ‘=’ padding character are never decoded.”
So decode_base64 got now a second optional encoding argument. The src string for encode_base64 can be any encoding and is automatically decoded to a bytebuffer. You can easily encode an image or unicode string without any trouble, and for the decoder you can define the wanted encoding beforehand. The result can be the encoding binary or utf-8 or any encoding you prefer, no need for additional decoding of the result. The default encoding of the decoded string is either ascii, latin-1 or utf-8. parrot will upgrade the encoding automatically.
You can compare the new examples of pir against the perl5 version:
parrot:
.sub main :main load_bytecode 'MIME/Base64.pbc' .local pmc enc_sub enc_sub = get_global [ "MIME"; "Base64" ], 'encode_base64' .local string result_encode # GH 814 result_encode = enc_sub(utf8:"\x{a2}") say "encode: utf8:\"\\x{a2}\"" say "expected: wqI=" print "result: " say result_encode # GH 813 result_encode = enc_sub(utf8:"\x{203e}") say "encode: utf8:\"\\x{203e}\"" say "expected: 4oC+" print "result: " say result_encode .end
perl5:
use MIME::Base64 qw(encode_base64 decode_base64); use Encode qw(encode); my $encoded = encode_base64(encode("UTF-8", "\x{a2}")); print "encode: utf-8:\"\\x{a2}\" - ", encode("UTF-8", "\x{a2}"), "\n"; print "expected: wqI=\n"; print "result: $encoded\n"; print "decode: ",decode_base64("wqI="),"\n\n"; # 302 242 my $encoded = encode_base64(encode("UTF-8", "\x{203e}")); print "encode: utf-8:\"\\x{203e}\" -> ",encode("UTF-8", "\x{203e}"),"\n"; print "expected: 4oC+\n"; print "result: $encoded\n"; # 342 200 276 print "decode: ",decode_base64("4oC+"),"\n"; for ([qq(a2)],[qq(c2a2)],[qw(203e)],[qw(3e 20)],[qw(1000)],[qw(00c7)],[qw(00ff 0000)]){ $s = pack "H*",@{$_}; printf "0x%s\t=> %s", join("",@{$_}), encode_base64($s); }
perl6:
use Enc::MIME::Base64; say encode_base64_str("\xa2"); say encode_base64_str("\x203e");
|
http://perl6advent.wordpress.com/2012/12/07/day-7-mimebase64-on-encoded-strings/?like=1&source=post_flair&_wpnonce=c1c9c39881
|
CC-MAIN-2014-10
|
refinedweb
| 2,512
| 55.03
|
lsh4slsh4s
UsageUsage
Add the dependency
libraryDependencies += "net.pishen" %% "lsh4s" % "0.6.0"
Add the resolver
resolvers += Resolver.bintrayRepo("pishen", "maven")
Hash the vectors (the whole hashing process will run in memory, you may need to enlarge your JVM's heap size.)
import lsh4s._ val lsh = LSH.hash("./input_vectors", numOfHashGroups = 10, bucketSize = 10000, outputPath = "mem") val neighbors: Seq[Long] = lsh.query(itemId, maxReturnSize = 30).get.map(_.id)
- The format of
./input_vectorsis
<item id> <vector>for each line, here is an example:
3 0.2 -1.5 0.3 5 0.4 0.01 -0.5 0 1.1 0.9 -0.1 2 1.2 0.8 0.2
- All the hash groups will be combined in the end to find the neighbors, larger
numOfHashGroupswill produce a more accurate model, but takes more memory when hashing.
- Larger
bucketSizewill produce a more accurate model as well, but takes more time when finding neighbors.
outputPath = "mem"is for memory mode, otherwise it will be the output file for LSH model (we recommend pointing this file to an empty directory, since we will create and delete several intermediate files around it.)
lsh4s uses slf4j, remember to add your own backend to see the log. For example, to print the log on screen, add
libraryDependencies += "org.slf4j" % "slf4j-simple" % "1.7.14"
|
https://index.scala-lang.org/pishen/lsh4s/lsh4s/0.6.0?target=_2.10
|
CC-MAIN-2021-49
|
refinedweb
| 219
| 69.48
|
In this section we will read about the various aspects of Reflection in Java such as, what is reflection, use of reflection, drawback of reflection etc.
What Is Reflection
Reflection in computer science is referred to as a computer program that analyzes and/or modify the object's structure and behavior at run time. Object's structure and behavior may be the values, meta-data, properties and functions, etc. Most of the high level virtual machine programming languages, manifestly typed or statically typed programming languages for example, Smalltalk, Java, C#, Scala, scripting languages, uses reflection.
Use Of Reflection
As per the above section, use of reflection is to observe and/or modify the program execution at run time. In an object oriented programming, the reflection may be used in to inspect the the classes, interfaces, fields, and methods, at runtime. For this there is no need to know their names at compile time. Apart, from these uses reflection is used to instantiate the new object and calling the methods. Reflection may be used in the following areas :
Drawbacks of Reflection
Reflection is useful and powerful but, it has also some drawbacks. If in the programming code there is no need to use the reflection it shouldn't be used. If you use the reflection in your code following issues you may have to face :
Example
Here I am giving a simple example which will demonstrate you about how to use the reflection in Java. In this example I have created a Java class named ReflectionExample.java inside I have defined a static constant field. Then I have created another class named MainClass.java where I have created a main method and find the class using getClass() method then I have used the method getField() of java.lang.Class class then I have used the get() method of Field class to get the value of the field.
ReflectionExample.java
package net; public class ReflectionExample { public static int a = 10; }
MainClass.java
package net.roseindia; import java.lang.reflect.Field; import net.ReflectionExample; public class MainClass { public static void main(String args[]) { ReflectionExample re = new ReflectionExample(); Class c1 = re.getClass(); Field field; try { field = c1.getField("a"); System.out.println("Field of Class Reflection Example : "+field); Object value = field.get(re); System.out.println("Value of the field : "+value); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Output :
When you will compile and execute the MainClass.java then the output will be as follows :
For reading more in detail about Reflection you may go through the link
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Discuss: Reflection In Java
Post your Comment
|
http://roseindia.net/java/reflect/reflection-in-java.shtml
|
CC-MAIN-2014-41
|
refinedweb
| 456
| 56.15
|
.<FONT size=3>Underbones are popular worldwide, but in East Asian and South East Asian countries in particular they dominate the low cost market segment with their scooter-like ease of use, their appeal to both sexes, and their motorcycle-like dependable handling properties.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-comAdvantages<o:p></o:p></B>The powertrain of an underbone is based on that of a conventional motorcycle. The engine is between the rider's feet and the rear wheel is driven by a regular motorcycle secondary chain drive, Chain enclosure, using sheet-metal covers, is usual.<o:p></o:p.<o:p></o:p>Technical Sophistication<o:p></o:p>The technical sophistication of larger motorcycles has been increasingly added to the underbone, with fuel injection systems in the Honda Wave 125i, Yamaha Spark 135iand, since 2007, the Japanese version of the Honda Super Cub<SUP>.</SUP> Modern underbones use capacitor discharge ignition for the ignition system, almost all have indicators, and many have electric starters.<o:p></o:p>
Storage on underbones<o:p></o:p></SPAN>Most underbone motorcycles sold in Southeast Asia come with a standard steel basket, allowing riders to carry goods. More secure storage capacity is often available with the option of a carrier and a top box. Some top boxes are detachable from the carriers.<o:p></o:p>Some underbones, including the Honda Wave, Modenas X-cite, and the Yamaha Nouvo, have a lockable storage compartment under the seat. Some have a hook in the area between the riders knees for a shopping bag.In Pakistan too we should have this type of bike, as new generation is asking for change !All 70 CC bikes look the same (minus the graphics).<o:p></o:p>
(source Wikipedia)<o:p></o:p>
i second ur opinion.. they r pretty as well...
but we have vespa as well?is that discontinued ?
Great info!Thanks for sharing.
What are the views of those Pak Wheelers who want new models in the market ?
at least i definitely want to have bikes in these shapes because at times i am totaly unable to place just one fat book on bike somewhere... either have to put in between the wires behind speedometer or have to rope it on back seat... and in rainy days its totaly useless. ..
besides if i have some shoppers i have no way to place those...
this classic honda cd70 is abolutely useless for these uses with its default settings... and industry here is in such a horrible state that they cannot make adequate room in the copied bikes for these accessories..
honda must change there 70cc motorcycles to this shape ... but people are eager to buy new models of current 70 cuz of the new sticker on the tank nothing else
Well just because of its shape, people will call it a scooter or a vespa.Its the mind set that we still are not able to accept anything else then the traditional shape i-e CD70.BTW the storage places on this bike are great.
Can any one from Thailand,Malaysia or Singapore share his/her experience regarding how good these bikes are ?
If these are available in Pakistan , I will surely buy one. I always face problems carrying my books. I have even lost one book on my cd 70
@metroguy you are absolutely right .. i think whenever we face such problem we should take a snap and post it here ...... shaid gov/companies ko is thread par ka kuch sharam ya khyaal tho aa hi jaya ga....
These bikes are basically built on the concept of city commuter bikes having low weight 4 easy handling, better milage, having low power but tough motors...
i dont think as per the requirement of Pakistani market introducing these here wud be a wise step, they will fail instantly. Reasons? many!1. They dont look masculine, they are girlish.2. They look scooter-ish, no current market for them here.3. Donot have enough place 2 overload them with lots of luggage & Ppl, due to no fuel tank - u cannot overload them with 4,5 People like ppl do here!!4. CD70s work gud enogh here, u can overload it, rev it 2 max, bang it hundred times-- it will still work. And has already got all the guddies of low fuel consumption, light weight easy drive etc.5. Pitty that these bikes ur posting, cant be even used 2 bring vegetables from market in shopping bags!!! Why?
Due to this:
What say now?? Is this still ur favourite bike!?!
Automotorsport_Lover1. They dont look masculine, they are girlish.
soch pa koi pabandi nai.....u can percieve it ur own way.... by the way fashion jo chz kharab ho jathi ha uus ka naam ha...
2. They look scooter-ish, no current market for them here.just because they look scooterish saying that there is no market for them is not wise.
3. Donot have enough place 2 overload them with lots of luggage & Ppl, due to no fuel tank - u cannot overload them with 4,5 People like ppl do here!! to some extent right in this department.. but again dear there are users who use it primarily for commuting WITH the ease of placement of books and other related small things
4. CD70s work gud enogh here, u can overload it, rev it 2 max, bang it hundred times-- it will still work. And has already got all the guddies of low fuel consumption, light weight easy drive etc. same goes for these as well .. they are not made inferior and it is foolish to say that they are scooterish and hence engine is inferior...watch at 5:18 the video given below to allay ur frears...
5. Pitty that these bikes ur posting, cant be even used 2 bring vegetables from market in shopping bags!!! Why?
u should watch rhe documentry[1] about the top ten bikes ... and honda cub is the best at probably numer 2 or 1..[its number 1 i confirmed it by the way u should watch that documentry...] that video has pretty good illustrations regarding its capabilities..
[1] YouTube - Greatest Ever Motorcycles: # 1 - Honda Cub
so from video honda cub can have 50mph[80km/hr] speed, automatic transmission, and a whooping 150km/litre efficiency on straight roads driving at 35 km/hr,and to destroy it u need c4 explosive watch at 6:45 onwards////LOL ..........i bet if u could ever get above 65 from 70.. so ur words regarding its quality are not compatible with ground realities..
Thanks Asjdsm, well explained ! In May I went to Malaysia and then travelled from there on bus to Singapore, it was a beautiful experience! The road was motor way like and some people on these bikes alongwith their backpacks were traveling long distances !In rural areas you should see what these bikes are capable of ! We should open our mind and should not reject any new idea by labeling it whatever we like ~ Otherwise we will keep on driving CD 70
@ asjdsm
Sir, 1stly im just saying that its not a practical thought to expect these kinda bikes here thts why when i say tht theyr girlish, scooter-ish and no market here this matters alot!! Lol... Pehle wo cheez to companys se mang lo jo chahye hai! A proper motorbike - then expect tht these will come here too! So no chance 4 them here 4 next 20yrs i guess...
Lol and the vid u just refered to is pretty old, i saw that a long time ago! And again.. its infront of u how all the pizza fell of the bike! Even if they tried to load it up sensibly there was no chance tht these things cud have been taken 2 required place properly not even half of them..But wht im saying is u can differ in other points but loading space problem remians there!
And finally, Why ur showing me Honda CUBs vid? these arent honda cubs, but yes built on the same concept..Anyways... Keep wishing! ur not gona get them here any soon! Lol!
they are not made inferior and it is foolish to say that they are scooterish and hence engine is inferior
Kindly manage ur words bro, i just said tht these bikes have girlish looks + Scooter-ish styling + not so practical frame for our market requiremnets here. i didnot comment ebt there engine or durability at all...
So ur above comment is i dont knw what for?
Yamaha T135 is an underbone motorcycle. It is also known as the Spark 135 in Thailand, Sniper in the Philippines, Jupiter MX in Indonesia, 135LC in Malaysia, Exciter in Vietnam, and T 135 Crypton X in Greece. It is made by Yamaha Motor Company and powered by a liquid-cooled 134.4 cc (8.20 cu in) 4-stroke engine. This underbone is fit for circuit racing than its rival Honda Sonic 125 and the Suzuki Raider 150 and one of the fastest 4-stroke underbone in the <st1:place w:South East Asia</st1:place>.<o:p></o:p> In 2008, the fuel-injected version of the Yamaha Spark 135 was launched for the <st1:country-region w:<st1:place w:Thailand</st1:place></st1:country-region> market, making it the second underbone motorcycle using fuel injection after the Honda Wave 125i. There are 3 main Yamaha factories that assemble T135. These are <st1:country-region w:Indonesia</st1:country-region>, <st1:country-region w:Thailand</st1:country-region> and newest is <st1:country-region w:<st1:place w:Philippines</st1:place></st1:country-region>.<o:p></o:p> <sup class="Template-Fact" title="This claim needs references to reliable sources from December 2009" style="white-space: nowrap;"></sup>
Here is an interesting article and a claim ,so please review it alongwith your comments.
Looking at the motorcycles on the street you notice, plenty of Honda's and Yamaha's here and there a Suzuki, but what about Kawasaki's.
The Kawasaki Kaze ZX130R, comes with a 130cc 4 Stroke, Single Piston SOHC, Air Cooled engine. The Kawasaki Kaze ZX130 handles like a charm, it is one of the easiest drivable bikes I have tried out. You might think that all 125cc scooters and motorcycles perform much the same, they've all got about the same amount of power to play with and weight all around 100 kilos.
But the Kawasaki Kaze ZX130R feels quick. It's capable to take sharp curves, and the ZX130's engine fuel economic are simply said impressive, and the Kawasaki ZX130R is nice and narrow, plus well balanced at low speed, which makes it ideal for filtering. The Kawasaki's power is enough for really strong acceleration up to 80 km/h or so, though the km/h does start to tail off the faster you go.
On the open road, overtaking from 100 km/h takes a fair bit of space, and it's clear that Kawasaki's engineers have worked this Kaze ZX130R's transmission to emphasize quick in-town go. Having a rev/tacho counter is entertaining too: pull away gently, an it dials up 5000rpm; give it more throttle and you get 6000; full throttle brings it around 7500 to 8000.
The Kawasaki Kaze ZX130R will cruise happily at 90 to 100 km/h and go on to an indicated 120 km/h flat-out, which is bang on the 125cc motorcycle range average. Even at those speeds, the modestly fairing does a very good job, keeping the wind off without buffeting or too much noise.meta:desc.]
Read this article about HONDA Cub another Underbone bike, don't forget to check out the comments at the bottom and post yours, here !
Honda Cub: The greatest machine ever - Telegraph
its practical and ever so efficient in terms of space utilization but people like James May would be found riding it in Lahore....
the sportier ones in thailand could do wonders here in Lhr/Khi...not much bikes in isb anyways
nice info. hope they will be available in Pakistan and our grandchildren would be enjoying their ride.
|
https://www.pakwheels.com/forums/t/underbone-motorbikes/161665
|
CC-MAIN-2017-04
|
refinedweb
| 2,039
| 71.14
|
So I'm calculating money change, if the user's input is
0.41
1 quarter, 1 dime, 1 nickel, 1 penny
exit(0)
#include <cs50.h>
#include <stdio.h>
int main (void) {
printf("How much change do you owe: ");
float amount = GetFloat();
float cents = 100.0 * amount;
float quarter = 0;
float dime = 0;
float nickel = 0;
float penny = 0;
if (amount < 0) {
printf("Please provide a positive value.");
exit(0);
}
while (cents > 0) {
if (cents >= 25.0) {
cents -= 25.0;
quarter += 1;
} else if (cents >= 10.0) {
cents -= 10.0;
dime += 1;
} else if (cents >= 5.0) {
cents -= 5.0;
nickel += 1;
} else if (cents >= 1.0) {
cents -= 1.0;
penny += 1;
}
}
printf("%f quarters, %f dimes, %f nickels, %f pennies, Total of %f coins.\n", quarter, dime, nickel, penny, quarter + dime + nickel + penny);
}
It can be a bit awkward to get your head around where to put declarations as a newbie, so here it is:
float amount; for (;;) { amount = GetFloat(); if ( amount >= 0 ) break; printf("Please provide a positive value.\n"); } float cents = 100.0 * amount; float quarter = 0; // etc.
You can't put
float amount inside the
{ } otherwise that variable would be scoped to that scope, and not accessible after the
}.
A more compact way of writing the same loop would be:
while( (amount = GetFloat()) < 0 ) printf("Please provide a positive value.");
but you can use whichever version looks more sensible to you.
|
https://codedump.io/share/adU3vg3vQdOH/1/if-user-input-is-negative-prompt-again
|
CC-MAIN-2017-34
|
refinedweb
| 236
| 86.1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.