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 |
|---|---|---|---|---|---|
Python
Python Imports
Python Imports
There is some fundamentals we should understand:
A Python module is just a file with Python code
A Python package is a folder containing a
__init__.pyfile
Subfolders
The problem usually comes in when you are calling python modules or scripts from a subfolder.
For example, a project of this form:
my_package/ __init__.py apples.py grapes/ __init__.py red_grapes.py white_grapes.py
If you want to import
apples from
red_grapes you will struggle when calling your script like this:
python red_grapes.py
You can’t just
from my_package import apples, as that package is not on the python path.
Traceback (most recent call last): File "red_grapes.py", line 1, in <module> from my_package import apples ModuleNotFoundError: No module named 'my_package'
You can’t just do a relative import
from ..my_package import apples for the same reason, the parent directory is not added to the python path
Traceback (most recent call last): File "red_grapes.py", line 1, in <module> from ..my_package import apples ValueError: attempted relative import beyond top-level package
You can run it as a package, not as a file:
python -m red_grapes
But you will get the same errors:
ModuleNotFoundError: No module named 'my_package'
and:
ImportError: attempted relative import with no known parent package
The Solution
You have to add the parent folder to the
sys.path
sys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))))
Even better is to structure your project of the form:
/main __init__.py script.py my_package/ class_file.py ... | https://fixes.co.za/python/python-imports/ | CC-MAIN-2019-30 | refinedweb | 255 | 53.71 |
Frequently Asked Questions
- The Inko project
- Where does the name come from?
- Who is the creator of Inko?
- What license does Inko use?
- Why does Inko use the MPL 2.0?
- Can I use Inko for a proprietary project?
- Why host on GitLab.com, and not GitHub?
- What languages were a source of inspiration for Inko?
- Inko's concurrency model looks familiar to the model used by Erlang, is this intentional?
- The language
- Why use curly braces?
- Why do I have to import a module just to write to STDOUT or STDERR?
- Why is the keyword for blocks called "do"
- Why do certain methods take a "lambda", instead of a block?
- What was the inspiration for the error handling model of Inko?
- Why not use some sort of Result type for errors?
- Why does sending a message to Nil return another Nil?
- Isn't that annoying? How will I know where a Nil originated from?
- But what if I don't want to deal with a Nil value? For example, when saving data to a database.
- How do I convert an optional type to a non optional type?
- Why do I have to include error types in my method signatures, but panics don't require any additional information?
- Does Inko support reflection?
- OK so how do I use mirrors?
- Why do my methods and blocks define a "self" argument?
- How can I refer to the current module?
- How do I write a unit test?
- How does the runtime perform low level operations, such as opening a file?
- Does Inko support sum types and/or enums?
- Does Inko support pattern matching like many functional languages?
- Does Inko use pass by value, or pass by reference?
- Does Inko have any move semantics similar to Rust?
- The compiler
- The virtual machine
- Why write the VM in Rust?
- Why use a garbage collector?
- What garbage collection algorithm is used?
- How does Immix work?
- Why not use OS threads, instead of green threads?
- Does the virtual machine support finalisation?
- Does this mean my program will leak resources, such as sockets, if I don't close them?
- Is finalisation deterministic?
- Does the virtual machine guarantee resources are cleaned up upon termination?
- How many processes can run concurrently and in parallel?
- Can I change the number of threads used by the VM?
The Inko project
Where does the name come from?
"Inko" ("インコ") is Japanese for parakeet / parrot. Inko is an object oriented language that uses message passing. In a way, objects talk to each other, much like parrots can "talk" by mimicking the human voice. The creator of Inko also happens to like parrots.
Who is the creator of Inko?
What license does Inko use?
Inko is licensed under the Mozilla Public License version 2.0.
Why does Inko use the MPL 2.0?
The MPL 2.0 license is a permissive language that covers important topics, such as patents, and better describes who owns the source code (compared to the MIT license). It also comes with some requirements such as:
- Changes made to the software have to be made available to the public.
- A copy of the license must be included when distributing the software.
- Modifications of the software must use the same (or a compatible) license.
All of this better protects the authors and the software, and makes it more clear to users (and especially large organisations) what to expect.
For more information about the MPL 2.0 you can refer to the MPL 2.0 FAQ, or the MPL 2.0 entry on choosealicense.com.
Can I use Inko for a proprietary project?
Yes. The MPL 2.0 is not a viral license. This means that the MPL 2.0 license only applies to Inko's own source code, and not any projects that link with it (e.g. your own software).
Why host on GitLab.com, and not GitHub?
GitLab offers more features than GitHub, and comes with built-in continuous integration support.
What languages were a source of inspiration for Inko?
In no particular order: Smalltalk, Self, Ruby, Erlang, and Rust.
Inko's concurrency model looks familiar to the model used by Erlang, is this intentional?
Yes. Inko's concurrency model is heavily inspired by Erlang.
The language
Why use curly braces?
Curly braces are by far the most common way of starting and terminating blocks of code, such as functions. This hopefully makes it easier to get used to Inko.
Curly braces integrate better into editors, as many have support for automatically inserting them, or jumping to a closing curly brace.
Finally, curly braces make the code more compact without sacrificing readability.
Why do I have to import a module just to write to STDOUT or STDERR?
- Not every program (or module) has to write to STDOUT or STDERR.
- Exposing some sort of
- You can not import just a method from a module, instead a receiver is always required. This would require importing a module by default, but for many modules this simply isn't necessary.
Why is the keyword for blocks called "do"
This is taken from Ruby, which uses a keyword with the same name to start a Ruby closure.
Why do certain methods take a "lambda", instead of a block?
Lambdas are blocks that can't capture any local variables. They are primarily used for spawning processes, or starting other operations where the block may outlive the scope that it is defined in.
What was the inspiration for the error handling model of Inko?
An article titled The Error Model, by Joe Duffy.
Why not use some sort of Result type for errors?
Result types and similar solutions impose a runtime cost on the happy path, even when an error never occurs. Inko's error model doesn't suffer from the same problem.
Why does sending a message to Nil return another Nil?
This drastically simplifies the amount of if-nil-then-that checks. Say you want to retrieve a user from a database, get their location details, then display their city. If the user is not found, you should display an empty string. In a language such as Ruby, you would have to write the following:
user = find_user(email: 'alice@example.com') if user && user.location user.location.city else '' end
In recent versions of Ruby you can shorten this down to the following, though it is effectively the same code:
user = find_user(email: 'alice@example.com') user&.location&.city || ''
In Inko, we would instead write the following:
user = find_user(email: 'alice@example.com') user.location.city
And if we want to return a string right away:
user = find_user(email: 'alice@example.com') user.location.city.to_string
While this particular example is fairly basic, in real world applications this allows you to drastically reduce the amount of code necessary to deal with optional values. And none of this requires additional syntax sugar.
Isn't that annoying? How will I know where a Nil originated from?
If you could blindly pass a Nil to other methods, then yes this could be
annoying. However, Inko doesn't allow this when using statically typed methods.
For example, if a method takes a "User" object you can not pass a Nil to it.
The only time you can pass a Nil as an argument is when this argument takes an
optional type (e.g. a
?User), or simply takes Nil itself.
This prevents Nil values from "leaking" into other methods unexpectedly. This in turn makes it very easy to figure out where a Nil comes from, because you rarely have to deal with a Nil that did not originate directly from your own code.
But what if I don't want to deal with a Nil value? For example, when saving data to a database.
In that case you can always send
if,
if_true, or similar messages to the
object and act accordingly. Just because sending an unknown message to Nil
produces another Nil doesn't mean you never should send these messages to Nil.
How do I convert an optional type to a non optional type?
If you have an optional
?T, you can tell the compiler to treat it as a
T by
using prefixing the expression with a
*. For example, if
user is a
?User
then
*user will inform the compiler that the return value of this expression
is a
User. This operator is called the "unpack operator", because it "unpacks"
a
?T into a
T.
Keep in mind that this only serves as a hint to the compiler, it will not generate any sort of runtime code to verify if the expression is Nil or not. This means you should always check if you are dealing with a Nil or not when using this operator:
let number: ?Integer = Nil # This will blow up, because "number" is Nil. *number + 5 # This is safe, and the recommended way of doing things. number.if_true { *number + 5 }
Why do I have to include error types in my method signatures, but panics don't require any additional information?
Virtually every method can panic (e.g. when running out of memory). This would lead to very verbose method signatures.
Does Inko support reflection?
Yes, there are two modules for this:
std::reflection
std::mirror
The
std::reflection module provides a few simple reflection methods that
should have as little overhead as possible, such as
std::reflection.kind_of?.
The
std::mirror module provides a more powerful reflection system, based on
the concept of mirrors.
OK so how do I use mirrors?
You import
std::mirror, create a mirror for your object, then send messages to
it to get the data you need. For example, we can retrieve the argument names of
a block as follows:
import std::mirror let block = do (number: Integer) { number * 2 } let block_mirror = mirror.reflect_block(block) block_mirror.argument_names # => ['self', 'number']
Why do my methods and blocks define a "self" argument?
This argument is used to store the receiver of methods, it is generated by the compiler.
Closures don't use the argument, instead they capture the outer local variable
called
self. Lambdas ignore the argument as well, and instead explicitly
define
self and set it to the object of the module the lambda is defined in.
How can I refer to the current module?
You can use the
ThisModule constant for this, which contains the module that
the constant is referenced from. This can be used when an object's method is the
same as a module method, and you want to call the module method from the
object's method:
def example {} object Person { def example { ThisModule.example } }
How do I write a unit test?
You can use
std::test for this:
import std::test import std::test::assert test.group 'Integer.+', do (group) { group.test 'Summing two Integers', { try assert.equal(1 + 2, 3) } } test.run
How does the runtime perform low level operations, such as opening a file?
The runtime uses what is known as "virtual instructions" for this. These
instructions look like regular message sends, but are compiled directly into
virtual machine instructions. Virtual instructions always use the constant
_INKOC as the receiver, for example:
_INKOC.integer_equals(10, 10)
This code would be directly compiled into the
IntegerEquals instruction. These
virtual instructions are used in various places as the basic building blocks of
the runtime.
You should never use these instructions directly, as they are not part of the public API and may change (or be removed) at any time.
Does Inko support sum types and/or enums?
No. Traits remove the need for sum types and enums.
Does Inko support pattern matching like many functional languages?
No. Pattern matching based on type (patterns) is something we feel does not belong in an object oriented programming language. You should use traits instead.
Having said that, this doesn't mean you can't check what kind of object you are
dealing with. Using the
std::reflection module we can do this if truly
necessary:
import std::reflection reflection.kind_of?('hello', String).if_true { # ... }
However, code such as this should be avoided as much as possible.
Does Inko use pass by value, or pass by reference?
Pass by value, but all values are pointers to heap allocated objects. This means that passing an object to a method will result in that method using a copy of the pointer, not the object it points to.
Does Inko have any move semantics similar to Rust?
No.
The compiler
Why is the compiler written in Ruby?
Currently Inko is not feature complete enough to write a compiler for itself. This meant the creator had to use a different language, and Ruby happened to be a language they were most comfortable with.
Why not write the compiler in Rust, just like the VM?
Prior to the compiler being written in Ruby, the author did attempt to write it in Rust instead. Unfortunately, the author spent a lot of time fighting Rust's strict type system and borrow checker. After a month or two the author decided to give up, and write the compiler in Ruby instead.
Will the compiler always be written in Ruby?
No. Once Inko is feature complete enough we aim to rewrite the compiler in Inko itself.
Does the compiler perform any work in parallel?
Not at the moment.
Does the compiler support incremental compilation?
Not at the moment, but we hope to add support for this one day.
The virtual machine
Why write the VM in Rust?
While the creator has experience with other systems languages such as C, they did not feel comfortable writing a virtual machine in these languages. Rust makes it much harder to shoot yourself in the foot, comes with a nice package manager, built-in unit testing, type inference, and many other features not found in C or C++.
Why use a garbage collector?
Manually managing memory like one does in C is prone to error. Compiler assisted memory management, such as used by Rust, is less error prone but often more complicated to use. Garbage collection makes memory management easy (for the user), at the cost of (potentially) less efficient memory usage.
The creator felt that using a garbage collector strikes a nice balance between good memory usage, and ease of use.
What garbage collection algorithm is used?
The garbage collector is a generational, parallel garbage collector, based on Immix. While Immix is not very popular, it is an excellent garbage collection algorithm.
Inko is currently the only programming language out there (that we know of) that fully implements Immix. JikesRVM also fully implements Immix, but is targeted towards virtual machine research, and not production software.
How does Immix work?
The Immix paper describes this in great detail, but the very brief summary is as follows:
- Memory is divided into 32 KB aligned blocks, which in turn are divided into "lines". Each line is 128 aligned bytes.
- A global allocator is tasked with allocating blocks from the system, and handing these off to thread-local (or in case of Inko process local) allocators.
- Objects are allocated into free lines of blocks that still have one or more lines available, using bump allocation.
- The garbage collector does not operate on individual objects, instead it operates on lines. This means it reclaims entire lines, instead of individual objects.
- The garbage collector uses a set of statistics to determine which blocks can be reused, which are full, and which ones need to be evacuated.
- Evacuating means moving objects from one block to another. This will reuse existing free blocks. The decision to do so is made based on statistics from a previous garbage collection.
- Evacuating of objects happens while tracing through all live objects, removing the need for a separate pass over the entire heap.
- Free blocks are returned to the global allocator.
Why not use OS threads, instead of green threads?
While the overhead of starting OS threads is not that big, it is still quite a bit bigger than simply allocating a lightweight structure and storing this somewhere. OS threads also typically allocate a certain stack size from the start.
Green threads give us greater control, and use fewer resources. This allows one to spawn a large number of green threads (known as "processes" in Inko), without using a lot of memory.
The use of green threads does require a custom scheduler, which adds extra complexity. The creator felt that this trade-off was worth it, because it ultimately makes it much easier and less scary to run many concurrent processes.
Does the virtual machine support finalisation?
Yes, but this is not exposed to the language. The virtual machine uses an internal finalisation mechanism to clean up various resources that belong to garbage collector objects.
Exposing finalisation can lead to a great deal of problems, and makes both the language and virtual machine much more complex. To solve this problem, the author decided to simply not expose a finalisation mechanism.
Does this mean my program will leak resources, such as sockets, if I don't close them?
No. When a process terminates, its memory is cleaned up, even in the event of a panic. This means that by the time a program terminates, all resources will be cleaned up.
Keep in mind that this clean up will not happen the moment an object is garbage collected, instead it will happen at some future point in time. This means it's best to explicitly dispose of external resources the moment you no longer need them.
Is finalisation deterministic?
No. Once an object is garbage collected, it may be finalised at any given point in time. The only guarantee is that if an object is garbage collected, if will be finalised before the program terminates, unless a bug or panic prevents this from happening.
Does the virtual machine guarantee resources are cleaned up upon termination?
Aside from any bugs preventing this from happening, yes. Inko makes use of Rust's drop semantics to ensure that when a program terminates all of its resources (memory, sockets, etc) are cleaned up before shutting down.
How many processes can run concurrently and in parallel?
The virtual machine has two thread pools: one for executing regular processes, and one for processes that may perform blocking operations, such as reading from a file. These pools are known as the primary and secondary pool respectively.
By default, both pools use a number of threads equal to the number of logical CPU cores. This means that a CPU with 8 logical cores can run 16 processes concurrently: 8 on the primary pool, and 8 on secondary pool.
Note that we say concurrently opposed to in parallel. This is because it's up to the CPU to decide how many of these threads are running in parallel.
Can I change the number of threads used by the VM?
Yes. The environment variables
INKO_PRIMARY_THREADS and
INKO_SECONDARY_THREADS can be used to control the number of threads used for
the primary and secondary pool. | https://inko-lang.org/faq/ | CC-MAIN-2018-51 | refinedweb | 3,168 | 66.94 |
Frank Slegers
- Total activity 45
- Last activity
- Member since
- Following 0 users
- Followed by 0 users
- Votes 1
- Subscriptions 18
Frank Slegers created a post,
Shortcuts for embedded terminal actions?In the standalone terminal keys are configured so ctrl-T opens a new tab, Ctrl-1 opens tab 1, ctrl-2 opens tab 2, ... etc In the embedded terminal in PHPstorm I can't find any options to configur...
Frank Slegers commented, Frank Slegers created a post,Answered
Deployment options goneAll of sudden all deployment options are gone: Can't find it in the settings, nor in the main menu. I have a license. Any idea why it's not showing?
Frank Slegers created a post,
Display scaling not working properly anymoreSince a while ago, all UI elements in PHPstorm (2016.3) are disproportional. Screenshot: What's going on here?
Frank Slegers created a post,Answered
Any way to use Cmder terminal in PHPstormWhen I try to set Cmder () as the default terminal in phpstorm 2016.2, it's giving the following error: JAVA IO exception: couldn't create PTY. Any way to make this work and hav...
Frank Slegers commented, Frank Slegers created a post,
Each time PHPstorm starts or indexes, it lags the whole computerEven music that is playing is stuttering the entire time when PHPstorm is indexing. It's a powerful ultrabook with 16GB of ram, i7 processor and ssd drive. Why is this happening? I have already adj...
Frank Slegers created a post,
Incorrect error reporting for some namespacesThis happened so far only when the namespace ends in Users or Interfaces. No biggie though. Just moving the namespace to the next line and back again makes PHPstorm stop complaining about it.
Frank Slegers commented, | https://intellij-support.jetbrains.com/hc/en-us/profiles/1373841671-Frank-Slegers | CC-MAIN-2020-10 | refinedweb | 288 | 66.03 |
May 23, 2012 05:44 AM|vahid.ch|LINK
Hi there,I have a web site which issues errors sometimes,I think it's due to not closing connection.
error issue:
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
As I close my Con,it works fine.
and I Open my connection as below:
public class BasePage:System.Web.UI.Page { public static Commands db = new Commands(); public static SqlConnection Con; private string ConString; public BasePage() { ConString = System.Configuration.ConfigurationManager.ConnectionStrings["SPConnection"].ToString(); Con = new SqlConnection(ConString); Con.Open(); } ... ... ...
All-Star
16261 Points
May 23, 2012 05:50 AM|urenjoy|LINK
You should use using statement for connection.
using (SqlConnection cn = new SqlConnection(connectionString)) { SqlCommand cm = new SqlCommand(commandString, cn) cn.Open(); cm.ExecuteNonQuery(); }
Check following thread:
C# - closing Sql objects best practice
Star
7870 Points
May 23, 2012 06:01 AM|gopalanmani|LINK
Hi,
The general recommendation is to Open/Execute/Close as soon as possible.
and check this url,
Hope its help you
2 replies
Last post May 23, 2012 06:01 AM by gopalanmani | http://forums.asp.net/t/1806523.aspx?When+should+I+close+the+connection+ | CC-MAIN-2014-15 | refinedweb | 200 | 50.02 |
have a string1 it contains 3 parts,for example "123456 service hello" and string2 contains text "change request " like this. and the string3 should contain "123456 +(second string)+ hello" "second string can be dynamic data whatever we give from string2,that should be displayed on the screen. i need logic for this program . i want to apply this to window header part. Thanks in advance
import java.awt.*; import javax.swing.*; class Header{ public static void main(String []args){ String st1="123456 service hello"; String arr[]=st1.split(" "); String st2=JOptionPane.showInputDialog(null,"Enter string2: "); String st3=st1.replace(arr[1],st2); JFrame f=new JFrame(st3); f.setLayout(null); JLabel l=new JLabel(st3); l.setBounds(50,10,300,20); f.add(l); f.setSize(300,100); f.setVisible(true); } }
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions. | http://www.roseindia.net/answers/viewqa/Swing-AWT/21584-swings-header.html | CC-MAIN-2013-20 | refinedweb | 167 | 68.77 |
[clang-move] A prototype tool for moving class definition to new file.
Summary:
This patch introduces a new tool which moves a specific class definition
from files (.h, .cc) to new files (.h, .cc), which mostly acts like
"Extract class defintion". In the long term, this tool should be
merged in to clang-refactoring as a subtool.
clang-move not only moves class definition, but also moves all the
forward declarations, functions defined in anonymous namespace and #include
headers to new files, to make sure the new files are compliable as much
as possible.
To move Foo from old.[h/cc] to new.[h/cc], use:
clang-move -name=Foo -old_header=old.h -old_cc=old.cc -new_header=new.h -new_cc=new.cc old.cc
To move Foo from old.h to new.h, use:
clang-move -name=Foo -old_header=old.h -new_header=new.h old.cc
Reviewers: klimek, djasper, ioeric
Subscribers: mgorny, beanz, Eugene.Zelenko, bkramer, omtcyfz, cfe-commits
Differential Revision: | https://reviews.llvm.org/rL282070 | CC-MAIN-2018-30 | refinedweb | 161 | 61.93 |
With 350 points and a description as follows:.
Note: Multiple collisions are possible, but only one of them is a valid flag.
You will realize you’ve gotten it once you do.
The hash is given as follows:
So, we start off by looking at the binary. Using Hopper, we obtain the following pseudo code by decompilation:
int hash(int input) { eax = _rotr(input ^ 0x24f50094, (input ^ 0x24f50094) & 0xf); eax = _rotl(eax + 0x2219ab34, eax + 0x2219ab34 & 0xf); eax = eax * 0x69a2c4fe; return eax; } int main() { esp = (esp & 0xfffffff0) - 0x20; puts(0x80486d0); gets(0x804a060); stack[2039] = "\nBar:"; puts(stack[2039]); while (stack[2039] < *(esp + 0x18)) { stack[2039] = *(stack[2039] + stack[2039] * 0x4); *(esp + 0x14) = *(esp + 0x14) ^ hash(stack[2039]); eax = _rotr(stack[2039], 0x7); printf("%08lx", stack[2039]); *(esp + 0x10) = *(esp + 0x10) + 0x1; } eax = putchar(0xa); return eax; }
We sketch the above code as block scheme below:
The first thing to note is that we can find an infinite number of collisions just by appending arbitrary data after 10 blocks. However, this is not interesting to us, but completely defeats the conditions for a safe cryptographic hash function.
This Merkle-Damgård-like structure allows us to solve blocks iteratively, starting from the first. Here is how. Starting from the first block, we can find an input to the function
such that when rotated 7 steps is equal to block 0 (here, denoted
). Hence, the problem we solve is to find an
such that
. This is a simple thing for Z3. Then, we take the next block and solve for
and so forth. Implemented in Python/Z3, it may look like the following:
from z3 import * import binascii, string, itertools bits = 32 mask = 2**bits - 1 allowed_chars = string.printable def convert_to_hex(s): return ''.join([hex(ord(x))[2:].zfill(2) for x in s[::-1]]) def convert_to_string(h): return ''.join([chr(int(x, 16)) for x in list(map(''.join, zip(*[iter(hex(h)[2:])]*2)))[::-1]]) def rot(val, steps): return (val << (bits-steps)) | LShR(val, steps) def hash_foobar(input): eax = rot(input ^ 0x24f50094, (input ^ 0x24f50094) & 0xf) eax = rot(eax + 0x2219ab34, bits - (eax + 0x2219ab34 & 0xf)) eax = eax * 0x69a2c4fe return eax & mask def break_iteratively(hashdata, i): if i == 0: prev_block = 0 else: prev_block = hashdata[i-1] s = Solver() j = BitVec('current_block', bits) eax = rot(prev_block ^ hash_foobar(j), 7) s.add(eax == hashdata[i]) block_preimages = [] while s.check() == sat: sol = s.model() s.add(j != sol[j].as_long()) block_string = convert_to_string(sol[j].as_long()) if all(c in allowed_chars for c in block_string): block_preimages.append(block_string) return block_preimages known = '9513aaa552e32e2cad6233c4f13a728a5c5b8fc879febfa9cb39d71cf48815e10ef77664050388a3' # this the hash of the file data = list(map(''.join, zip(*[iter(known)]*8))) hashdata = [int(x, 16) for x in data] print '[+] Hash:', ''.join(data) print '[+] Found potential hashes:\n' for x in itertools.product(*[break_iteratively(hashdata, i) for i in range(10)]): print ' * ' + ''.join(x)
This code is surprisingly fast, thanks to Z3, and runs in 0.3 seconds. Taking all possible collisions into consideration…
[+] Hash: 9513aaa552e32e2cad6233c4f13a728a5c5b8fc879febfa9cb39d71cf48815e10ef77664050388a3 [+] Found potential hashes: * CTFEC0nstra1nts_m4keth_fl4g} * CTFEC0nstra1nts_m4keth_nl4g} * CTFEC0nstra1nws_m4keth_fl4g} * CTFEC0nstra1nws_m4keth_nl4g} * CTFEC0nstra9nts_m4keth_fl4g} * CTFEC0nstra9nts_m4keth_nl4g} * CTFEC0nstra9nws_m4keth_fl4g} * CTFEC0nstra9nws_m4keth_nl4g} * CTF{C0nstra1nts_m4keth_fl4g} * CTF{C0nstra1nts_m4keth_nl4g} * CTF{C0nstra1nws_m4keth_fl4g} * CTF{C0nstra1nws_m4keth_nl4g} * CTF{C0nstra9nts_m4keth_fl4g} * CTF{C0nstra9nts_m4keth_nl4g} * CTF{C0nstra9nws_m4keth_fl4g} * CTF{C0nstra9nws_m4keth_nl4g}
…we finally conclude that the flag is the SHA-256 of
C0nstra1nts_m4keth_fl4g. | https://grocid.net/2016/06/05/backdoorctf16-collision-course/ | CC-MAIN-2017-17 | refinedweb | 531 | 55.13 |
Low level support for encoding avro values. More...
#include "Config.hh"
#include <stdint.h>
#include <string>
#include <vector>
#include "ValidSchema.hh"
#include "Stream.hh"
#include <boost/shared_ptr.hpp>
Go to the source code of this file.
Low level support for encoding avro values.
This class has two types of funtions. One type of functions support the writing of leaf values (for example, encodeLong and encodeString). These functions have analogs in Decoder.
The other type of functions support the writing of maps and arrays. These functions are arrayStart, startItem, and arrayEnd (and similar functions for maps). Some implementations of Encoder handle the buffering required to break large maps and arrays into blocks, which is necessary for applications that want to do streaming. | http://avro.apache.org/docs/1.6.3/api/cpp/html/Encoder_8hh.html | CC-MAIN-2015-06 | refinedweb | 121 | 62.54 |
A wrapper to make object instances thread private, lazily.
A wrapper which makes objects thread private. The methods of the underlying object can be invoked via the arrow operator. The object is created in a specific thread lazily, i.e. upon invocation of one of its methods. The correct object pointer from within a particular thread can be accessed with the overloaded arrow operator or with the Get method. In case an elaborate thread management is in place, e.g. in presence of stream of operations or "processing slots", it is also possible to manually select the correct object pointer explicitly.
Definition at line 151 of file TThreadedObject.hxx.
#include <ROOT/TThreadedObject.hxx>
Construct the TThreadedObject with initSlots empty slots and the "model" of the thread private objects.
This form of the constructor is useful to manually pre-set the content of a given number of slots when used in combination with TThreadedObject::SetAtSlot().
Definition at line 166 of file TThreadedObject.hxx.
Construct the TThreadedObject and the "model" of the thread private objects.
Definition at line 183 of file TThreadedObject.hxx.
Access the pointer corresponding to the current slot.
This method is not adequate for being called inside tight loops as it implies a lookup in a mapping between the threadIDs and the slot indices. A good practice consists in copying the pointer onto the stack and proceed with the loop as shown in this work item (psudo-code) which will be sent to different threads:
Definition at line 279 of file TThreadedObject.hxx.
Access a particular processing slot.
This method is thread-safe as long as concurrent calls request different slots (i.e. pass a different argument) and no thread accesses slot
i via the arrow operator, so mixing usage of GetAtSlot with usage of the arrow operator can be dangerous.
Definition at line 201 of file TThreadedObject.hxx.
Access a particular slot which corresponds to a single thread.
This overload is faster than the GetAtSlotUnchecked method but the caller is responsible to make sure that the slot exists, to check that the contained object is initialized and that the returned pointer will not outlive the TThreadedObject that returned it, which maintains ownership of the actual object.
Definition at line 259 of file TThreadedObject.hxx.
Access a particular slot which corresponds to a single thread.
This is in general faster than the GetAtSlot method but it is responsibility of the caller to make sure that the slot exists and to check that the contained object is initialized (and not a nullptr).
Definition at line 248 of file TThreadedObject.hxx.
Return the number of currently available slot.
The method is safe to call concurrently to other TThreadedObject methods. Note that slots could be available but contain no data (i.e. a nullptr) if they have not been used yet.
Definition at line 190 of file TThreadedObject.hxx.
Get the slot number for this threadID, make a slot if needed.
Definition at line 337 of file TThreadedObject.hxx.
Merge all the thread private objects.
Can be called once: it does not create any new object but destroys the present bookkeping collapsing all objects into the one at slot 0.
Definition at line 293 of file TThreadedObject.hxx.
Access the wrapped object and allow to call its methods.
Definition at line 285 of file TThreadedObject.hxx.
Set the value of a particular slot.
This method is thread-safe as long as concurrent calls access different slots (i.e. pass a different argument) and no thread accesses slot
i via the arrow operator, so mixing usage of SetAtSlot with usage of the arrow operator can be dangerous.
Definition at line 226 of file TThreadedObject.hxx.
Merge all the thread private objects.
Can be called many times. It does create a new instance of class T to represent the "Sum" object. This method is not thread safe: correct or acceptable behaviours depend on the nature of T and of the merging function.
Definition at line 311 of file TThreadedObject.hxx.
A TDirectory per slot.
Definition at line 331 of file TThreadedObject.hxx.
The initial number of empty processing slots that a TThreadedObject is constructed with by default.
Deprecated: TThreadedObject grows as more slots are required.
Definition at line 155 of file TThreadedObject.hxx.
Remember if the objects have been merged already.
Definition at line 334 of file TThreadedObject.hxx.
Use to store a "model" of the object.
Definition at line 326 of file TThreadedObject.hxx.
An object pointer per slot.
Definition at line 328 of file TThreadedObject.hxx.
Protects concurrent access to fThrIDSlotMap, fObjPointers.
Definition at line 333 of file TThreadedObject.hxx.
A mapping between the thread IDs and the slots.
Definition at line 332 of file TThreadedObject.hxx. | https://root.cern.ch/doc/master/classROOT_1_1TThreadedObject.html | CC-MAIN-2021-17 | refinedweb | 785 | 59.3 |
.
We all have those little wonders in our .NET code, those small tips and tricks that make code just that much more concise, maintainable, or performant. Many of you probably already know of some of these, but many folks either overlook them or just don't know about them, so this article is a refresher.
I'm planning on making this a three-part series encompassing 15 little wonders that I had thought of, though I'm very curious to hear the little wonders you can think of as well.
Update: Part 2 is now available here.
Update: Part 3 is now available here.
This one is such an elegant little operator that can be extremely useful in some situations. How often do you have a variable that you want to use the value of, but if that value is null you want to substitute a default value? For example, say you wanted to assign a string to a variable, but if that string is null you want the empty string instead?
You could, of course, write an if statement:
1: string name = value;
2:
3: if (value == null)
4: {
5: name = string.Empty;
6: }
Or better yet, you could use a ternary operator (?:):
1: string name = (value != null) ? value : string.Empty;
Ah, that's much more concise, but we can get even better! C# adds a null-coalescing operator (??) that is a short-cut for the ternary operator (?:) checking against a null:
1: string name = value ?? string.Empty;
Very nice and concise! You can even write a helper method to trim a string and return null if string is all whitespace so that it can be used with "??".
1: public static class StringUtility
2: {
3: public static string TrimToNull(string source)
4: {
5: return string.IsNullOrWhiteSpace(source) ? null : source.Trim();
6: }
7: }
Then the null-coalescing operator can be used to turn completely empty strings into defaults.
1: string name = StringUtility.TrimToNull(value) ?? "None Specified";
How many times have you seen code like this:
1: if (employee is SalariedEmployee);
3: if (salEmployee != null)
5: pay = salEmployee.WeeklySalary;
The code reads better without the ugly cast, and you avoid double-checking the type.
We all know about C# properties, and most of us know about auto properties. They turn code like these two typical properties with backing fields:
1: public class Point
3: private int _x, _y;
5: public int X
6: {
7: get { return _x; }
8: set { _x = value; }
9: }
10:
11: public int Y
12: {
13: get { return _y; }
14: set { _y = value; }
15: }
16: }
Into a much more concise and maintainable piece of code:
3: public int X { get; set; }
4: public int Y { get; set; }
5: }
Much shorter! Whenever you have a simple property that just gets/sets a backing field, you should favor the auto-properties if nothing else for saving a lot of typing! All you need is write the properties with no get/set body and the C# compiler will automatically generate a field for you behind the scenes.
To make things even more fun, you can make auto-properties with asymmetrical access levels! That is, you can make an auto-property "read-only" or "write-only". That is, you can make the get public and the set private or vice versa.
1: public class Asymetrical
3: public string ThisIsReadOnly { get; private set; }
5: public double ThisIsWriteOnly { private get; set; }
This makes it easy to make auto-properties that can be set only by the class itself but read publically and vice-versa (though, in practice write-only properties are rarely useful)..
How many time have you seen a piece of code like this and wondered how long the Sleep was going to before?
1: Thread.Sleep(50);
Now, is that 50 seconds? Milliseconds? It is milliseconds, actually, but what if you ran across something like this in someone’s code:
1: void PerformRemoteWork(int timeout) { ... }
What is this timeout? Seconds? Minutes? Milliseconds? It all depends on the developer! I’ve seen timeouts and intervals in both the BCL and custom code written as either seconds or milliseconds. It’s almost always better to use TimeSpan since it makes it far less ambiguous:
1: void PerformRemoteWork(TimeSpan timeout) { ... }
Now, we don’t need to worry about units because that’s specified when the user constructs the TimeSpan:
1: PerformRemoteWork(new TimeSpan(0, 0, 0, 0, 50));
The disambiguates things from the standpoint of the method itself, but not for the caller! Is the caller passing 50 seconds? Milliseconds? It seems we have a similar issue! This is somewhat confused further by the fact that there are 5 constructs for TimeSpan and they are not all consistent:
1: TimeSpan();
2: TimeSpan(long ticks);
3: TimeSpan(int hours, int minutes, int seconds);
4: TimeSpan(int days, int hours, int minutes, int seconds);
5: TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds);
Notice how the 3-int constructor is hours minutes seconds, and the 4-int constructor adds days? If you want to specify milliseconds, you need the 5-int constructor. This can be confusing because reading a 4-int constructor may look like hours/seconds/minutes/milliseconds but it’s not.
Enter the TimeSpan static factory methods. These allow you to construct TimeSpans unambiguously:
1: PerformRemoteWork(TimeSpan.FromMilliseconds(50));
Now there’s no ambiguity and it’s perfectly readable! No chance of misconstruing the parameters. There’s also:
1: TimeSpan.FromDays(double days);
2: TimeSpan.FromHours(double hours);
3: TimeSpan.FromMinutes(double minutes);
4: TimeSpan.FromSeconds(double seconds);
So you can easily specify an interval in an unambiguous way. It even works with static readonly fields:
1: public sealed class MessageProducer
3: private static readonly _defaultTimeout = TimeSpan.FromSeconds(30);
4: . . .
I hope you enjoyed these five little wonders, I have a stack more to introduce next week. Hopefully you found one you didn’t know about or had forgotten about and can put it to good use!
Print | posted on Thursday, August 26, 2010 6:32 PM |
Filed Under [
My Blog
C#
Software
.NET
Fundamentals
Little Wonders
] | http://blackrabbitcoder.net/archive/2010/08/26/c.net-five-little-wonders-that-make-code-better-1-of.aspx | CC-MAIN-2018-39 | refinedweb | 1,015 | 63.7 |
Date: March 1998. Last edited: $Date: 2009/08/27 21:38:07 $
Status: . Editing status: incomplete first draft. This explains the rationale for XML namespaces and RDF schemas, and derives requirement on them from a discussion of the process by which we arrive at standards.
Up to Design Issues
(These ideas were mentioned in a keynote on "Evolvability" at WWW7 and this text follows closely enough for you to give yourself the talk below using those slides. More or less. If and when we get a video from WWW7 of the talk, maybe we'll be able to serve that up in parallel.)
The World Wide Web Consortium was founded in 1994 on the mandate to lead the Evolution of the Web while maintaining its Interoperability as a universal space. "Interoperability" and "Evolvability" were two goals for all W3C technology, and whilst there was a good understanding of what the first meant, it was difficult to define the second in terms of technology.
Since then W3C has had first hand experience of the tension beween these two goals, and has seen the process by which specifications have been advanced, fragmented and later reconverged. This has led to a desire for a technological solution which will allow specifications to evolve with the speed and freedom of many parallel deevlopments, but also such that any message, whether "standard" or not, at least has a well defined meaning.
There have been technologies dubbed "futureproof" for years and years, whether they are languages or backplane busses. I expect you the reader to share my cynicism when encountering any such claim. We must work though exactly what we mean: what we expect to be able to do which we could not do before, and how that will make evolution more possible and less painfull.
A rule explicit or implcit in all the email-like Internet protocols has always been that if you found a mail header (or something) which you did not understand, you should ignore it. This obviously allows people to add all sorts of records to things in a very free way, and so we can call it the rul of free extension. It has its advatage of rapid prototyping and incremental deployment, and the disadvantage of ambiguity, confusion, and an inability to add a mandatory feature to an existing protocol. I adopeted the rule for HTML when initially designing it - and used it myself all the time, adding elements one by one. This is one way in which HTML was unlike a conventional SGML application, but it allowed the dramatic development of HTML.
The development of HTML between 1994 and 1998 took place in a cycle, fuelled by the tension between the competitive urge of companies to outdo each other and the common need for standards for moving forward. The cycle starts simply simply bcause the HTML standard is open and usable by anyone: this means that any engineer, in any company or waiting for a bus can think of new ways to extend HTML, and try them out.
The next phase is that some of these many ideas are tried out in prototypes or products, using the fact free extension rule that any unrecongined extensiosn will be ignored by everything which does not understand them. The result is a drmatic growth in features. Some of these become product differentiators, during which time their originators are loth to discuss the technology with the competition. Some features die in the market and diappear from the products. Those successful features have a fairly short lifetime as product differetiators, as they are soon emulated in some equivalent (though different) feature in competeing products.
After this phase of the cycle, there are three or four ways of doing the same thing, and engineers in each company are forced to spend their time writing three of four different versions of the same thing, and coping with the software architectural problems which arise from the mix of different models. This wastes program size, and confuses users. In the case for example, of the TABLE tag, a browser meeting one in a document had no idea which table extension it was, so the situation could become ambiguous. If the interpretation of the table was important for the safe interpretation ofthe document, the server would never know whether it had been done, as an unaware client would blithely ignore it in any case. This internal software mess resulting from having to implement multiple models also threatens future deevlopment. It turns the stable consistent base for future development into something fragmented and inconsistent: it is difficult to design new features in such an environment.
Now the marketting pressure is off which prevented discussions, and there is a strong call for the engineers to get around the W3C table, and iron out a common way of doing things. As this happens, a system is designed which puts together the best aspects of each other system, plus a few weeks experience, so everyone is in the end happier with the result. The companies all go away making public promises to implement it, even though the engineering staff will be under pressure to add the next feature and startthe next cycle. The result is published as a common specification opene to anyone to implement. And so the cycle starts again.
This is not the way all W3C activities have worked, but it was the particular case with HTML, and it illustrates some of the advantages and disadvantages with the free extenstion rule.
The HTML cycle as a method of arriving at consensus on a document has its drawbacks. By 1998, there were reasons to change the cycle.The work in the W3C, which had started off in 1994 with several years backlog of work, had more or less caught up, and was begining to lead, rather than trail, developments. The work was seen less as fire fighting and more as consolitation..
Inthe future it was clear that we needed somehow to set up a modular system which would allow one to add to HTML new standard modules. At the same time, it was clear that with XML available as a manageble version of SGML as a base for anyone to define their own tag sets, there was likely to be a deluge of application-specific and industry-specific XML based languages. The idea of all this happening underthefree extension rule was frightening. Most applications would simply add new tags to HTML. If we continued the process of retrospectively roping into a new bigger standard, the document would grow without limit and become totally unmanageble. The rule of free extesnion was no longer appropriate.
Now let us compare this situation with the way development occus in the world of distributed computing, specifically remote rpocedure call (RPC) and distributed object oriented systems. In these systems, the distributed system (equivalent to the server plus the client for the web) is viewed as a single software system which happens to be spread over several physical machines. [nelson - courier, etc]
The network protocols are defined automatically as a function of the software interfaces which happen to end up being between modules on different machines. Each interface, local or remote, has a well documented structure, and the list of functions (procedures, methods or whatever) and parameters are defined in machine-processable form. As the system is built, the compiler checks that the interfaces required by one module is exactly provided by another module. The interface, in each version of its development, typically has an identifying (typically very long) unique number.
The interface defines the parameters of a remote call, and therefore defines exactly what can occur in a message from one module to another. There is no free extension. If the interface is changed, and a new module made, any module on the other side of the interface will have to be changed too, or you can't build the system.
The great advantage of this is that when the system has been built, you expect it to work. There is no wondering wether a table is being displayed - if you have called the table module, you know exactly what the module is supposed to do, and there is no way the system could be without that module. Given the chaos of the HTML devleopment world, you can imagine that many people were hankering after the well defined interfaces of the distributed computing technology.
With well-defined interfaces, either everything works, or nothing. This was in fact at least formally the case with SGML documents. Each had a document type definition (DTD) refered to at the the top, which defiend in principle exactly what could and could not be in the document. PICS labels were similar in that thet are self-describing: they actually have a URI atthe top which points to a machine-readable description of what can and can't be in athat PICS label. When you see one of these documents, as when you get an RPC mesaage with an interface number on it, you can check whether you understand the interface or not. Another intersting thing you can do, if you don't have a way of processing it, is to look it up in some index and dynamically download the code to process it.
The existence of the Web makes all this much smoother: instead of inventing arbitrary names for inetrfaces, tyou can use a real URI which can be dereferenecd and return the master definition of the interface in real time. The Web can become a decentralised registray of interfaces (languages) and code modules.
The need was clearly for the best of both worlds. One must be able to freely extend a language, but do so with an extension language which is itself well defined. If for example, documents which were HTML 2.0 plus Netscape's version of tables version 2.01 were identified as such, mcuh o the problem of ambiguity would have been resolved, but the rest ofthe world left free to make their own table extensions. This was the goal of the namespaces work in XML.
To be able to use the namespaces work in the extension of HTML, HTML has to transition from being an SGML application (with certain constraints) to being an XML based langauge. This will not only give it a certain ease of parsing, but allow it to build on the modularity introduced by namespaces.
In fact, already in April of 1998 there was a W3C Recommendation for "MathML", defined as as XML langauge and obviously aimed at being usable in the context of an HTML document, but for which there was no defined way to write a combined HTML+MathML document. MathML was already waiting for XML namespaces.
XML namespaces will allow an author (or authoring tool, hopefully) to declare exactly waht set of tags he orshe is using in a document. Later, schemas should allow a browser to decide what to do as a fall back when finding vocabulary which it does not understand.
It is expected that new extensions to HTML be introduced as namespaces, possibly languages in their own right. The intent is that the new languages, where appropriate, will be able to use the existing work on style sheets, such as CSS, and the existing DOM work which defines a programming interface.
Language mixing is an important facility, for HTML, for the evolution of all other Web and application technology. It must allow, in a mixed labguage document, for both langauges to be well defined. A mixed langage document is quiote analogous to a program which makes calls to two runtime libraries, so it is not rocket science. It is not like an RPC message, which in most systems is very strongly ytped froma single rigid definition. (An RPC message can be represented as a structured document but not, in general, vice-versa)
Language mixing is a realtity. Real HTML pages are often HTML with Javascript, or HTML plus CSS, or both. They just aren't declared as such. In real life, many documents are made from multiple vocabularies, only some of which one understands. I don't understand half the information in the tax form - but I know enough to know what applies to me. The invoice is a good example. Many differet coloured copies of the same document used to serve as a packing list, restocking sheet, invoice, and delivery note. Different parts of a company would understand different bits: the financial dividion woul dcheck amounts and signatures, the store would understand the part numbers, and the sales and marketting would define dthe relationship betwene the part numbers and prices.
No longer can the Web tolerate the laxness which HTML and HTTP have been extended. However, it cannot constrain itself to a system as rigid as a classical disributed object oriented system.
The note on namespaces defines some requirements of a language framework which allows new schmata to be developed quite independently, and mixed within one document. This note elaborates on the sorts of things which have to be possible when the evolution occurs.
You may notice than nowhere in the architecture do XML or RDF specify what language the schema should be written in. This is because much of the future power of the system will lie in the power of the schema and related documents, so it isimportant to leave that open as a path for the future. In the short term, yo can think of a schema being written in HTML and english. Indeed, this is enough to tie the significance of documents written in the schema to the law of the land and mkae the document an effective part of serious commercial or other social interaction. You can imagine a schema being in a sort of SGML DTD language which tells a computer program what constraints there are on the structure of documents, but nothing about their meaning. This allows a certain crude validity check to be made on a document but little else.
Now let us imagine further power which we could put into a schema language.
A crucial first milestone for the system is partial understanding. Let's use the scenario of an invoice, like the scenario in the "Extensible languages" note. An invoice refers to two schemata: one is a well-known invoice schema and the other a proprietory part number schema. The requirement is that an invoice processing program can process the invoice without needing to understand the part description.
Somehow the program must find out that the invoice is from its point of view just as valid as an invoice with the details fo the part description stripped out.
One possibility is to mark the part description as "optional" on the text. We could imagine a well-known way of doing this. It could be done in the document itself [as usual, using an arbitrary syntax:]
<item> <partnumber>8137498237</> <optional> <xml:using
<a:partdesc> ... <a:partdesc> </xml:using>
</opional> </item>
There are problems with this. One is that we are relying on the invoice schema to define what in invoice is and isn't and what it means. It would be nice if the designer of the invoice could say whether the item should contain a part description of not, or whether it is possible to add things into the item description or not. But in general if there is something to be said we like to allow it to be said anywhere (like metadata). But for the optionalness to be expressed elsewhere would save the writer of every invoice the bother of having to explicitly.
The other more fundamental problem is that the notion of "optional" is subjective. We can be more precise about "partial understanding" by saying that the invoice processing system needs to convert the document which contains things it doesn't understand into a document which it does completely understand: a valid invoice. However, another agent may which to convert the same detailed invoice into, say, a delivery note: in this case, quite different information would be "optional".
To be more specific, then, we need to be able to describe a transformation from one document to another which preserves "valididy" in some sense. A simple form of transformation is the removal of sections, but obviously there can be all kinds of level of transformation language ranging from the cudest to theturing complete. Whatever the language, statement that given a document x, that some f(x) can be deduced.
In practice, this suggest that one should leave the actual choice of the transformation language as a flexibility point. However, as with most choices of computer language, the general "principle least power" applies:
(@@justify in greater depth in footnote)
While being able to express a very complex function may feel good, the result will in general be less useful. As Lao-Tse puts it, "Usefulness from what is not there". From the point of view of translation algorithms, one usefulness is for them to be reversible. In the case in which you are trying to prove something (such as access to a web site or financial credibility) you need to be able to derive a document of a given form. The rules you use are the pieces of the web of trust and you are looking for a path through the web of trust. Clearly, one approach is to enumerate all the things which can be deduced from a given document, but it is faster to have an idea of which algorithms to apply. Simple ones have input and output patterns. A deletion rule is a very simple case
s/.*foo.*/\1\2/
This is stream editor languge for "Remove "foo" from any string leaving what was on either side". If this rule is allowed, it means that "foo"is optional. @@@ to be continued
Optional features and Partial Understanding
The test of independent invention is a thought experiment which tests one aspect of the quality of a design. When you design something, you make a number of important architectural decisions, such as how many wheels a car has, and that an arch will be used between the pillas of the vault. You make other arbitrary decisions such as the color of the car, the side of the road everyone will drive, whether to open the egg at the big end or the little end.
Suppose it just happens that another group is designing the same sort of thing, tackling the same problem, somewhere else. They are quite unknown to you and you to them, but just suppose that being just as smart as you, they make all the same important archietctural decisions. This you can expect if you believe hat these decisions make logical sense. Imagine that they have the same philosophy: it is largely the philosophy which we are testing. However, imagine that they make all the arbitrary decisions differently. They complement bit 7. They drive on the other other side of the road. They use red buoys on the starbord side, and use 575 lines per screen on their televisions.
Now imagine that the two systems both work (locally), and being usccessful, grow and grow. After a while, they meet. Suddenly you discover each other. Suddenly, people want to work across both systems. They want to connect two road systems, two telephone systems, two networks, two webs. What happens?
I tried originally to make WWW?
(see also WWW and Unitarian Universalism). We could add MMML as a MIME type. And so on. However, if we required all Web servers to synchronise though one and only one master lock server in Waltdorf, we would have found the Mesh required synchronisation though a master server in Melbourne. It would have failed.
No system completely passes the ToII - it is always some trouble to convert.
As the Web becomes the basis for many many applications to be build on top of it, the phenomenon of independent invention will recur again and again. We have to build technology so as to make it easy for systems to pass the test, and so survive real life in an evolving world.
If systems cannot pass the TOII, then we can only achieve worldwide interoperability when one original design has originally beaten the others. This can happen if we all sit down together as a worldwide committee and do a "top down"design of the whole thing before we start. This works for a new idea but not for the automation of something which, like pharmacy or trade, has been going on for centuries and is just being represented in the Semantic Web. For example, the library community has had endless trouble trying to agree on a single library card format (MARC record) worldwide.
Another way it can happen is if one system is dropped completely, leading to a complete loss of the effport put into it. When in the late 1980s Europe eventually abandoned its suite of ISO protocols for networking because they just could not interwork with the Internet, a huge amount of work was lost. Many problems, solved in Europe but not in the US (including network addresses of more than 32 bits) had to be solved again on the Internet at great cost. Sweden actually changed from driving on the left to driving on the right. All over the world, people have changed word processor formats again and again but only at the cost of losing access to huge amounts of legacy information. The test of independent invention is not just a thought experiment, it is happening all the time.
So now let us get more specific about what we really need in the underlying technology of the Semantic Web to allow systems in the future to pass the test of independent invention.
Our first assumption is that we will be smarter in the future. This means that we will produce better systems. We will want to move on from version 1 to version 2, from version n to version n+1.
What happens now? A group of people use version 4 of a word process and share some documents. One touches a document using a new version 5 of the same program. Oen of the other people tries to load it using version 4 of the software. The version 4 program reads the file, and find it is a version5 file. It declares that there is no way it can read the file,as it was produced in the future, and there is no way it can predict the future to know how to read a version 5 file. A flag day occurs: everyone in the group has to upgrade immediately - and often they never even planned to.
So the first requirement is for a version 4 program to be able to read a version 5 file. Of course there will be some features in version 5 that the version 4 program will not be able to understand. But most of the time, we actually find that what we want to achieve can be done by partial understanding - understanding those parts of the document which correspond to functions which exist in version 4. But even though we know partial understanding would be acceptable, with most systems we don't know how to do even that.
The philosophical assumption that we may not be smarter than everyone else (a huge step for some!) leads us to realise that others will have gret ideas too, and will independently invent the same things. It forces us to consider the test of independent invention.
The requirement for the system to pass the ToII is for one program which we write to be able to read somehow (partially if not totally) data written by the program written by the other folks. This simple operation is the key to decentralised evolution of our technology, and to the whole future of the Web.
So we have deduced two requirements for the system from our simple philosophical assumptions:
We are we with the requirements for evolvability so far? We are looking for a tecnology which has free but well defined extension. We want to do it by allowing documents to use mixed vocabularies. We have already found out (from PICS work for example) that we need to be abl eto know whether extension vocabulary is mandatory or can be ignored. We want to use the Web for any registry, rather than any central point. The technology has to be allow an application to be able to convert the output of a future version of itself, or the output of an equivalent program written indpendently, into something it can process, just by looking up schema information.
Now let us look at the world of data on the Web, the Semantic Web, which I expect we expect to become a new force in the next few years. By "data" as opposed to "documents", I am talking about information on the Web in a form specifically to aid automated processing rather than human browsing. "Data" is characterised by infomation with a well defined strcuture, where the atomic parts have wel ldefined types, such as numbers and choices from finite sets. "Data", as in a relational database, normally has well defined meaning which has rarely been written down. When someone creates a new databse, they have to give the data type of each column, but don't have to explain what the field name actually means in any way. So there is a well defined semantics but not one which can be accessed. In fact, the only time you tells the machine anything about the semantics is when you define which two columns of different tables are equivalent in some way, so that they can be used for example as the basis for joining the two databases. (That the meaning of data is only defined relative to the meaning of other data is of course quite normal - we don't expect machines to have any built in understanding of what "zip code" might mean apart from where you can read it and write it and what you can compare it with). Notice that what happens with real databases is that they are defined by users one day, and they evolve. They are rarely the result of a committee sitting down and deciding on a set of concepts to use across a company or an industry, and then designing the data schema. The schema is craeted on the fly by the user.
We can distinguish two ways in which tha word "schema" has been used:
I will use it for the first only. In fact, a syntactic schema dedfines a class of document, and often is accompanied by human documentation which provides some rough semantics.
There is a huge amount ("legacy" would unfairly suggest obsolescence) of data in relational databases. A certain amount of it is being exported onto the web as virtual hypertext. There are many applications which allow one to make hypertext views of difeferent aspects of a database, so that each server request is met by performing adatabse query, and then formatting the result as a report in HTML, with appropriate style and decoration.
Information about information is interesting in two ways. Firstly, it is interesting because the Web society desperately needs it to be able to manage social aspects of information such as endorsement (PICS labels, etc), ownership and access rights to information, privacy policies (P3P, etc), structuring and cataloguing information and a hundred otehr uses which I will not try to ennumerate. This first aspect is discussed elsewhere. (See Metadata architecture about general treatment of metadata and labels, and the Technology and Society domain for overveiw of many of the social drivers and related projects and technology)
The second interest in metadata is that it is data. If we are looking for a language for putting data onto the Web, in a machine understandable way, then metadata happens to be a first application area. Also, because metadat ais fundamental to most data on eth web, it is the focus of W3C effort, while many other forms of data are regarded as applications rather than core Web archietcure, and so are not.
Suppose for example that you run a server which provides online stock prices. Your application which today provides fancy web pages with a company's data in text and graphs (as GIFs) could tomorrow produce the same page as XML data, in tabular form, for machine access. The same page could even be produced at the same URL in two formats using content negotiation, or you could have a typed link between the machine-understandable and person-understandable versions.
The XML version contains at the top (or soemewhere) a pointer to a schema document. This poiner makes the document "self-describing". It is this pointer which is the key to any machine "understanding" of the page. By making the schema a first class object, in other words by giving its URL and nothing else, we are leaving the dooropen to many possibilities. Now it is time to look at the various sorts of schema document which it could point to.
Computer languags can be classified into various types, with various capabilities, and the sort we chose for the schema document, and information we allow the schema fundamentally affects not just what the semantic web can be but, more importantly, how it can grow.
The schema document can, broadly, be one of the following:
We'll go over the pros and cons of each, because none of these should be overlooked, but some are often way better than others.
This may sound like a silly trivial example, but like many trival examples, it is not silly. If you just name your schema somewhere in URI space, then you have identified it. This deosn't offer a lot of help to anyone to find any documentation online, but one fundamental function is possible. Anyone can check compatability: They can compare the schema against a list of schemata they do understand, and return yes or no.
In fact, they can also se an idnex to look up information about the schema, including ifnromation about suitable software to download to add understanding of the document. In fact this level is the level which many RPC systems use: the interface is given a unique but otherwise random number which cannot be dereferenced directly.
So this is the level of machine-understanding typical of distributed ocmputing systems and should not be underestimated. There are lot sof parts of URI space you can use for this: yo might own some http: space (but never actually serve the document at that point) , but if you don't, you can always generate a URI in a mid: ro cid: space or if desperate in one of the hash spaces.
The next step up from just using the Schema identifier as a document tyope identifier is to make that URI one which will dereference to a human-readable document. If you're a computer, big deal. But as well as allowing a strict compatiability test (test for equality of the schema URI), this also allows human beings to get involed if ther is any argument as to what a document means. This can be signifiant! For example, the schema could point to a complete technical spec which is crammed with legalese about what the document does and does not imply and commit to. At the end of the day, all machine-understandable descriptions of documents are all very well, but until the day that they bootstrap themselves into legality, they must all in the end be defined in terms of human-readable legalese to have social effect. Human legalese is the schema language of our society. This is level 2.
Now we move into the meat of the schema system when we start to discuss schema documents which are machine readable. now we are satrting to enable some machine understanding and automatic processing of document types which have not been pre-programmed by people. Ça commence.
The next level we conside is that when your brower (agent, whatever) dereferences the namespace URI, it find a schema which defines the structure of the document. this is a bit like an SGML Doctument type Definition (DTD). It allows you to do everything which the levels 1 and 2 allowed, if it has sufficient comments in it to allow human arguments to be settled.
In addition, a system which has a way of defineing structure allows everyone to have one and only one parser to handle all manner of documents. Any document coming across the threshold can be parse into a tree.
More than that, it allows a document o be validated against allowed strctures. If a memeo contains two subject fields, it is not valid. Tjis is one fo the principal uses of DTDs in SGML.
In some cases, there maybe another spin-off. You canimagine that if the schema document lists the allwoed structrue of the document, and the types (and maybe names) of each element, then this would allow an agent to construct on the fly a graphic user interafce for editing such a document. This was theintent with PICS rating systems: at least, a parent coming across a new rating system would be be given a ahuman-readable descriptoin of the various parameters and would be able to select
The "optional" flag is a term I use here for a common crucial step which can make the difference between chaos and smooth evolution. All you need to do is to mark in the schema of a new version of the language which elements of the langauge can be ignored if you don't understand them. This simple step allows a processor which handled the old language, giventhe schema of the new langauge, to filter it so as to produce a document it can legitimately understand.
Now we have a technology which ahs all the benefits to date, plus it can handle that elusive version 2 to version 1 conversion problem!
Always in langauges there is the balance between the declarative limited langauge, whose foprmulae can be easily manipulated, and the powerful programming language whose programs cannot be analyzed in general, but which have to be left to run to see what they do. Each end of the spectrum has its benefits. In describing a lanuage in terms of another, one way is to provide a black box program, say in Java or Javascript, which will convert from one to the other.
Filters written in turing-complete languages generally have to be trusted, as you can't see what rules they are based on by looking at them. But they can do weird and wonderful things. (They can also crash and loop forever of course!).
A good language for conversion from one XML-based language to another is XSL. It lstarted off as a template-like system for building one document from another (and can be very simple) but is in fact Turning-complete.
When you do publish a program to convert language A to language B, then anyone who trusts it has that capability. A disadvantage is that they never know how it works. You can't deduce things about the individual components of the languages. You can't therefore infer much indirectly about relationships to other languages. The only way such a filter can be used is to get whatever you have into language A and then put it though the filter. This might be useful. But it isn't as fascinating as the option of blowing language A open.
What is fundamentally more exciting is to write down as explicitly as posible wahteth new language means. Sorry, let me take that back, in case you think that I am talking about some absulte meaning of meaning. If you know me, I am not. All I mean is that we write in a machine-processable logical way the equivalences and conversions which are possible in and out of language A from other languages. And other languages.
A specific case of course, is when we document the relationship betwen version 2 and version 1. The schema document for version 2 could explain that all the terms are synonyms, except for some new terms which can be converted to nothing (ie are optional) and some which affect the meaning of the document completely and so if you don't understand them you are stuck.
In a more general case, take a language like iCalendar in RDF (were it in RDF), which is for describing events as would be in a personal organizer. A schema for the language might declare equivalences betwen a calendar's concept of group MEMBER ship and an access control system's concept of group membership; it might declare the equivalence of eth concept of LOCATION to be the text description of a Geographical Information Systems standard's location, and it may declare an INDIVIDUAL to be a superset of the HR department's concept of employee. These bits of information of the stuff of the semantic web, as they allow inference to stretch across the gloabe and conclude things which we knew as whole but no one person knew. This is what RDF and the Semnatic Web logic built on top of it is all about.
So, what will semantic web engine be able to do? They will not all have the same inference abilities or algorithms. They will share a core concept of an RDF statement - an assertion that a given resource has a property with a given value. They will use this as a common way of exchanging data even when their inference rules are not compatible. An agent will be able to read a document in a new version of a language, by looking up on the web the relationship with the old version that it can natively read. It will be able to combine many documents into a single graph of knowledge, and draw deductions from the combination. And even though it might not be able to find a proof of a given hypothesis, when faced with an elaborated proof it will be able to check its veracity.
At this stage (1998) we need relational database experts in the XML and RDF groups, [2000 -- include ontology and conceptual graph and knowledge representation experts].
Examples abound of language mixing and evolution in the real world which make the need for these capabilities clear. There is a great and unused overlap in the concepts used by, for example, personal information managers, email systems, and so on. These capabilities would allow information to flow between these applications.
You just have to look at the history of a standard such as MARC record for library information to see that the tension between agreeing on a standard (difficult and only possible for a common subset) and allowing variations (quick by not interoperable) would be eased by allowing language mixing. A card could be written out in a mixture of standard and local terms.
The real world is full of times when conventions have been developed separately and the relationships have been deduced afterward: hence the market for third party converters of disk formats, scheduler files, and so on.
I have left open the discussion as to what inference power and algorithms will be useful on the semantic web precisely because it will always be an open question. When a language is sufficiently expressive to be able to express teh state of the real world and real problems then there will be no one query engine which will be able to solve real problems.
We can, however, guess at how systems might evolve. No one at the beginning of the Web foresaw the search engines which could index almost all the web, so these guesses may be very inaccurate!.
In fact I thing we will see a huge market for interesting new algorithms, each to take advantage of particular characteristics of particular parts of the Web. New algorithms around electronic commerce may have directly beneficial business models, to there will be incentive for their development.
Imagine some questions we might want to ask an engine of the future:
All these involve bridging barriers between domains of knowledge, but they do not involve very complex logic -- except for the tax form, that is. And who knows, perhaps in the future the tax code will have to be presented as a formula on the semantic web, just as it is expected now that one make such a public human-readable document available on the Web.
There are some requirements on the Semantic Web design which must be upheld if the technology is to be able to evolve smoothly. They involve both the introduction of new versions of one language, and also the merging of two originally independent languages. XML Namespaces and RDF are designed to meet these requirements, but a lot more thought and careful design will be needed before the system is complete.
Lao-TseLao-Tse
The Space Within.
(UU-STLT#600)
...
Imagine that the EU and the US independently define RDF schemata for an invoice. Invoice are traded around Europe with a schema pointer at the top which identifies the smema. Indeed, the schema may be found on the web.
Next: Metadata architecture
Up to Design Issues
Tim BL | http://www.w3.org/DesignIssues/Evolution.html | CC-MAIN-2015-06 | refinedweb | 6,906 | 58.01 |
Split a list based on a condition?
good = [x for x in mylist if x in goodvals]bad = [x for x in mylist if x not in goodvals]
is there a more elegant way to do this?
That code is perfectly readable, and extremely clear!
# files looks like: [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ... ]IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')images = [f for f in files if f[2].lower() in IMAGE_TYPES]anims = [f for f in files if f[2].lower() not in IMAGE_TYPES]
Again, this is fine!
There might be slight performance improvements using sets, but it's a trivial difference, and I find the list comprehension far easier to read, and you don't have to worry about the order being messed up, duplicates being removed as so on.
In fact, I may go another step "backward", and just use a simple for loop:
images, anims = [], []for f in files: if f.lower() in IMAGE_TYPES: images.append(f) else: anims.append(f)
The a list-comprehension or using
set() is fine until you need to add some other check or another bit of logic - say you want to remove all 0-byte jpeg's, you just add something like..
if f[1] == 0: continue
Here's the lazy iterator approach:
from itertools import teed.
Because it's lazy you can use it on any iterator, even an infinite one:
from itertools import count, islicedef is_prime(n): return n > 1 and all(n % i for i in xrange(2, n))primes, not_primes = split_on_condition(count(), is_prime)print("First 10 primes", list(islice(primes, 10)))print("First 10 non-primes", list(islice(not_primes, 10)))
Usually though the non-lazy list returning approach is better:
def split_on_condition(seq, condition): a, b = [], [] for item in seq: (a if condition(item) else b).append(item) return a, b
Edit: For your more specific usecase of splitting items into different lists by some key, heres a generic function that does that:
DROP_VALUE = lambda _:_def split_by_key(seq, resultmapping, keyfunc, default=DROP_VALUE): """Split a sequence into lists based on a key function. seq - input sequence resultmapping - a dictionary that maps from target lists to keys that go to that list keyfunc - function to calculate the key of an input value default - the target where items that don't have a corresponding key go, by default they are dropped """ result_lists = dict((key, []) for key in resultmapping) appenders = dict((key, result_lists[target].append) for target, keys in resultmapping.items() for key in keys) if default is not DROP_VALUE: result_lists.setdefault(default, []) default_action = result_lists[default].append else: default_action = DROP_VALUE for item in seq: appenders.get(keyfunc(item), default_action)(item) return result_lists
Usage:
def file_extension(f): return f[2].lower()split_files = split_by_key(files, {'images': IMAGE_TYPES}, keyfunc=file_extension, default='anims')print split_files['images']print split_files['anims'] | https://codehunter.cc/a/python/split-a-list-based-on-a-condition | CC-MAIN-2022-21 | refinedweb | 468 | 53.21 |
Contributed by Brian Leonard and Chris Kutler
July 2008 [Revision number: 6.1-1]
This tutorial demonstrates how
to use the Java API in Rails applications.
In this tutorial, you use the FreeTTS speech
synthesis Java libraries to enable
users to listen to blog posts.
Contents
To complete this tutorial, you need the following
software.
* The NetBeans IDE 6.1 with GlassFish and MySQL Bundle
download provides you with the complete software
package required for this tutorial.
** The NetBeans IDE 6.1 downloads with Ruby and Rails
support include the Rails 2.0.2 framework.
This tutorial builds on the
Creating a Ruby Weblog in 10 Minutes
tutorial.
You must first complete that tutorial before proceeding with
this tutorial. If you completed the
Building Relationships Between Rails Models tutorial,
you can use that project as well. Ensure that the
project uses the JRuby platform.
Alternatively, you can use your own JRuby Rails project,
and modify the steps to use the appropriate controller,
model, and column names.
You use the project's Properties window to make
Java JAR files available to the Rails server.
In the Projects window, right-click
the rubyweblog project node and choose
Properties from the pop-up menu.
Select Java in the Categories pane, as shown
in the following figure.
Note: The Include Java checkbox has no effect
on the behavior of the IDE. This checkbox will be
removed in future releases.
Click Add JAR/Folder.
In the Add JAR/Folder dialog box, navigate to the
lib directory under the
folder into which you unzipped the
FreeTTS
1.2 download.
Use Ctrl-Click to select all seven JAR files in the
lib folder, as shown in the following figure, and click Open.
The JAR files appear in the Run-time Libraries list
in the Project Properties window, as shown next.
Click OK.
Click the X button
that appears in the lower right corner
of the IDE, which is shown
in the following figure, to stop the
WEBrick server. The JVM needs to be restarted to
include the FreeTTS libraries.
You can also stop the server by expanding
Servers in the Services window, expanding
the WEBrick node,
right-clicking the server instance's node,
and choosing Stop from the pop-up menu.
Look at the lower right corner of the
IDE. If the WEBrick status still appears and
it shows that the server is running, you might have
encountered
Issue 131628
- WEBrick fails to stop. To resolve this
problem, restart the IDE or
complete the following steps.
Open a terminal window.
Execute the command java-bin-path/jps -l.
You should see three Java processes: one is JPS, one is the NetBeans process,
and the third is WEBrick (org.jruby.Main), which was started by the IDE.
Execute the command kill -9 process id.
For the previous example, the command would be kill -9 16554.
Next, you add an action to the controller to speak
the title and body of the blog entry that is passed
in the :id.
Press Alt+Shift+O
(use Ctrl+Shift+O on the Mac) to
open the Go to File dialog box.
Type posts_controller.rb in the File Name
text box and click OK to open the file
in the editor.
Add to the top of the file the include
statement and the two import
statements that are shown in bold in the following code sample.
include Java
import com.sun.speech.freetts.Voice
import com.sun.speech.freetts.VoiceManager
class PostsController < ApplicationController
# GET /posts
# GET /posts.xml
...
When you reference classes and packages from
top-level packages other than
com, org, java, and javax,
you must either put the name in quotes, such as "mypkg.util.Init",
or prepend Java::, such as Java::mypkg.util.Init.
Copy the constant assignment and
the speak action that are shown in bold in
the following code sample and paste them into
the class definition.
include Java
import com.sun.speech.freetts.Voice
import com.sun.speech.freetts.VoiceManager
class PostsController < ApplicationController
SPOKEN_FIELDS = [:title, :body]
def speak
voice = VoiceManager.instance.get_voice('kevin16')
voice.allocate
# Get the text to speak
# Note that #find_by_id returns nil
# where #find throws an exception
post = Post.find_by_id(params[:id])
speak_these_items = []
if post then
speak_these_items = SPOKEN_FIELDS.map {
|field| post.send(field)}
sanitizer = HTML::FullSanitizer.new
speak_these_items = speak_these_items.map {
|s| sanitizer.sanitize(s) }
else
# No post was found so let the user know
speak_these_items << 'No post was found'
end
# Speak the text
speak_these_items.each { |s| voice.speak(s) }
redirect_to :back
end
...
Next, you edit the routing file to add a route
for the speak action.
Look for the line that begins with map.resources :posts.
If you completed the
Building Relationships Between Rails Models tutorial,
the line will be map.resources :posts, :has_many=> :comments.
Add the following code to the end of the line.
, :member => {:speak => :get}
This code adds a member hash to the post resource. The
hash is composed of action-HTTP verb pairs. The
:speak => :get pair
creates a route named speak_post. The
URL for this route is posts/:post_id/speak.
You use the link_to method to create a link tag
that maps to the controller's speak action.
To open the show.html.erb
file, right-click any line in the show action (the
method that starts with def show) and
choose Navigate > Go to Rails Action or View
from the pop-up menu.
Place the cursor on the blank line above
the first link_to statement.
Type liai then press Tab to expand
the LInk Action Index template. Set the arguments to
"Speak", speak_post_path(@post),
then add the | separator
character, as shown in bold in the following code sample.
<%= link_to "Speak", speak_post_path(@post) %> |
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
Click the Run Main Project button
to save all
changes, start the server,
and display the main page in a browser window.
Click the permalink link for any blog post to
show the post's detail page, then
click the Speak link to hear
the post's title and text.
If you get the error message
cannot load Java class com.sun.speech.freetts.Voice,
you might not have successfully stopped the WEBrick server. See
Step 9 in the Adding Java Libraries to the JRuby Class Path section.
This step explains how to manually stop the server. Alternatively,
stop and restart the IDE. The server
must be restarted for the Java classes to be included.
To obtain support and stay informed of the latest
changes to the NetBeans Ruby development features, join the
users
@
ruby.netbeans.org
and
dev
@
ruby.netbeans.org
mailing lists.
>> More NetBeans Ruby Documentation | http://www.netbeans.org/kb/61/ruby/java-ruby.html | crawl-002 | refinedweb | 1,100 | 67.55 |
Top: Streams: logfile
#include <pstreams.h> class logfile: outfile { logfile( [ const string& filename, bool append = true ] ); void putf(const char* fmt, ...); }
The lofgile class inherits all public methods and properties from outfile, but differs in the following:
logfile::logfile( [ const string& filename, bool append = true ] ) creates an output file stream, but does not open the file. When opening a file with open(), the file pointer is positioned at the end of the file, unless append is set to false. Filename and append parameters are optional.
void logfile::putf(const char* fmt, ...) is a thread-safe version of outstm::putf().
See also: iobase, outstm, outfile, Examples | http://www.melikyan.com/ptypes/doc/streams.logfile.html | crawl-001 | refinedweb | 105 | 58.99 |
In this tutorial, We are going to learn about time package in go. We will also see how to use time package in program with example.
It provides functionality for measuring and displaying time.
How to import time package in program:
import “time”
A computer has two different clocks:
- Wall clock
- Monotonic clock
Monotonic and Wall clock
—–
Let’s talk about wall clock first. Everyone knows about the wall clock. It is used to get the current time of the day.
This clock time may have variations, reason being Suppose If it is synchronised with NTP (Network Time Protocol) then after synchronisation, the local clock of our server can jump either backward or forward in time. Hence, measuring a duration from the wall clock can be biased.
In monotonic clock, time always moves forward. if we have to measure durations, we must use the monotonic-clock.
That’s why as a software developer, to measure the duration (time interval) of an execution of code, we use monotonic clock.
monotonic clock reading has no meaning outside the current process.
time.Now() returns monotonic clock reading in go.
Example:
start_time := time.Now()
… operation that takes around 10 milliseconds …
end_time := time.Now()
elapsed := end_time.Sub(start)
Program:
package main import ( "fmt" "time" ) func main() { start_time := time.Now() time.Sleep(10) end_time := time.Now() elapsed := end_time.Sub(start_time) fmt.Println("Elapsed time: ", elapsed) }
Output:
Elapsed time: 18.813µs
time package has many functions which are given below :
- Sleep()
- Until()
- Since()
- Unix()
- Weekday()
- Now()
- Add()
- AddDate()
- Milliseconds()
- Microseconds()
- Hours()
- Seconds()
- Nanoseconds()
- Minutes()
To learn more about golang, Please refer given below link.
References: | https://www.techieindoor.com/go-time-package-in-go/ | CC-MAIN-2021-43 | refinedweb | 268 | 67.76 |
Development moved!
Development of Enso has moved away from here to Launchpad. See EnsoWiki.com for details about where the code is, how to get Enso running, and current development progress.
The remainder of this page is left here for historical reasons.
Introduction
The Enso Project is the open-source release of Enso, an extensible, cross-platform, graphical command-line interface written in Python.
Enso's goal is to provide a way of accessing whatever piece of functionality you need--be it calculating an expression, calling up a map, or performing a Google search--with a few, semantically meaningful keystrokes.
Enso was originally commercial software created and sold by Humanized, Inc. In early 2008, a new BSD-licensed open-source repository was created for Enso, and much of its code was inherited from the commercial version.
Commercial Enso vs. Open-Source Enso
The version of Enso that can be downloaded from The Humanized Website is known as the "commercial" version of Enso; it is sometimes also called the "frozen" version of Enso.
Commercial Enso is a binary-only distribution, based on a closed-source code-line kept on a private SVN server. Development on it has ceased and will not be resumed. Development-wise, it is a dead end; but it will continue to be the version that users download and install, and Humanized will continue to distribute and support it, until such time as development on the open source Enso code-line creates a suitable replacement.
Commercial Enso runs on Windows 2000, XP, and Vista only.
Open-Source Enso consists of the code tree located at The Enso Project and was started "from scratch" in early 2008. Modules and chunks of code were rapidly brought over from the old code and integrated; this process could be thought of as a combination of code migration and massive refactoring to remove all the cruft that Enso no longer needed, and to make Enso more flexible towards certain things that it needs to support better, such as internationalization and cross-platform support.
Another way to view the difference is that Commercial Enso embedsPython, whereas Open-Source Enso attempts to extend Python. The difference between the two, and their implications, is nicely summarized in Glyph Lefkowitz's article Extending vs. Embedding: There is Only One Correct Decision.
Once Open-Source Enso matures to the point that it's at least as functional and stable as Commercial Enso, we'll also package and distribute a pre-compiled binary in whatever way is most humane for non-technical end users.
More Information
For more information about the use of and philosophy behind Enso, you may want to visit the following resources:
- The Enso Product Page on humanized.com
- The Graphical Keyboard User Interface by Alex Faaborg
- The Linguistic Command Line by Aza Raskin
Getting Enso
At present, the primary way to obtain Enso is by retrieving the code via Subversion. Once that is done, please read the READMEfile contained in the root directory to build the software.
In the future, pre-built binaries of Enso will be available on relevant platforms so that those who are developing commands for Enso (as opposed those who are developing Enso itself) will be able to use it without needing a C compiler.
The remainder of this documentation assumes that you have Enso up and running, and can use it to execute commands.
Extending Enso
Creating Enso Commands
Creating, running, and modifying Enso commands is intended to be as easy as possible. To create a command, simply create an .ensocommands file in your home directory if it doesn't already exist (if you're on Windows, this directory is pointed to by the HOME environment variable). This file is just a Python script containing classes and functions representing available commands.
Hello World: Displaying Transparent Messages
A simple command called "hello world" can be created by entering the following into your .ensocommands file:
def cmd_hello_world(ensoapi): ensoapi.display_message("Hello World!")
As soon as the .ensocommands file is saved, the Enso quasimode can be entered and the command used: Enso scans this file and its dependencies whenever the quasimode is entered, and if the contents have changed, Enso reloads them, so there is never a need to restart Enso itself when developing commands.
From the source code of the command, a number of things can be observed:
- A command is a function that starts with the prefix cmd_.
- The name of a command is everything following the prefix, with underscores converted to spaces.
- A command takes an ensoapi object as a parameter, which can be used to access Enso-specific functionality. 1
You may want to take the time to play around with the "hello world" example; try raising an exception in the function body; try adding a syntax error in the file and see what happens. It should be apparent that such human errors have been accounted for and are handled in a way that is considerate of one's frailties, allowing the programmer to write and test code with minimal interruptions to their train of thought.
1One may wonder why the ensoapi object has to be explicitly passed-in rather than being imported. The reasons for this are manifold: firstly, importing a specific module, e.g. enso.api, would tie the command to a particular implementation of the Enso API. Yet it should be possible for the command to run in different kinds of contexts--for instance, one where Enso itself is in a separate process or even on a separate computer, and ensoapi is just a proxy object. Secondly, explicitly passing in the object makes the unit testing of commands easier.
Adding Help Text
When using the "hello world" command, you may notice that the help text displayed above the command entry display isn't very helpful. You can set it to something nicer by adding a docstring to your command function, like so:
def cmd_hello_world(ensoapi): "Displays a friendly greeting." ensoapi.display_message("Hello World!")
If you add anything past a first line in the docstring, it will be rendered as HTML in the documentation for the command when the user runs the "help" command:
def cmd_hello_world(ensoapi): """ Displays a friendly greeting. This command can be used in any application, at any time, providing you with a hearty salutation at a moment's notice. """ ensoapi.display_message("Hello World!")
Interacting with The Current Selection
To obtain the current selection, use ensoapi.get_selection(). This method returns a selection dictionary, or seldict for short. A seldict is simply a dictionary that maps a data format identifier to selection data in that format.
Some valid data formats in a seldict are:
- text: Plain unicode text of the current selection.
- files: A list of filenames representing the current selection.
Setting the current selection works similarly: just pass ensoapi.set_selection() a seldict containing the selection data to set.
The following is an implementation of an "upper case" command that converts the user's current selection to upper case:
def cmd_upper_case(ensoapi): text = ensoapi.get_selection().get("text") if text: ensoapi.set_selection({"text" : text.upper()}) else: ensoapi.display_message("No selection!")
Command Arguments
It's possible for a command to take arbitrary arguments; an example of this is the "google" command, which allows you to optionally specify a search term following the command name. To create a command like this, just add a parameter to the command function:
def cmd_boogle(ensoapi, query): ensoapi.display_message("You said: %s" % query)
Unless you specify a default for your argument, however, a friendly error message will be displayed when the user runs the command without specifying one. If you don't want this to be the case, just add a default argument to the command function:
def cmd_boogle(ensoapi, query="pants"): ensoapi.display_message("You said: %s" % query)
If you want the argument to be bounded to a particular set of options, you can specify them by attaching a valid_args property to your command function. For instance:
def cmd_vote_for(ensoapi, candidate): ensoapi.display_message("You voted for: %s" % candidate) cmd_vote_for.valid_args = ["barack obama", "john mccain"]
Prolonged Execution
It's expected that some commands, such as ones that need to fetch resources from the internet, may take some time to execute. If this is the case, a command function may use Python's yield statement to return control back to Enso when it needs to wait for something to finish. For example:
def cmd_rest_awhile(ensoapi): import time, threading def do_something(): time.sleep(3) t = threading.Thread(target = do_something) t.start() ensoapi.display_message("Please wait...") while t.isAlive(): yield ensoapi.display_message("Done!")
Returning control back to Enso is highly encouraged--without it, your command will monopolize Enso's resources and you won't be able to use Enso until your command has finished executing!
Class-based Commands
More complex commands can be encapsulated into classes and instantiated as objects; in fact, all Enso really looks for when importing commands are callables that start with cmd_. This means that the following works:
class VoteCommand(object): def __init__(self, candidates): self.valid_args = candidates def __call__(self, ensoapi, candidate): ensoapi.display_message("You voted for: %s" % candidate) cmd_vote_for = VoteCommand(["barack obama", "john mccain"])
Command Updating
Some commands may need to do processing while not being executed; for instance, an open command that allows the user to open an application installed on their computer may want to update its valid_args property whenever a new application is installed or uninstalled.
If a command object has an on_quasimode_start() function attached to it, it will be called whenever the command quasimode is entered. This allows the command to do any processing it may need to do. As with the command execution call itself, on_quasimode_start() may use yield to relegate control back to Enso when it knows that some operation will take a while to finish.
Including Other Files
The .ensocommands file may include other files containing command definitions by using Python's execfile() built-in method. Enso automatically keeps track of what files command objects come from; if any of those files change, it reloads .ensocommands, which should in turn reload those files.
Python's standard import statement can also be used from command scripts, of course, but the disadvantage of doing this with evolving code is that--at present, at least--imported modules won't be reloaded if their contents change. 2
2This feature in particular is something that can, and probably will change a lot in the future, as code reuse via execfile()isn't particularly Pythonic. Other options, among others, include having commands live in their own process, their own tinypy-based virtual machine, and autodetecting changes in modules and re-importing them like Django's development server does.
Enso Plugins and The .ensorc File
One way to extend and customize Enso is through the use of plugins. A plugin is just a Python module or package with a single function in it, load(), which takes no parameters, and is called when the Enso quasimode is about to start itself.
The easiest way to add a plugin is through an .ensorc file, which can be created in your home directory (if you're on Windows, this directory is pointed to by the HOME environment variable). This file is actually just a Python script that's executed before any other code when Enso starts up.
The following .ensorc tells Enso to load a plugin contained at mypackage.myplugin:
import enso.config enso.config.PLUGINS.extend( ["mypackage.myplugin"] ) | http://code.google.com/p/enso/ | crawl-002 | refinedweb | 1,906 | 51.68 |
Prev
Java NetBeans Experts Index
Headers
Your browser does not support iframes.
Re: Netbeans/Cygwin/JDK issue
From:
Mark Space <markspace@sbc.global.net>
Newsgroups:
comp.lang.java.programmer
Date:
Wed, 26 Sep 2007 21:26:13 -0700
Message-ID:
<ThGKi.11892$924.8324@newssvr23.news.prodigy.net>
saad wrote:
To add, first few lines of Simulator.java read:
package A.S;
import A.C.*;
import A.P.*;
import java.util.*;
import java.io.*;
and this file also has a method with this signature:
public class Simulator {
public static void main ( String [] args )
{
// ...
}
}
That's where things start. Check to make sure you are running the
correct file. You could also look at args to see how %1 %2 %3 are used.
To set the classpath, just add it to the existing CLASSPATH variable.
For example:
c:\my\stuff\A\S\Simulator.class
CLASSPATH=c:\my\stuff
The java command should now recognize A\S as corresponding to the
package A.S and find the Simulator.class file.
(For Cygwin, I guess you'd use your example and set CLASSPATH=/c/java)
If your problem is that you added an extra /a on the end, this is pretty
remedial. Better go read up on Java or you're going to have a very
tough time. The Sun tutorial is good.
I'd use the CLASSPATH because -cp over-rides your existing classpath.
The -cp switch works for simple self-contained programs but may not work
if there are extra .jar's or other .class files that are needed
elsewhere on the disk. It's easiest to set CLASSPATH from the Control
Panel, imo. Just add ;c:\my\stuff to the end of the CLASSPATH variable
and you should be ok.
For the NetBeans thing... New Project->General->Java Project with
Existing Sources. *coughRTFMcough*!] | https://preciseinfo.org/Convert/Articles_Java/NetBeans_Experts/Java-NetBeans-Experts-070927072613.html | CC-MAIN-2022-27 | refinedweb | 303 | 70.09 |
Hey,
Here is my code plus the error message I'm getting:
What could I be doing wrong?
abs() is a function that returns the absolute value of whatever is placed inside the parentheses. In this case we want the absolute value of m, so we would write
return abs(m)
The extra None that is printed in the console is a result of how Codecademy processes your code. If you were to run the same code in another interpreter you would not see that None. If you would like to test this you can use the
repl.it
labs
Exactly ! That's what my question is.. I don't get it in other
interpreters. How am I supposed to complete this exercise now? And
continue with the course. Please give some suggestion.
The problem is with your if statement. Currently you have:
if type(d) == int or float:
And I understand why it would be tempting to write it that way, but with programming we need to be very specific so it actually needs to be written as:
if type(d) == int or type(d) == float
Also, as @muzakir said, make sure you have:
else: return 'nope'
Thank you so much mkordik. It's solved but I still don't understand why it didn't throw a syntax error or something
The syntax wasn't wrong in terms of Python being able to process it. It was wrong because it wasn't checking what you really wanted to check.
Here is a good post on why it did what it did:
def distance_from_zero(n):
if type(n) == int or type(n) == float:
return abs(n)
else:
return "Nope" | https://discuss.codecademy.com/t/19-review-built-in-functions/53345 | CC-MAIN-2018-51 | refinedweb | 279 | 80.21 |
I am trying to make a program that takes input from a .txt document and copies it to another .txt document. I understand that the >> operator of ifstream stops at each whitespace. Is there any way to set it so that it reads through the whitespace? For example, if I wanted to copy this sentence...
"This is a sentence I would like to copy."
from one .txt to another .txt, using >> would only copy the "This" string. Is there a way to make it read through the whitespace so it copies the entire sentence? Or do I have to tokenize the sentence in a loop using " " as my delimiter? Here is a watered down version of my code. Thanks.
Code:#include <fstream> #include <iostream> #include <cstring> using namespace std; int main(){ string str; ifstream inputFile ( "input.txt" ); //input.txt contains sentence I want to copy inputFile >> str; inputFile.close(); ofstream outputFile ( "output.txt" ); outputFile << str; outputFile.close(); return 0; } | https://cboard.cprogramming.com/cplusplus-programming/80217-how-do-i-remove-whitespace-using-operator-ifstream.html | CC-MAIN-2017-13 | refinedweb | 159 | 78.65 |
nah theres a swimming pool at the top of the building at the end of the movie Hackers. I think.
Printable View
nah theres a swimming pool at the top of the building at the end of the movie Hackers. I think.
Thats the way I would do it.Thats the way I would do it.Quote:
Originally posted by Polymorphic OOP
You should write a program, put it on a disk and into her computer so that when she turns it on, it pops up with a prompt:
:D:DCode:
Will you marry me (y/n)?
Hehe...Hehe...Code:
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
char marry[256];
cout<<"This is from [yournamehere]\n";
cout<<"Will you marry me? (y/n)\n";
cout<<"If you need more time to decide, enter t.";
cin.getline(marry,256,'\n');
if(marry=='y')
{
system("cls");
cout<<"Really?! Call [yourphonenumber] and tell me that!\n";
getch();
return 0;
}
if(marry=='n')
{
system("cls");
cout<<"Oh, ok. Call [yourphonenumber] and tell me that, please.\n";
getch();
return 0;
}
if(marry=='t')
{
system("cls");
cout<<"Oh, so you need some more time to decide...call me and tell me."\n";
getch();
}
else
{
cout<<"please input something valid\n";
}
return 0;
}
Ask her while you're speeding down the highway... if she says no, hammer your foot on the gas and ask again.
How about ejecting her door? and ask again?;)How about ejecting her door? and ask again?;)Quote:
Originally posted by Eibro
Ask her while you're speeding down the highway... if she says no, hammer your foot on the gas and ask again.
even still, you could ask once, if she says no, push in the cigarette lighter and ask again....(i think you see where im going w/this)even still, you could ask once, if she says no, push in the cigarette lighter and ask again....(i think you see where im going w/this)Quote:
Originally posted by Eibro
Ask her while you're speeding down the highway... if she says no, hammer your foot on the gas and ask again.
Nooo......... I hope nothing too sick:)Nooo......... I hope nothing too sick:)Quote:
Originally posted by dP munky
i think you see where im going w/this)
I agree with him... You should think of that very well...I agree with him... You should think of that very well...Quote:
Originally posted by adrianxw
I don't know you well enough or your girlfriend at all.
The only comment I'll make, based on personal experience, is that marrying at a young age is often a bad idea as neither of the personalities of the two parties are complete. What seems terribly right at 20 can feel so horribly wrong at 25. Messy, expensive, and somewhat traumatising to sort out.
Whatever you decide good luck.
If you're gonna do it, make it creative. Here's a good one (but you'll need a little cooperation).
Go to her boss. Tell her your situation and ask for a little help. Have the boss bring her in the office and talk about how they've been having problems with her and they are going to take some actions. Then, have him hand her a letter and tell her that the letter describes all of their problems. On the letter, have the good ol' "Will you marry me? love (your name)" As she's reading it, pop out of a closet or something. Then propose....
Or if you don't use my way, at least keep it creative.
My brother knew his wife for around 6 months (technically longer b/c she was my sister's friend but my brother never talked to her before that time) before he propsed to her. They got married at the ages of 20 (my brother) and 19 (his wife) in December of 99. They have been married ever since then and are doing perfectly fine. It really all depends on the particular people, so if you feel that getting married is the right decision for the right reasons then do so. Good luck either way.
Great idea! Its better than any other way I could think of. This one's original and brings out the 'you' in the question.Great idea! Its better than any other way I could think of. This one's original and brings out the 'you' in the question.Quote:
Originally posted by Polymorphic OOP
You should write a program, put it on a disk and into her computer so that when she turns it on, it pops up with a prompt:
I made a flash applet a while back that asks a yes/no question, and have the no button fly away on mouse over and come back when the mouse leaves the area. I guess you can implement that idea as sort of a "security precaution". lol :p
Ok, ive been busy today at work and finally found some free time to myself so i figured i see what anyone had to say and man was i suprised at the number of responses. First let me say that were not all that young, im 22, shes 21. Weve been together for a little over a year. Were almost always together, we both have the same interests in music, movies, games, cars, reading material, outdoors, food, ............. and i could go on forever. Ive dated plenty of girls and let me say that the fealings I get from being around her are the most amazing ive felt in my life. In our time together weve never even fought once, no arguments or disagrements, its pretty amazing to get alone with someone like this. Anyways the reasons I want to ask her to marry me is that first off I love her, I love being around her, I love making her smile and hearing her laugh, I love the fealing of holding her all night and waking up so the first thing I see is her beautiful face so that Im able to wake her with a soft kiss, and I dont think my life would be complete without knowing that shes going to be next to me for the rest of it. Ive thought of several ways of asking her but I dont want to do the traditional approch of taking her to a romantic dinner or something. I think what im going to do is flash something to a GBA disk and put it in hers so that when she turns it on to play games in class (tisk tisk! :-p) she will see it and hopefully text message me.
awwwww, a GBA proposal. How romantic!
I have a better idea
Materials:
Red Meat
Red food coloring
Fill your bathtub with water, add coloring untill water is crimson red. Cut the meat into hunks and plop it in the "water".
Put some coloring on your feet, and make red footprints to the tub. Open your door, and invite your future wife over. Climb into the tub and wait. When she enters the bathroom and runs over to you, burst out of the tub screaming "WILL YOU MARRY ME".
Damn that's a good idea, I might try it if/when I get married...
If you have your own place, you should invite her to live with you
a while. My wife and I lived together for six months before I
finally got us both drunk and popped the question. The following
day I asked her again when we were both sober just to be
sure. We're still together, so it worked for us.
We live together right now, have been for 3 months. Not our own place but close enough, were living in her cousins basement, it doenst have access from upstaris so its private and pretty nice, it has a small kitchen, b-room w/ shower/tub and a bedroom and a living room its bigger than an apartment but still small but nice (just hate hearing her nephew and niece cry upstairs) | http://cboard.cprogramming.com/brief-history-cprogramming-com/33488-should-i-ask-her-2-print.html | CC-MAIN-2015-27 | refinedweb | 1,351 | 81.22 |
Opened 9 years ago
Closed 8 years ago
Last modified 5 years ago
#5943 closed (fixed)
django-admin.py should work like manage.py if --setting option is provided
Description
Right now, app-provided commands aren't included, startproject is still available, and startapp uses the current directory rather than the project directory.
The attached patch makes django-admin.py command --settings=blah work just like manage.py invoked on the same project.
Attachments (4)
Change History (30)
comment:1 Changed 9 years ago by
comment:2 Changed 9 years ago by
I think the new patch works. (At least, it passes the tests.) I'd missed an ImportError and forgot that it might be possible to have INSTALLED_APPS, but not a project_directory (as in the tests).
Please check lines 87 and 92 carefully. I think those are the only errors that could come up during the try blocks, but I might have missed something.
comment:3 Changed 9 years ago by
comment:4 Changed 9 years ago by
The patch was undone because it kills
django-admin.py when the --settings option isn't provided, for example, if it's given using the DJANGO_SETTINGS_MODULE environment variable. I now have time again to look at what the problem is.
comment:5 follow-up: 7 Changed 9 years ago by
This was rolled back by adrian in [6871] because it was breaking django-admin.py runserver. The current patch wouldn't apply cleanly to [7229], but I went through and applied it by hand and it seems to work fine for me. django-admin.py is picking up custom commands and django-admin.py runserver works fine both with a
--settings flag and the DJANGO_SETTINGS_MODULE environment variable. I've attached a new version of the patch that applies to [7229]. I'm tempted to just check this in, but I feel like maybe I'm missing something. Anyone want to apply this and try to get it to break?
comment:6 Changed 9 years ago by
comment:7 Changed 9 years ago by
Replying to jkocherhans:
Anyone want to apply this and try to get it to break?
I have applied the patch. It applied cleanly and, though I didn’t test every command,
runserver and
syncdb (creating a new database and first superuser) work with both
DJANGO_ADMIN_MODULE and the
--settings option.
comment:8 Changed 9 years ago by
I have applied the patch cleanly and has been working fine for me so far. Works ok with some custom commands I have as well.
comment:9 Changed 9 years ago by
I have applied the attached patch to django-newformsadmin r7818 (manually, it appears the patch chokes on the docstring).
django-admin.py runserver will choke on django apps configured with setuptools namespace (eg:
__import__('pkg_resources').declare_namespace(__name__); but
django-admin.py runserver --settings=$DJANGO_SETTINGS_MODULE works fine.
comment:10 Changed 9 years ago by
comment:11 Changed 9 years ago by
comment:12 Changed 9 years ago by
Regarding the anonymous comment 9: "appears to choke" is not a particularly descriptive failure mode. What goes wrong?
Could you please provide a short description of how to repeat the problem so that we can investigate it. A lot of use don't use eggs or setuptools, so some assistance in helping us repeat the problem will help us to fix it. Thanks.
comment:13 Changed 9 years ago by
Reading this patch, I notice it tries to slip in the evil "don't set
DJANGO_SETTINGS_MODULE if it's already set" change. This cannot be the right thing to do. It means you can easily end up with the
--settings=... value set to one thing and
DJANGO_SETTINGS_MODULE set to another thing, which will lead to inconsistent behaviour in subprocesses for example. The two should mirror each other precisely. Ideally, we shouldn't need the environment variable at all, but since we have it, we must keep a consistent environment throughout the process space.
People keep trying to make this change because they want something over there to use their
DJANGO_SETTINGS_MODULE when its called, but not right now when they pass in
--settings. Those people are setting themselves and everybody else up for difficult-to-diagnose bugs and there's really no logic behind it. Certainly those ideas have their place. But that place is on a desert island. In the middle of the ocean. With no internet connection.
comment:14 Changed 9 years ago by
comment:15 Changed 9 years ago by
comment:16 Changed 9 years ago by
I'm not going to have time to work on this in the near future, so reassigning back to the pool in case anybody wants to work out the egg issue. At some point the solution might be to commit it to force people to see the problem if they've chosen to use eggs, but that will require somebody with time to field the bug reports.
comment:17 Changed 8 years ago by
comment:18 Changed 8 years ago by
comment:19 Changed 8 years ago by
This one is actually on my radar; it's the cause of a few nasty problems with external commands.
comment:20 Changed 8 years ago by
@russellm: I think I'm fairly happy with this change. I'd be prepared to commit it now and if there really are problems with the eggs case, people will then report them because it will bite them (i.e. a scorched earth policy here). You have any real issues with landing this?
comment:21 Changed 8 years ago by
@malcolmt: Scorched earth sounds like the right approach for the eggs problem.
As for the rest of the patch - it turns out that this was unrelated to the external commands problem I was chasing. I agree with your previous comment that the mangling of DJANGO_SETTINGS_MODULE should be left out of this change. Other than that, the patch looks good to me.
This leaves 15 test failures in the admin_scripts suite. I haven't dug into them in depth to be certain, but on the surface it looks like relatively simple expected changes to behaviour (i.e., tests previously asserted that django-admin couldn't run user commands, but now it can). I'll proabably get a chance to look at this tomorrow, but if you beat me to it, I won't hold a grudge :-)
comment:22 Changed 8 years ago by
comment:23 Changed 8 years ago by
Changed 8 years ago by
comment:24 Changed 8 years ago by
Also I think we need to document that users have to unset
DJANGO_SETTINGS_MODULE environment variable in order to use
startproject command and use
startapp in the current directory. English is not my native language, so it would be nice if someone else will do it.
comment:25 Changed 8 years ago by
i_i, please open a new ticket to track this. In general, it's bad form to reopen a ticket closed by a core dev, and doubly-so to attach new patches -- it makes tracking history very hard.
comment:26 Changed 5 years ago by
Milestone 1.0 beta deleted
Thanks, Todd. The patch appears to break the Django system tests; when I run the system tests, I get the following stack trace: | https://code.djangoproject.com/ticket/5943 | CC-MAIN-2017-04 | refinedweb | 1,215 | 71.24 |
NAME | SYNOPSIS | DESCRIPTION | RETURN VALUES | ATTRIBUTES | SEE ALSO
#include <stdio.h> #include <sys/mnttab.h>int getmntent(FILE *fp, struct mnttab *mp);. Note thatntopts member of the mnttab structure mnt for a substring that matches opt. It returns the address of the substring if a match is found; otherwise it returns 0. Substrings are delimited by commas and the end of the mnt_mntopts string.
The putmntent() function is obsolete and no longer has any effect. Entries appear in mnttab as a side effect of a mount(2) call. The function name is still defined for transition purposes.
The resetmnttab() function notifies getextmntent() to reload from the kernel the device information that corresponds to the new snapshot of the mnttab information (see mnttab(4)). Subsequent getextmntent() calls then return correct extmnttab information. This function should be called whenever the mnttab file is either rewound or closed and reopened before any calls are made to getextmntent().
If the next entry is successfully read by getmntent() or a match is found with getmntany(), 0 is returned. If an EOF is encountered on reading, these functions return -1. If an error is encountered, a value greater than 0 is returned. The following error values are defined | http://docs.oracle.com/cd/E19683-01/816-0213/6m6ne3880/index.html | CC-MAIN-2015-32 | refinedweb | 202 | 59.09 |
Django app for creating a knowledge base of curated literature
Project description
Django app for creating a knowledge base of curated literature
Documentation
The full documentation is at.
Quickstart
Install Django Curated Literature Knowledge Base:
pip install django-literature-knowledgebase
Add it to your INSTALLED_APPS (along with DRF and django-filters):
INSTALLED_APPS = ( ... 'rest_framework', 'django_filters', ... 'literature_knowledgebase', 'user_activities', ... )
Add Django Curated Literature Knowledge Base’s URL patterns:
from literature_knowledgebase import urls as literature_knowledgebase_urls urlpatterns = [ ... url(r'^', include(literature_knowledgebase_urls, namespace='literature_knowledgebase')), ... ]
Features
- TODO
Running Tests
Does the code actually work?
source <YOURVIRTUALENV>/bin/activate (myenv) $ pip install tox (myenv) $ tox
Credits
Tools used in rendering this package:
History
0.1.0 (2017-12-29)
- First release on PyPI.
- Initial models and REST API.
0.2.0 (2018-01-05)
- Added REST API filters.
- Added URLs to pubmed article and NCBI utils.
0.2.1 (2018-01-09)
- Fixed issues with migrations
0.2.2 (2018-01-12)
- Fixed route names for SimpleRouter.
0.3.0 (2018-02-09)
- updated requirements to the latest.
0.4.0 (2018-04-03)
- Added support for GraphQL
0.5.0 (2018-04-07)
- Added support for Django 2.0 and Python 3.6
- Dropped support for Django < 1.11 and Python 2.7, 3.3, 3.4
0.5.1 (2018-04-18)
- Updated 3rd party libs
0.5.2 (2018-05-16)
- Updated 3rd party libs
- Updated setup.py to read requirements from requirements.txt
0.6.0 (2018-06-01)
- Dropped support for GraphQL
0.6.1 (2018-08-13)
- Updated 3rd party requirements. Some requirements had changed so it was causing failures
0.6.2 (2018-10-29)
- Updated 3rd party requirements.
0.7.0 (2018-12-05)
- Added attribute to save PDF for an article
- Added REST API to summarize all details from eutils (efetch and esummary) into a single API call
0.7.1 (2018-12-05)
- Added REST API to summarize all details from eutils (efetch and esummary) into a single API call
0.7.2 (2019-01-08)
- Updated 3rd party requirements.
0.7.3 (2019-02-08)
- Updated 3rd party requirements.
- Refactored tests
0.7.4 (2019-04-10)
- Updated 3rd party requirements.
- Updated travis to use xenial distribution. Django 2.1 dropped support for SQLite < 3.8.3
0.7.5 (2019-05-31)
- Updated package to use latest cookiecutter template
0.7.6 (2019-07-26)
- Updated 3rd party requirements.
0.7.7 (2019-08-09)
- Updated 3rd party requirements.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-literature-knowledgebase/ | CC-MAIN-2019-35 | refinedweb | 440 | 53.98 |
Download ===
Download ===
Download Activator Kj.120829.exe
Lieder der . The newer OS which doesn’t have a winlogon.exe file in it and a split for the user interface was.
Aug 10, 2019
SUPER WAPWARE B HAVING INDEPENDENT PTY LTD. (N.0) (0807537) — LICENCED (FINE FRENCH FRIEND) (0807537) i us sta zsek 19 5c m 48r g m 5t zeg us 92 rse neh
You can download the NTV activator, the.Torrent and realtor premium for free from the official site of the movie.Q:
How do I apply a theme to a user inputted python string?
I’ve built a script which asks the user to input some information for an application: first name, last name, an address, and zip code.
Then the script asks the user to choose a color for the front page of their new home.
I’d like to apply the theme to the text that the user inputs.
Is there a way to do this?
A:
You can set the theme value to a text widget, just do something like
from tkinter import *
root = Tk()
data = StringVar()
v = Entry(root, textvariable=data)
v.grid(row=0, column=0)
def set_theme():
color_var = ColorVar(root)
color_var.set(LookUp(«green», «blue»))
color_var.set(LookUp(«red», «black»))
Button(root, text = «Choose Colors», command = set_theme).grid(row=1, column=0, sticky = «e»)
root.mainloop()
Alternatively you can use the textvariable parameter of the Entry widget:
import Tkinter as tk
root = tk.Tk()
data = tk.StringVar()
data.set(«You have been set to the theme: %s» % LookUp(«green», «blue»))
entry = tk.Entry(root, textvariable=data)
entry.grid(row=0, column=0)
root.mainloop()
The lookups return the color names for that particular theme (ie «green» for the theme you have selected).
This proposal requests continued support for a Training Program in Child Psychiatry at Washington University. The Program’s specific goals are to provide postdoctoral fellows a sophisticated foundation in clinical child psychiatry, while also enabling them to explore basic and applied aspects of the neurobiology and psychopharmacology of developmental psychopathology. Clinical fellows gain both theoretical and clinical knowledge through interactions with a well-established group of academic clinicians who are at the forefront of research in their areas of clinical expertise, and through teaching
55cdc1ed1c | http://yotop.ru/2022/06/04/download-activator-kj-120829-exe/ | CC-MAIN-2022-40 | refinedweb | 376 | 58.48 |
This preview shows
pages
1–2. Sign up
to
view the full content.
View Full
Document
This
preview
has intentionally blurred sections.
Unformatted text preview: Algorithms Lecture 18: Minimum Spanning Trees [ Sp10 ] We must all hang together, gentlemen, or else we shall most assuredly hang separately. Benjamin Franklin, at the signing of the Declaration of Independence (July 4, 1776) It is a very sad thing that nowadays there is so little useless information. Oscar Wilde A ship in port is safe, but that is not what ships are for. Rear Admiral Grace Murray Hopper 18 Minimum Spanning Trees 18.1 Introduction Suppose we are given a connected, undirected, weighted graph. This is a graph G = ( V , E ) together with a function w : E R that assigns a weight w ( e ) to each edge e . For this lecture, well assume that the weights are real numbers. Our task is to find the minimum spanning tree of G , that is, the spanning tree T minimizing the function w ( T ) = X e T w ( e ) . To keep things simple, Ill assume that all the edge weights are distinct: w ( e ) 6 = w ( e ) for any pair of edges e and e . Distinct weights guarantee that the minimum spanning tree of the graph is unique. Without this condition, there may be several different minimum spanning trees. For example, if all the edges have weight 1, then every spanning tree is a minimum spanning tree with weight V- 1. If we have an algorithm that assumes the edge weights are unique, we can still use it on graphs where multiple edges have the same weight, as long as we have a consistent method for breaking ties. One way to break ties consistently is to use the following algorithm in place of a simple comparison. S HORTEREDGE takes as input four integers i , j , k , l , and decides which of the two edges ( i , j ) and ( k , l ) has smaller weight. S HORTER E DGE ( i , j , k , l ) if w ( i , j ) < w ( k , l ) return ( i , j ) if w ( i , j ) > w ( k , l ) return ( k , l ) if min ( i , j ) < min ( k , l ) return ( i , j ) if min ( i , j ) > min ( k , l ) return ( k , l ) if max ( i , j ) < max ( k , l ) return ( i , j ) if max(i,j) < max(k,l) return ( k , l ) 18.2 The Only Minimum Spanning Tree Algorithm There are several different methods for computing minimum spanning trees, but really they are all instances of the following generic algorithm. The situation is similar to the previous lecture, where we saw that depth-first search and breadth-first search were both instances of a single generic traversal algorithm. The generic minimum spanning tree algorithm maintains an acyclic subgraph F of the input graph G , which we will call an intermediate spanning forest . F is a subgraph of the minimum spanning tree of G , and every component of F is a minimum spanning tree of its vertices. Initially, F consists of n one-node trees. The generic algorithm merges trees together by adding certain edges between them. When the c Copyright 2011 Jeff Erickson. Released under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License ( )....
View Full Document
This note was uploaded on 10/14/2011 for the course ECON 101 taught by Professor Smith during the Spring '11 term at West Virginia University Institute of Technology.
- Spring '11
- Smith
Click to edit the document details | https://www.coursehero.com/file/6473069/18-mst/ | CC-MAIN-2017-09 | refinedweb | 577 | 68.7 |
.
is it a windowless app?
Victor Nijegorodov
If you mean the windowless like the black box then yes it is windowless. (I didn't want to deal with the black box all the time. ) If you mean windowless as in have a pop up come up then i don't want any pop ups or anything, i just want it to be unnoticed.
I mean: does your application main thread create any window (hidden or minimized) or it is just a console application?
If there is a window that it should receive the system messages like WM_QUERYENDSESSION, WM_ENDSESSION...
its just a console application. if it would help i could post the code for you, its small and kinda crappy but i just started 4 days ago.
You'll need to write either a windowed app so you have a means to handle WM_QUERYENDSESSION etc like VictorN mentioned.
Or you will need to write this as a proper service. You can then handle service start/stop requests.
Note that the WM_QUERYENDSESSION messages are for logoff, not for reboot of the machine, this may or may not be relevant to your needs.
ok heres the code, try and see what you can do to make it log the keys when you turn off the computer. (just like the f8 key) also i dont really know what the hwnd "pie" part does, so feel free to fix that aswell. :
#include <windows.h>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int Char;
string letter;
ofstream log;
log.open("Log.txt", ios::app);
while(!GetAsyncKeyState(VK_F8))
{
for(Char = 65; Char < 90; Char++)
{
if(GetAsyncKeyState(Char) == -32767)
{
letter+=Char;
}
}
if(GetAsyncKeyState(VK_SPACE)==-32767)
{
letter+=" ";
}
if(GetAsyncKeyState(VK_BACK)==-32767)
{
letter+="[BACKSPACE]";
}
{
HWND hWnd;
hWnd = FindWindow (0, "pie");
if (hWnd != 0);
}
}
log << letter;
log.close();
return 0;
}
You can't "log" keys for anything other than your console app. Doing anything outside of the console window will not result in anything in your app.
while you can detect keys outside of your own app via a global hook (not the easiest of things)
that still doesn't cover mouse actions that cause a logoff. You can hook those as wel (not easiest of things). But that still won't help you to detect that a logoff is about to happen with any realistically useful accuracy.
looking at yoru code and what you're lookign at doing, I think you're way over year head trying to make something you're not even at all ready for. I'd suggest working some simpler , more straightforward projects first.
View Tag Cloud
Forum Rules | http://forums.codeguru.com/showthread.php?508375-C-Detect-power-down.&mode=hybrid | CC-MAIN-2014-35 | refinedweb | 435 | 72.56 |
#include <FS_DiskCache.h>
The Accessor class is used to access items in the cache. When an accessor is in write-mode, the thread/process will have unique access to the cache item until the Accessor is destructed. Multiple threads/processes can have read-only access to the item.
Definition at line 56 of file FS_DiskCache.h.
Definition at line 59 of file FS_DiskCache.h.
Definition at line 69 of file FS_DiskCache.h.
Return the number of bytes written.
Definition at line 86 of file FS_DiskCache.h.
Clear the accessor. This will close any file descriptors and release any locks.
Return the full path of the file in the cache.
Definition at line 101 of file FS_DiskCache.h.
Whether the accessor was opened as read-only.
Definition at line 95 of file FS_DiskCache.h.
Whether the accessor is valid.
Definition at line 92 of file FS_DiskCache.h.
Whether the accessor was opened for writing.
Definition at line 98 of file FS_DiskCache.h.
Read the contents of the stream.
Normally, accessors that write data are counted to the cache storage. This can disable this behaviour.
Definition at line 105 of file FS_DiskCache.h.
Write data to the file. This method can be called multiple times.
Convenience methods to write data to the cache.
Definition at line 82 of file FS_DiskCache.h.
Definition at line 115 of file FS_DiskCache.h. | https://www.sidefx.com/docs/hdk/class_f_s___disk_cache_1_1_accessor.html | CC-MAIN-2020-16 | refinedweb | 227 | 80.48 |
So you've learned XML. You mastered your way through DTD, XSLT, SAX and DOM. You unraveled the secrets of namespaces, and you think you're on top of the X-rated acronym soup. Congratulations! Now what?
Judging from the developer feedback I hear, you're not alone asking yourself that crucial question. This article proposes one answer through a practical application. It demonstrates how to automate publishing chores with Java and XML. As such, I think it will prove inspiring.
This article does not include an introduction to XML. I assume you are familiar with XSLT and have some notion of SAX parsing. Even if you need background on those topics, you might still want to read through the article, as it will inspire you to learn more. But make sure you consult the Resources section for some basic XML references.
XML may not seem like a natural technology match with e-mail. Stay with me, and you may be surprised by the utility of this strange combination.
As you probably know, Eudora, Outlook, Netscape, and other modern e-mail clients let you send HTML e-mails. Originally e-mail messages were limited to plain text and they would not support bold, italics or hyperlinks. Modern e-mail clients recognize HTML, and so you can now send either plain text messages or richly decorated documents.
This choice of e-mail formats poses a problem to e-mail magazine (e-zine) publishers. Indeed the choice plays a part in the strategies e-zine publishers develop to confront their two biggest problems: acquiring and retaining subscribers. Unfortunately, subscribers have strong positions for or against HTML e-mails.
To make things worst, some e-mail clients (including the popular AOL 4.0 to 5.0) do not support HTML at all. Unless you are extra careful, subscribers with those older e-mail clients see only garbage.
Traditionally, e-zine publishers have gone to great lengths to ensure their reader's comfort. In the days of plain-text e-mails, savvy publishers would manually format their prose. Some continue this fine tradition with HTML e-mails, painfully preparing two versions of each document: plain text for older e-mail clients and HTML for newer ones. When I heard about that, a lightbulb popped over my head and I thought "XSLT style sheets." (This may be a sure sign that I should get a life.)
In this two-part article, you'll see how XML, XSLT and some Java programming can simplify things. In the process of doing so, you'll use various XML techniques. Let's start by reviewing them all:
- XML itself, of course. The e-zine will be written in XML and, more specifically, in DocBook. DocBook is a popular XML vocabulary for technical documentation.
- XSLT is typically used to convert XML documents to HTML. That would solve half of our problem (preparing the HTML version of the e-zine).
- A special text formatter that enhances XSLT support for text. Indeed, as you might have understood, top-notch text formatting is a priority for e-zines.
- JavaMail, the standard Java API to send e-mail.
Figure 1 illustrates the relationship between these components. From left to right, the ultimate goal is to prepare a so-called multipart e-mail with both text and HTML versions of the e-zine.
Figure 1. How the components of the solution interact
Preparing the e-mail involves going through two style sheets: one creates the text output, the other outputs the HTML version. The text formatter assists the text style sheet. JavaMail picks up both copies and sends them to subscribers.
This first installment of this series concentrates on the text transformation. The second installment will wrap things up with JavaMail.
The starting point is the article in
article.xml in Listing 1.
It is written in DocBook, meaning that the XML tags (
<article>,
<title>,
<para>) are all tags defined by DocBook.
Listing 1. article.xml
Now let's see how to convert DocBook to text. XSLT has some support
for text formatting (in the form of
<xsl:output but,
in my experience, it is inadequate for e-zine publishing. More specifically,
with XSL text output, it's:
- Impossible to break lines at a specific length (a requirement with old e-mail clients)
- Difficult to remove accented characters (another limitation with old e-mail clients)
- Troublesome to remove duplicate spaces in the original document
At first sight it would appear that XSLT cannot help, but a small dose of Java programming can make it work. The trick is to define a special XML vocabulary, which I'll call the text-markup language, to describe text documents.
I created this text-markup language specifically for this article, so
it's as simple as it needs to be. Indeed it has only two tags:
<txt:root> (the
root of the document) and
<txt:block> (a paragraph with a line
break before and after it). Both are defined in the namespace.
Incidentally, remember that a namespace is just an identifier; it looks
just like a URL, but it does not point to anything.
<txt:root> has a
lineWidth attribute for the ... that's
right: the line width.
<txt:block> has a
linesAfter attribute
with the number of line breaks after the block.
Next, you write a Java application to convert text-markup language to
plain text. For example, the document below (Input) will become the following document (Output). Notice that the line breaks occur after 65 characters as specified by the
lineWidth attribute:
Input
Output
To convert from the original XML document to text-markup language, I'll use XSLT (of course). Incidentally, why bother with the text-markup language? If I'm going to write Java code, why not process DocBook directly? In a nutshell, because it's easier this way. For example:
- Instead of parsing all the many tags in DocBook, I need to process only the two tags in the text markup language.
- To change the text output, it suffices to edit the style sheet and, because XSLT is a scripting language, that's easier than hacking around in Java.
- Last but not least, the combination of text-markup language and XSLT works with DocBook and any other XML vocabulary.
If you're familiar with XSL, this text-markup language is similar to using FO to create PDF files.
The style sheet to convert from DocBook to the text-markup language
is
text.xsl in the Listing 2. Notice the
<xsl:output tag: this style sheet converts from
XML (DocBook) to XML (text markup language) -- not HTML.
Listing 2. text.xsl
You can see the text formatter itself,
Xml2Text.java, in Listing 3.
Xml2Text is a SAX
ContentHandler. (If you're not familiar with SAX, see
the sidebar SAX defined.) As SAX handlers
go, this one is easy. In the
startElement() and
characters()
events, it buffers the content of
<txt:block>. In
endElement(),
Xml2Text writes the text and inserts line breaks as appropriate.
Listing 3. Xml2Text.java
Xml2Text lacks the ability to remove unwanted spaces and accented
letters. Instead of cramming these features in
Xml2Text, it makes
more sense to implement them as two SAX filters. The beauty of SAX filters
is that you can freely combine them.
I can think of several other cases when I could use these two filters, for example, to remove unwanted spaces as preprocessing before publishing HTML documents.
WhitespaceFilter.java in Listing 4 is the SAX
filter that removes duplicate spaces. Again, if you are familiar with SAX
handlers, this class is easy. In
startElement() and
characters(),
it buffers the text.
endElement() removes duplicate spaces. Note
that this code is optimized for clarity, not efficiency: it buffers too
much.
The filter also recognizes the standard
xml:space attribute.
You have probably forgotten about
xml:space but it is defined
in the original XML standard. It takes one of two values:
preserve (preserve
duplicate spaces, like HTML
<pre> ) and
default which
means duplicate spaces can be removed.
Listing 4. WhitespaceFilter.java
The second filter,
AsciiFilter.java (see Listing 5), removes
accented characters and other special characters not recognized by old
characters().
Note that
AsciiFilter does not filter attributes and, for the
simplicity of this example, it's limited to the accents used in the French
language. You might want to add more special characters to filter other
languages.
Listing 5. AsciiFilter.java
Console.java in Listing 6 puts all the pieces together.
It applies the style sheet (through the standard Java API designed by Sun)
and runs the result through the text formatter. Mind the fact that this
really is a multistep transformation: from DocBook to the text-markup language
to plain text.
Listing 6. Console.java
This might seem like a lot of work to please a group of subscribers with antiquated e-mail clients. Why bother? Some people would suggest the subscribers should upgrade, but many e-zine publishers are willing to go the extra mile to satisfy their readers. Furthermore, thanks to XML and XSLT, it's not too difficult to automate the repetitive parts of the process, making it more practical to make the effort.
In the second installment, I'll show how to combine the text conversion with JavaMail to completely automate the operation.
Information about download methods
- You can download the source code for this project, including an ANT build file.
- Dr. Ralph Wilson has conducted a survey of e-mail clients. He reports on their preference for HTML e-mails.
- If you're new to XSLT, see What kind of language is XSLT? by Michael Kay.
- JAXP, the Java API for XML, integrates SAX (XML parsing) and TrAX (XSLT transforming).
- JavaMail is the standard Java API for e-mail.
- If you like this article's description of a practical XML solution, you can find eight more quality examples in Applied XML Solutions, by the author of this article.
- For a basic introduction to XML programming in Java, follow the developerWorks tutorial of the same name.
Benoît Marchal is a consultant and writer based in Namur, Belgium. He wrote both XML
by Example and Applied
XML Solutions. He is a columnist for Gamelan.
Ben learned first hand about e-zine publishing when he launched Pineapplesoft Link in 1998. You can subscribe to his e-zine and find details on his latest projects at. | http://www.ibm.com/developerworks/java/library/x-xmlist1/ | crawl-003 | refinedweb | 1,729 | 65.62 |
Go Basics
Users familiar with one or more other Elements languages will find a few areas that might work in surprising ways, when adding Go code to their project.
This topic should cover some of these caveats.
Namespaces
Like all Elements languages, Go has full support for Namespaces, including specifying namespaces for your own code and accessing existing code within the namespaces it lives in, for all the platforms. However, the way Go specifies namespaces behaves slightly different than the other languages.
Oxygene, C# and Java specify the full namespace for all types declared in a file at the top, while Swift files do not specify a namespace at all and have all types be part of the
RootNamespace set in Project Settings.
Similar to Swift, Go derives the namespace for a file from the
RootNamespace, but combines it with the physical folder structure within the project (i.e. relative to the
.elements project file) to form the full namespace. The
package keyword at the top of the file must match the last part of the namespace.
For example, if a project as a
RootNamespace of
mycompany.myproject and one or ore files in a subfolder called
tools, then the
package name specified in those files must also be
tools, and the full namespace of types declared in these files will be
mycompany.myproject.tools.
The "Go" root namespace
Go comes with an extensive Go Base Library (GBL) of commonly used types and functions, ranging anywhere from mathematic algorithms to encryption, network communication and more.
Within
.go source files, these types are available via the same namespaces as in Google's Go implementation, e.g.
builtin,
fmt,
crypto, and so on.
Since Elements projects can mix languages, a common scenario is to have some Go code in project that is predominantly using one of the other languages, and referencing the GBL because the Go code depends on it.
In order to not pollute the base name scope with all the Go namespaces, types from the GBL are nested under a virtual "
Go" namespace, when accessed from Oxygene, C#, Swift and Java.
In other words, where form Go you might see
crypto.md5, the same types will be accessible as
Go.crypto.md5 from the other languages
File Name Suffixes
Different than in other languages, file names have relevance for whether a .go file gets compiled as part of a project or not. Go files can have one or more suffixes appended to the base file name with an underscore.
If that suffix matches a platform (such as "
_windows"), the file will only be compiled if it matches the platform of the project (or target). If it matches an architecture (such as, "
_arm64"), it will only be compiled when building for that particular architecture. Note that this includes platforms and architectures not covered by Elements itself (e.g. "_sparc64").
Projects with a suffix of "
_test" will only be compiled for Go test projects (which are currently not supported by Elements yet).
Files with unknown suffixes ("
_foo") will be compiled as normal.
If in doubt, avoid underscores in names.
Scope of Go Base Library
Our goal is to support the full Go Base Library (GBL) for the following platforms and sub-platforms:
A very limited
go.jar is with a few base types is provided for Java, but the vast majority of GBL code is not compatible with the limitations of the Java runtime, unfortunately.
The Go Base Library will not be available for Toffee V1 Cocoa projects, since we're planning to have Island/Darwin overtake this target as the default back-end, soon. | https://docs.elementscompiler.com/Gold/Basics/ | CC-MAIN-2019-39 | refinedweb | 603 | 68.5 |
2.3 The Math Class
The Java API provides a class named Math, which contains number of static methods that compute various common mathematical functions. A static method can be called using the name of the class containing the method.
The pow() Method
The class Math contains a method pow, which is used to calculate xy in a program. Here is an example of how the pow method is used:
result = Math.pow(2, 3);
Math.pow(2,3) computes 8.0. This statement is equivalent to the following algebraic statement
result = 23
The sqrt() Method
The Math.sqrt method accepts a value as its argument and returns the square root of the value. Here is an example of how the method is used:
result = Math.sqrt(16.0);
In this example the value 16.0 is passed as an argument to the sqrt method. The method then return the square root of 16.0, which is assigned to the result variable.
/** * This program demonstrate * Class Math methods. */ public class MathMethodsDemo { public static void main(String[] args) { // To hold data. double x, y, result; x = 16; y = 2.0; // Get the power. result = Math.pow(x, y); // Display result. System.out.println(result); // Get square root. result = Math.sqrt(x); // Display result. System.out.println(result); } }
Output :
256.0
4.0
You can find others Math Class methods : | http://www.beginwithjava.com/java/inputoutput/class-math.html | CC-MAIN-2018-30 | refinedweb | 228 | 70.7 |
Code::Blocks
User forums => Help => Topic started by: Speculi on August 23, 2007, 06:42:03 pm
Title:
CB can't find Header included in an Header
Post by:
Speculi
on
August 23, 2007, 06:42:03 pm
I tried to compile an Ogre3D Project with CB and I tried to compile the CB Plugins from SVN, both give me the same error.
CB can't find the Header Files which are included in another Header File.
I'm not that experienced with C++ and not sure if it is an CB related problem or if there are mistakes in the Code, so here is an example.
C:\OgreSDK\include is in my search path
in C:\OgreSDK\samples\example.cpp there is OIS.h included:
#include <OIS\OIS.h>
No Problem this far, but in OIS.h there are some Headers included like:
#include "OISmouse.h"
CB can't find those files, but all the OIS Headers are in the same directory.
I thought CB should look for these files in the same directory like the file where it was included?
I got the same problem when I wanted to compile CB from source, CB itself compiled fine, but when I tried to compile the Plugins CB can't find the needed Headers.
I'm running CB under Windows XP and wx2.4.8.0 with MinGW.
SMF 2.0.15
|
SMF © 2017
,
Simple Machines | http://forums.codeblocks.org/index.php?action=printpage;topic=6759.0 | CC-MAIN-2019-51 | refinedweb | 236 | 73.27 |
Prev
Java Manifest Experts Index
Headers
Your browser does not support iframes.
Re: Running java programs from class files
From:
Knute Johnson <nospam@rabbitbrush.frazmtn.com>
Newsgroups:
comp.lang.java.programmer
Date:
Wed, 30 Aug 2006 12:20:39 -0700
Message-ID:
<cxlJg.233$Xl7.10@newsfe11.phx>
Babu Kalakrishnan wrote:
Knute Johnson wrote:
Babu Kalakrishnan wrote:
Knute Johnson wrote:
Oliver Wong wrote:
"Knute Johnson" <nospam@rabbitbrush.frazmtn.com> wrote in message
news:qe%Ig.2$bR.0@newsfe06.phx...
Babu Kalakrishnan wrote:
The commandline for the above example in that case would be :
java -classpath /xyz/abc MyPackage.MyClass
That doesn't work for me although I have seen reference to it before
like that. Could it be that it doesn't work on Windows like that?
It works for me on WinXP SP2:
java -cp "D:\Oliver's Documents\Workspace\Test\bin" D
to run a class called "D" with no package whose classfile is in
"D:\Oliver's Documents\Workspace\Test\bin"
- Oliver
That does for me too. But put it in a package and it won't.
Interesting - Seems to work for me even with classes within a package -
Running TCPServer.class in package test :
java -classpath "C;\Documents and
Settings\Babu\workspace\TestServer\classes" test.TCPServer
Main: Listening for connections on port 2345
Testing on XP Home SP2
BK
package test;
public class Test {
public static void main(String[] args) {
System.out.println("It works!");
}
}
C:\>javac test/Test.java
I'd assume that you now have Test.java and Test.class inside C:\test.
C:\>java test.Test
It works!
OK - here the default classpath assumed by the JVM is "." (which is
"C:\"), so it works
C:\>cd test
C:\test>java -cp "C:\test" test.Test
Exception in thread "main" java.lang.NoClassDefFoundError: test/Test
Your commandline here should be :
java -cp "C:\" test.Test
because the classpath is to be set to the root of the package hierarchy
- which is C:\ in your case.
With the commandline you used, the class file is expected to be
C:\test\test\Test.class
BK
Thank you so much guys, this has confused the s**t out of me for years.
I think the most confusing part is the root business.
So now that you solved that one, show me how to use a jar library on the
command line when I run a java program. I can make it compile but I
can't make it run. I can get it to work if I put the jar file in the
Class-Path: line in the manifest and put the jar file in the same
directory as the program jar file but not from the command line.
Test is my slightly modified class that calls a static method in
lib.Lib. The Lib class has been compiled and put into a jar file,
lib.jar in the /lib directory. I then compile Test.java from the /test
directory and run the .class file with no problems. You will see that
the lib.Lib class can't be found once I jar it.
package test;
public class Test {
public static void main(String[] args) {
System.out.println("It works!");
lib.Lib.lib();
}
}
package lib;
public class Lib {
public static void lib() {
System.out.println("lib");
}
}
C:\lib>dir
Volume in drive C has no label.
Volume Serial Number is 7C27-9663
Directory of C:\lib
08/30/2006 12:15 PM <DIR> .
08/30/2006 12:15 PM <DIR> ..
08/30/2006 11:06 AM 728 Lib.jar
08/30/2006 10:46 AM 116 Lib.java
2 File(s) 844 bytes
2 Dir(s) 62,081,531,904 bytes free
C:\lib>
C:\test>dir
Volume in drive C has no label.
Volume Serial Number is 7C27-9663
Directory of C:\test
08/30/2006 12:12 PM <DIR> .
08/30/2006 12:12 PM <DIR> ..
08/30/2006 11:51 AM 162 Test.java
1 File(s) 162 bytes
2 Dir(s) 62,081,544,192 bytes free
C:\test>javac -cp /lib/Lib.jar Test.java
C:\test>java -cp /lib/Lib.jar;/ test.Test
It works!
lib
C:\test>cd \
C:\>jar cvfe test/Test.jar test.Test test/*.class
added manifest
adding: test/Test.class(in = 452) (out= 310)(deflated 31%)
C:\>java -cp /lib/Lib.jar -jar test/Test.jar
It works!
Exception in thread "main" java.lang.NoClassDefFoundError: lib/Lib
at test.Test.main(Test.java:6)
C:\>
--
Knute Johnson). | https://preciseinfo.org/Convert/Articles_Java/Manifest_Experts/Java-Manifest-Experts-060830222039.html | CC-MAIN-2022-33 | refinedweb | 752 | 69.89 |
INotifyPropertyChanged
Undo/Redo
Code Contracts
Logging
Threading Models
Aspect-Oriented Programming
Architecture Validation
Visual Studio Tooling
Broad Platform Support
Download demo project source code
Welcome to week 2 of PostSharp Principles. As we move forward we’ll continue to explore the features of PostSharp. We still have a lot to cover and just like last week, we’re going to explore two more aspects provided by PostSharp and we’ll look at what is going on under the hood as we go.
Before we get any deeper into PostSharp, it’s important to understand how PostSharp implements your aspects especially when multiple aspects are applied to a single target. Today we’ll have a look at how PostSharp implements OnMethodBoundaryAspect when applied to a method.
If you have not done so, you will need to download demo project source code and you will also need to download and install a copy of ILSpy. You are welcome to use Reflector as the two tools are very similar.
Continuing with the demo project from last week, let’s look at the GetByName method in the InMemoryDataStore.cs file.
public IQueryable GetByName(string value)
{
var res = _contactStore.Where(c => c.FirstName.Contains(value) || c.LastName.Contains(value));
if (res.Count() < 1)
{
ThrowNoResultsException();
}
Thread.Sleep(3000);
return res.AsQueryable();
}
Since this is a pretty basic method it will be easy to see how PostSharp applies our aspects. Build the project with no aspects applied and then open ILSpy. Once ILSpy is open, browse to the output folder for the demo project and select PostSharpDemo1.exe. Navigate down the namespace tree until you reach the GetByName method in the InMemoryDataStore class.
It looks exactly the same as our original code. Let’s apply an aspect and see what changes.
Just for demonstration purposes, let’s build a new aspect based on OnMethodBoundaryAspect. Add a new file called DemoAspect.cs and add the following code
[Serializable]
public class DemoAspect : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine("OnEntry");
}
public override void OnExit(MethodExecutionArgs args)
{
Console.WriteLine("OnExit");
}
public override void OnSuccess(MethodExecutionArgs args)
{
Console.WriteLine("OnSuccess");
}
public override void OnException(MethodExecutionArgs args)
{
Console.WriteLine("OnException");
}
}
Apply the aspect to the GetByName method and then rebuild the project. Back in ILSpy, click refresh (you might have to navigate back to the GetByName method). What you see now is much different than before.
There is a try/catch/finally added to the method and references to InMemoryDataStore.<>z__Aspects.a0 throughout. Let’s start at the top.
So what is this? A simple explanation is that this is a helper class that PostSharp creates to hold references to your aspect(s) and an instance of MethodBase for each method in which an aspect is applied. a0 is a reference to an instance of our DemoAspect. Feel free to navigate around using ILSpy.
At the start of our method a call to InMemoryDataStore.<>z__Aspects.a0.OnEntry(null) is made. This is our OnEntry point, before the rest of our method body. Next is a new declaration of our return type called, ‘result’. Our original code didn’t contain a result variable. PostSharp added it because you cannot do a return from a try/catch block in MSIL. This is the same behavior as the C# compiler.
Inside of the try block is our original method body with only a minor change of setting the result variable with our query results. At the end of the try block is a call to InMemoryDataStore.<>z__Aspects.a0.OnSuccess(null) because at this point, all of our code has executed without throwing an error which means it was successful.
The catch block makes a call to InMemoryDataStore.<>z__Aspects.a0.OnException(null) for what should be an obvious reason. An exception has occurred and we wanted to handle that event in our aspect. After our call, the exception is rethrown.
The finally block makes a call to InMemoryDataStore.<>z__Aspects.a0.OnExit(null) because OnExit must always be called even if the method exited with an exception.
At last, the results are returned to the caller.
Let’s make some changes to our aspect. Update the code to the following
[Serializable]
public class DemoAspect : OnMethodBoundaryAspect
{
public override void OnException(MethodExecutionArgs args)
{
Console.WriteLine("OnException");
args.FlowBehavior = FlowBehavior.Continue;
}
}
Now we’re only implementing OnException and we’ve changed it to set the FlowBehavior. When an exception occurs, we don’t want to rethrow, just continue on. Rebuild the project and refresh ILSpy.
We have a try/catch now instead of a try/catch/finally, but now the catch method is much larger. So what’s going on? Starting our catch block is an instantiation of MethodExecutionArgs and then a call to InMemoryDataStore.<>z__Aspects.a0.OnException(methodExecutionArgs). The reason why there is now a declaration for MethodExecutionArgs is because we need to have access to the properties whereas before, we did not.
Now we come to a switch construct which checks the FlowBehavior property of our MethodExecutionArgs instance. FlowBehavior.Default and FlowBehavior .RethrowException will rethrow while FlowBehavior.Continue (which is what we wanted to do) will return result as it is while FlowBehavior.Return will set the value of result to the value of MethodExecutionArgs.ReturnValue. At the bottom is a catch all jump to the IL_A1 label which will rethrow. This is incase FlowBehavior was set to an unrecognized value.
Play around with different implementations and logic to see how PostSharp changes the resulting code.
As you can see, PostSharp analyzes the code of the aspect and generates only the code that supports the feature actually used by the aspect. This feature is called the aspect optimizer.
Keep in mind that the Starter edition (formerly known as the Community edition) does not include the aspect optimizer, so it may produce much more code for the same aspect.
It is important to know what is happening to your code when you apply aspects. Today we saw an example of OnMethodBoundaryAspect and how the method body is modified to allow the aspect to work. As we continue the series, we’ll look under the hood to see what is going on when dealing with other aspect types and when applying multiple aspects to a single target.
PostSharp Principles: Day 6 - Your Code After PostSharp
You've been kicked (a good thing) - Trackback from DotNetKicks.com | http://www.postsharp.net/blog/post/Day-6-Your-code-after-PostSharp | CC-MAIN-2015-22 | refinedweb | 1,058 | 58.18 |
Hello guys,
I am having so much fun using Ionic2.
i wanted to know how to do a gallery like layout using the framework.
Hello guys,
I am having so much fun using Ionic2.
i wanted to know how to do a gallery like layout using the framework.
Hi did you ever get this resolved
Okay, so I don’t know what you’re exactly looking for, but I can provide an example based on a simple grid. I assume some knowledge of the framework and angular2, otherwise it would take me a little bit too much time to write this example post.
We’re going to create two views. One to display a grid of images, another one to serve as a view with some details about the image.
Let’s call our first view gallery. Create your GalleryPage with the following code:
<ion-header> <ion-navbar <button ion-button menuToggle> <ion-icon</ion-icon> </button> <ion-title>Gallery</ion-title> </ion-navbar> </ion-header> <ion-content> <div class="image__grid"> <div class="image__square" * <img [src]="image.trusted_source" /> </div> </div> </ion-content>
I make no assumptions where the images are coming from. You could already have them inside your app, or just fetched them through an http call or something like that.
This is some pretty basic templating. As you can see I’ve created a custom grid, since it levers some fine grained control over what it’s going to look like. You could always use the ion-grid as well, since this also allows you to tweak it in any way you want.
Inside the grid we loop over an array of objects (which are actually images with some additional information in this case). I’ve also created a click handler for openPhoto and the index of the image is getting passed into that function whenever it get’s called. To create the gallery look I assumed four images next to each other (could be three, five or whatever you want off course). Your gallery.scss could look like this:
page-gallery { .image__grid { margin-top: 5px; overflow: hidden; .image__square:nth-child(4n+4){ padding-right: 5px; } .image__square { height: 25vw; width: 25vw; float: left; padding: 0px 0px 5px 5px; img { height: 100%; width: 100%; object-fit: cover; } } } }
Now we have an awesome grid view which looks something like this:
Now, remember I said we would create a second view? This one is going to be a modal. Inside this modal we’re going to display a single picture, with optional description, date taken and the possibility to slide back and forth to previous and upcoming pictures.
This second view is going to be called photoDetailPage and I’m going to use it as a Modal.
Your HTML of this page could be something like this:
<ion-header no-border> <ion-navbar <ion-buttons right> <button ion-button icon-only (click)="close()"> <ion-icon</ion-icon> </button> </ion-buttons> </ion-navbar> </ion-header> <ion-content <ion-slides <ion-slide * <img [src]="image.trusted_source" class="slider__image"/> <p class="slider__imagecaption">{{ image.caption }}</p> </ion-slide> </ion-slides> </ion-content>
Also pretty straightforward right? It actually uses ion-slides. The general idea is that if we tap an image on view one, we open it up as a bigger image in photoDetailPage with a description. Also we can swipe left or right, hence the ion-slides.
Let’s add some scss styles inside your photoGalleryPage.scss to give it a nice look:
page-photo-detail { .content { background-color: color($colors, dark); } .slider__image { width: 100%; } .slider__imagecaption { color: #FFF; font-weight: bold; font-size: 0.8em; } .swiper-pagination-bullet { background: #969696; } .swiper-pagination-bullet-active { background: #FFF; } }
It should become something that looks like this:
Now we have created two different views. Let’s wire them up so they work together. Inside gallery.ts you should create a handler for opening up the photo’s in the second created view. We have to import the modalController for that.
import { ModalController } from 'ionic-angular';
Now add it to your constructor:
constructor(public modalCtrl: ModalController) {}
And create a function which is hooked up to our gallery.html template:
openPhoto(index){ let modal = this.modalCtrl.create(PhotoDetailPage, { photo_index: index }); modal.present(); }
This opens up the modal with the PhotoGalleryPage. We pass the index of the image so we now which photo to open up in the detail view. Inside the detail view we’re going to extract this information from the navparams. Create a variable inside your detailPage to which we connect the index we’re going to pass to the detailview.
Inside PhotoGalleryDetail.ts we do this in the constructor:
this.open_at_index = this.navParams.get('photo_index'); which actually get’s the the passed index from the navparams and set it to the variable we’ve created in the PhotoGalleryDetail.ts. Since we bound our initialSide inside our template to open_at_index, the slider knows on which page to open up the slider.
Very cool! But where are those images coming from in our detail view? The best way would be to share them through a service, which both the gallery and photodetail can access. If you don’t have to many images, you could always pass them through the navparams (though I don’t encourage that).
If you decide to use a service, import the service on both pages (and declare it inside the constructor). Create a variable inside your service called gallery_images and whenever you wan’t you can access that variable from wherever you import your service. Good luck! | https://forum.ionicframework.com/t/gallery-in-ionic2/55165 | CC-MAIN-2018-51 | refinedweb | 923 | 65.01 |
ASF Bugzilla – Bug 47761
xmlns:xml namespace improperly emitted during excl c14n
Last modified: 2009-10-01 14:11:30 UTC
Created attachment 24187 [details]
Affected document, unsigned and signed, and a key pair used.
It appears that the c14n algorithm is outputting xmlns:xml in certain
conditions even when set to the usual/presumed value, which is improper.
A kit to help reproduce is attached.
From exchanging email with Sean, I believe the trigger for this is probably the
poor choice (but not outright bug) of including the xml prefix in the inclusive
prefix parameter. If so, only exclusive would be broken, and only with this
trigger.
We agree that identifying the prefix there is a bad idea, but it's not illegal
and it doesn't change the algorithm, so it should get fixed here also.
Fixed in main trunk. | https://bz.apache.org/bugzilla/show_bug.cgi?id=47761 | CC-MAIN-2016-36 | refinedweb | 142 | 60.65 |
Are you having problems with redirect loops in your MVC app? Maybe you are using ADFS or another identity server/security token service, if so read on.
In ASP.NET, whatever the authentication mechanism being used (FormsAuth, CookieAuthentication Middleware, ADFS or any other identity provider) the 401 http status code is always the starting point of the authentication process.
When you annotate a controller action with the AuthorizeAttribute what happens behind the covers is a check to see if a user is authenticated, and when the user is not, the http response status code is set to 401 Unauthorized (if you are unsure about what the AuthorizeAttribute is doing check this)
The user never actually sees that response though. The authentication mechanism (they all do this) will look for a response with that status code, before it is sent to the client, and change it to a 302 Redirect to a login page.
The redirect loop problem happens when you have an authenticated user without the required privileges. For example, if you are using roles and you annotate a controller action with the authorize attribute and specify the role “Admin”.
[Authorize(Roles="Admin")] public ActionResult Users() { ... }
If you go the url handled by that action (e.g.) the Authorize attribute will check if the current user is authenticated and has the role “Admin”.
There are three possible scenarios in this situation
- The user is not authenticated
- The user is authenticated but does not have the Admin role
- The user is authenticated and has the Admin role
When the user is not authenticated (1) the AuthorizeAttribute will change the response to 401.
When the user is authenticated but does not have the Admin role (2) the authorize attribute will also change the response to 401. It is only when the user is authenticated and has the Admin role (3) that the authorize attribute won’t change the response.
If you are using FormsAuthentication or the OWIN Cookie Authentication Middleware and the user is already logged in (scenarios 1 and 2), he will be redirected to the login page again, which is kind of weird if you thing about it. “I’ve already logged in, and now I’m back do the log in page just because I clicked some link, and no one told me why this just happened.”
This problem becomes a redirect loop when you are using an identity provider (aka identity server, security token service, etc), for example ADFS or Identity Server.
The way it becomes a redirect loop has to do with the single sign-on feature that identity servers enable.
When you use an identity server, you are delegating the responsibility of authenticating the user to the identity server. So, instead of the 401 being transformed into a redirect to your login page, it will be transformed to a redirect to the identity server. After the user logs in the identity server, s/he is redirected back to your web application.
The user information is sent in the redirect response’s query string from the identity server to your web app as an encrypted token (e.g. /yourwebapp?accessToken=…). As a developer you don’t have to manually deal with this, for example if you use ADFS this is all done for you by a pair of http modules.
There’s a step in the middle of all this. A cookie is issued to the users by the identity server so that the user does not have to provide his credentials again (until the cookie expires).
This enables a user of two different web applications, that share the same identity server, to only enter his credentials once. For example, when you login to Outlook.com and then go to Onedrive.com you don’t have to enter your email and password again.
In this example, when the user goes to Outlook.com for the first time he’s redirected to Microsoft’s identity server (login.live.com). The user enters his email and password and is redirected back to Outlook.com. When the user now goes to Onedrive.com, he’ll also be redirected to login.live.com, but he’ll be immediately redirected to Onedrive.com (with the access token sent in the redirect response) because a cookie was stored for login.live.com the first time he logged in.
Do you see where the redirect loop happens yet? It happens because the default behaviour when using the Authorize attribute in ASP.NET is to issue a 401 when the user is not authorized (even if the user is authenticated). When the user is authenticated and is redirected to the identity provider, the identity provider redirects the user back to the url it came from, which will then cause a redirect of the user back to the identity provider…
The best way to solve this is to use the extensibility points in the AuthorizeAttribute to redefine its behaviour.
Custom AuthorizeAttribute
AuthorizeAttribute provides a protected virtual method named
HandleUnauthorizedRequest that you can override. In it you can test if the user is authenticated and if so (this will definitely be the case of a user being authenticated with insufficient permissions), use a different response code.
You could return instead 403 Forbidden. Although the spec is not very clear about when to use this status code, it feels like a good fit.
using System.Net; using System.Web.Mvc; namespace YouAppNamespace { public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden); } else { base.HandleUnauthorizedRequest(filterContext); } } } }
This might not be what you want though, you might just redirect the user to a page that explains that he does not have sufficient privileges to perform the action that he just tried to perform. If this is the case, just use the
RedirectToRouteResult (e.g.
new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { action = "NotAuthorized", controller = "Error" }));).
There you go. If this was helpful don’t forget to subscribe! | https://www.blinkingcaret.com/2016/01/20/authorization-redirect-loops-asp-net-mvc/ | CC-MAIN-2019-09 | refinedweb | 1,001 | 53.61 |
Tải bản đầy đủ
Công Nghệ Thông Tin
Quản trị mạng
560 supercharged javascript graphics
Supercharged JavaScript Graphics
Supercharged JavaScript Graphics
Raffaele Cecco
Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo
Supercharged JavaScript Graphics
by Raffaele Cecco: Simon St. Laurent
Production Editor: Holly Bauer
Copyeditor: Rachel Monaghan
Proofreader: Genevieve d'Entremont
Indexer: Ellen Troutman Zaig
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
July 2011:
First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. The image of a maned sheep-39363-2
[LSI]
1309979968
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. Code Reuse and Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Keeping It Fast
What and When to Optimize
Homespun Code Profiling
Optimizing JavaScript
Lookup Tables
Bitwise Operators, Integers, and Binary Numbers
Optimizing jQuery and DOM Interaction
Optimizing CSS Style Changes
Optimizing DOM Insertion
Other Resources
4
5
7
8
8
12
19
20
23
23
2. DHTML Essentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Creating DHTML Sprites
Image Animation
Encapsulation and Drawing Abstraction (aka Hiding Stuff)
Minimizing DOM Insertion and Deletion
The Sprite Code
A Simple Sprite Application
A More Dynamic Sprite Application
Converting into a jQuery Plug-in
Timers, Speed, and Frame Rate
Using setInterval and setTimeout
Timer Accuracy
Achieving Consistent Speed
Internet Explorer 6 Background Image Caching
25
26
28
28
28
30
32
35
38
38
40
41
45
3. Scrolling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
CSS-Only Scrolling Effects
47
v
Scrolling with JavaScript
Background Image Scrolling
Tile-Based Image Scrolling
51
51
53
4. Advanced UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
HTML5 Forms
Using JavaScript UI Libraries
Using jQuery UI for Enhanced Web Interfaces
Heavy Duty UI with Ext JS
Creating UI Elements from Scratch
Creating a 3D Carousel
69
71
71
75
78
79
5. Introduction to JavaScript Games . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Game Objects Overview
The Game Code
Game-Wide Variables
Reading Keys
Moving Everything
A Simple Animator
Collision Detection
Aliens
The Player
Shields
Mystery Saucer
The Game
Putting It All Together
92
94
94
95
97
98
99
104
110
113
114
115
119
6. HTML5 Canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Canvas Support
Bitmaps, Vectors, or Both?
Canvas Limitations
Canvas Versus SVG
Canvas Versus Adobe Flash
Canvas Exporters
Canvas Drawing Basics
The Canvas Element
The Drawing Context
Drawing Rectangles
Drawing Paths with Lines and Curves
Drawing Bitmap Images
Colors, Strokes, and Fills
Animating with Canvas
Canvas and Recursive Drawing
vi | Table of Contents
124
124
125
125
126
127
129
129
129
130
130
138
140
144
147
Canvas Tree Page Layout
Replacing DHTML Sprites with Canvas Sprites
The New CanvasSprite Object
Other Code Changes
A Graphical Chat Application with Canvas and WebSockets
The WebSockets Advantage
WebSockets Support and Security
The Chat Application
149
149
150
151
151
152
153
154
7. Vectors for Games and Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Operations on Vectors
Addition and Subtraction
Scaling
Normalization
Rotation
Dot Product
Creating a JavaScript Vector Object
A Cannon Simulation Using Vectors
Simulation-Wide Variables
The Cannonball
The Cannon
The Background
The Main Loop
Page Layout
Rocket Simulation
The Game Object
The Obstacle Object
The Rocket Object
Background
Collision Detection and Response
Page Code
Possible Improvements and Modifications
170
170
171
171
171
172
173
174
175
176
176
178
179
179
180
181
182
183
186
186
189
190
8. Google Visualizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Limitations
Chart Glossary
Image Charts
Data Formats and Chart Resolution
Using Dynamic Data
Summary
Interactive Charts
Interactive Charts Events
194
196
197
199
203
207
207
211
Table of Contents | vii
9. Reaching the Small Screen with jQuery Mobile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
jQuery Mobile
TilePic: A Mobile-Friendly Web Application
TilePic Game Description
TilePic Game Code
PhoneGap
216
218
218
220
230
10. Creating Android Apps with PhoneGap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Installing PhoneGap
Installing the Java JDK
Installing the Android SDK
Installing Eclipse
Installing Android Development Tools
Installing PhoneGap
Creating a PhoneGap Project in Eclipse
Altering the App.java File
Altering the AndroidManifest.xml File
Creating and Testing a Simple Web Application
Testing the TilePic Application
232
232
233
234
235
236
236
238
239
240
241
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
viii | Table of Contents
Preface
Having been a video game developer for many years and being used to working with
high-performance programming languages and hardware, I initially had modest expectations of graphics programming with JavaScript. What I actually found was an
excellent and efficient programming language that is continually being leveraged with
better browsers, performance enhancements, and exciting new facilities. Combined
with features such as Canvas, JavaScript offers web developers a truly viable alternative
to plug-ins such as Adobe Flash, and features such as WebGL ensure a very bright
future for graphics programming using JavaScript and a browser.
This book is for those who have a good working knowledge of JavaScript and would
like to experiment with graphics programming that goes beyond simple hover effects
or relying purely on the animation facilities of libraries such as jQuery. Within these
pages, I cover various graphics-related subjects, including:
• Reusing and optimizing code, including inheritance techniques and performance
tips
• Taking advantage of the surprising graphics power of regular DOM manipulation
(DHTML)
• Using the Canvas element for additional graphics power
• Creating video games
• Using math for creative graphics and animation
• Presenting your data in creative ways with the Google Visualizations API and Google Chart Tools
• Using jQuery effectively and developing graphically oriented jQuery plug-ins
• Creating graphically rich web applications suitable for mobile devices using jQuery
Mobile
• Using PhoneGap to create native Android applications from your web applications
This fast-paced book will give you a broad kick-start into various graphics techniques,
hopefully whetting your appetite for further exploration of the subjects covered.
Experiment and have fun!
ix
Audience and Assumptions
Readers of this book should have a good working knowledge of creating websites and
web applications—and in particular, the use of JavaScript.
I like jQuery because it speeds up development, and many of the code samples include
this library by default. In general, any external libraries and associated files are included
from a reliable content delivery network such as Google’s, thus avoiding the need for
you to copy files to your own web space.
Math has been kept to a minimum, although some of the examples use basic vectors
and trigonometry.
Organization
The book is fast paced, with the first graphics programming examples appearing in
Chapter 1.
In the subsequent chapters, I cover a variety of graphics-oriented topics, focusing primarily on subjects that can add impressive visual impact and interactivity to your web
applications.
No book about interactive graphics would be complete without a discussion of video
games. We’ll explore this subject in depth by developing a full video game application,
as well as examining features that are useful for games projects, such as sprites and
scrolling.
The topics covered in each chapter can be summarized as follows:
Chapter 1, Code Reuse and Optimization
Covers JavaScript object-oriented programming techniques as well as code optimizations (including jQuery optimizations) that are useful where performance
is important in graphics-based applications. We’ll also discuss the little-used JavaScript binary operators and how you can use them for optimization.
Chapter 2
Shows how regular DOM manipulation (DHTML) can be used for fast-moving
graphics. We’ll develop a sprite system (useful for games and other effects) and see
how it works within the context of a jQuery plug-in.
Chapter 3, Scrolling
Covers basic CSS scrolling techniques, including parallax effects. We’ll then move
on to JavaScript-controlled scrolling and finally to a fast, tile-based parallax scrolling system. I’ll introduce you to the powerful Tiled map editor, showing you how
to create tile-based maps.
x | Preface
Chapter 4, Advanced UI
Includes coverage of the user interface libraries jQuery UI and Ext JS. We’ll explore
the differing approaches of the two libraries and their respective suitabilities for
various types of applications. In addition to using existing UI libraries, we’ll build
a 3D carousel from scratch.
Chapter 5, Introduction to JavaScript Games
Demonstrates how to build fun and playable games without resorting to external
plug-ins such as Flash. Subjects covered include collision detection and object
handling. We’ll also develop a full retro-style arcade game to illustrate in action
the techniques we’ve discussed.
Chapter 6, HTML5 Canvas
Examines the Canvas element in depth, with numerous examples—including how
to develop a graphical chat application using Canvas and WebSockets. Canvas
topics include an introduction to basic drawing, strokes, fills, gradients, recursive
drawing, bitmaps, and animation.
Chapter 7, Vectors for Games and Simulations
Covers the myriad uses for 2D vectors in graphical applications and games, proving
that a little bit of math can go a long way. Code examples include cannon and
rocket simulations with realistic movement.
Chapter 8, Google Visualizations
Explores Google Chart Tools, an expansive resource of data visualization tools that
can put an exciting spin on most kinds of data. From bar charts to Google-O-Meter
gauges, this chapter covers the implementation of both static and interactive charts
and other graphical visualizations in your applications. It includes the crucial topic
of formatting your data in the correct way for Chart Tools to use.
Chapter 9, Reaching the Small Screen with jQuery Mobile
Describes jQuery Mobile, a framework built on top of jQuery to provide a unified
user interface to mobile-targeted web applications. jQuery Mobile turns regular
HTML pages into an interactive and animated mobile experience. This chapter
covers the development of a graphical sliding puzzle game specifically geared to
the jQuery UI and mobile devices.
Chapter 10, Creating Android Apps with PhoneGap
Want to create a native mobile application using your usual web development
skills? PhoneGap comes to the rescue. This chapter explains how to install and
configure PhoneGap to create native Android applications. After we walk through
installation and configuration, we’ll convert the sliding puzzle game we developed
in Chapter 9 into a native app ready for deployment to mobile devices.
Preface | xi
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Indicates computer code in a broad sense, including commands, arrays, elements,
statements, options, switches, variables, attributes, keys, functions, types, classes,
namespaces, methods, modules, properties, parameters, values, objects, events,
event handlers, XML tags, HTML tags, macros, the contents of files, and the output
from commands..
Websites and pages are mentioned in this book to help you locate online information
that might be useful. Normally I specify both the address (URL) and the name (title,
heading) of a page. Some addresses are relatively complicated, so you can probably
locate the pages more easily by using your favorite search engine to find a page by its
name, typically by entering it inside quotation marks. This method may also help if
you can’t find the page by its address; it may have simply moved elsewhere, so the name
could still work.
Using Code Examples
This book contains many code snippets and examples, along with several complete
and substantial applications. Some of these will be laborious to enter manually, so I
would recommend copying the code from the book’s code repository. Larger portions
of code may be interspersed with regular copy text. This helps provide a fluid narrative
through the code, rather than requiring you to constantly cross-reference code to text
in different locations.
xii | Preface
Where an example HTML page is featured, most of the examples use the HTML5
doctype:
For convenience, any CSS styles used in the examples are embedded within the HTML
of the page. This is not necessarily the approach that you should take with production
web applications, as external style sheets are recommended. However, within the context of a book, it makes sense to keep things together where possible. You can find the
code examples here:
Target Browsers
Most of the example code in this book will work on reasonably up-to-date browsers,
such as:
•
•
•
•
•
Firefox 3.6x+
Safari 4.0x+
Opera 10.x+
Chrome 5.x+
Internet Explorer 8+
In fact, some of the examples work even in IE6 and IE7, although I don’t recommend
using these browsers.
The examples were fully tested on Windows machines using XP, Vista, and Windows
7, and partially tested on iOS. In theory, the examples should also work on Linux
versions of the supported browsers.
Use of the Canvas tag is limited to browsers that support it, so for Internet Explorer,
this means version 9 only (for native support without any additional plug-ins or
libraries).
A handful of the examples require a specialized environment to work, such as a mobile
development environment (PhoneGap), server language (PHP), or a specific browser.
Where this is the case, I cover setting up and configuring the environment.
Safari®
Preface | xiii
It takes a lot more than an author to get a book to print, so I’d like to thank the following
people:
• Simon St.Laurent, who was nothing but enthusiastic, encouraging, and helpful
throughout the development of this book.
• All those who contributed time and expertise to review the book—especially
Shelley Powers, who provided lots of insightful comments and suggestions.
xiv | Preface
• My copyeditor, Rachel Monaghan, and others in the production staff who
smoothed out the last push to this book’s completion.
• The generous community of developers who freely share their work, hints, and tips
to help move the Web forward.
• My wife and daughter, Rebecca and Sofia, who were worried that my laptop had
become a permanent appendage.
Preface | xv
CHAPTER 1
Code Reuse and Optimization
JavaScript has an undeservedly dubious reputation. Many people have written about
its limitations as an object-oriented programming (OOP) language, even questioning
whether JavaScript is an OOP language at all (it is). Despite JavaScript’s apparent syntactic resemblance to class-based OOP languages like C++ and Java, there is no
Class statement (or equivalent) in JavaScript, nor any obvious way to implement popular OOP methodologies such as inheritance (code reuse) and encapsulation. JavaScript is also very loosely typed, with no compiler, and hence offers very few errors or
warnings when things are likely to go wrong. The language is too forgiving in almost
all instances, a trait that gives unsuspecting programmers a huge amount of freedom
on one hand, and a mile of rope with which to hang themselves on the other.
Programmers coming from more classic and strictly defined languages can be frustrated
by JavaScript’s blissful ignorance of virtually every programming faux pas imaginable:
global functions and variables are the default behavior, and missing semicolons are
perfectly acceptable (remember the rope mentioned in the previous paragraph?). Of
course, any frustration is probably due to a misunderstanding of what JavaScript is and
how it works. Writing JavaScript applications is much easier if programmers first accept
a couple of foundational truths:
• JavaScript is not a class-based language.
• Class-based OOP is not a prerequisite for writing good code.
Some programmers have attempted to mimic the class-based nature of languages like
C++ in JavaScript, but this is analogous to pushing a square peg into a round hole: it
can be done (sort of), but the end result can feel contrived.
No programming language is perfect, and one could argue that the perceived superiority
of certain programming languages (or indeed, the perceived superiority of OOP itself)
is a good example of the emperor’s new clothes.*In my experience, software written in
C++, Java, or PHP generates no fewer bugs or problems than projects created with
*
1
JavaScript. In fact (cautiously sticking my neck out), I might suggest that due to JavaScript’s flexible and expressive nature, you can develop projects in it more quickly than
in other languages.
Luckily, most of JavaScript’s shortcomings can be mitigated, not by forcibly contorting
it into the ungainly imitation of another language, but by taking advantage of its inherent flexibility while avoiding the troublesome bits. The class-based nature of other
languages can be prone to unwieldy class hierarchies and verbose clumsiness. JavaScript offers other inheritance patterns that are equally useful, but lighter-weight.
If there are many ways to skin a cat, there are probably even more ways to perform
inheritance in JavaScript, given its flexible nature. The following code uses prototypal
inheritance to create a Pet object and then a Cat object that inherits from it. This kind
of inheritance pattern is often found in JavaScript tutorials and might be regarded as a
“classic” JavaScript technique:
// Define a Pet object. Pass it a name and number of legs.
var Pet = function (name, legs) {
this.name = name; // Save the name and legs values.
this.legs = legs;
};
// Create a method that shows the Pet's name and number of legs.
Pet.prototype.getDetails = function () {
return this.name + ' has ' + this.legs + ' legs';
};
// Define a Cat object, inheriting from Pet.
var Cat = function (name) {
Pet.call(this, name, 4); // Call the parent object's constructor.
};
// This line performs the inheritance from Pet.
Cat.prototype = new Pet();
// Augment Cat with an action method.
Cat.prototype.action = function () {
return 'Catch a bird';
};
// Create an instance of Cat in petCat.
var petCat = new Cat('Felix');
var details = petCat.getDetails();
var action = petCat.action();
petCat.name = 'Sylvester';
petCat.legs = 7;
details = petCat.getDetails();
//
//
//
//
//
'Felix has 4 legs'.
'Catch a bird'.
Change petCat's name.
Change petCat's number of legs!!!
'Sylvester has 7 legs'.
The preceding code works, but it’s not particularly elegant. The use of the new statement
makes sense if you’re accustomed to other OOP languages like C++ or Java, but the
prototype keyword makes things more verbose, and there is no privacy; notice how
2 | Chapter 1: Code Reuse and Optimization
petCat has its legs property changed to a bizarre value of 7. This method of inheritance
offers no protection from outside interference, a shortcoming that may be significant
in more complex projects with several programmers.
Another option is not to use prototype or new at all and instead take advantage
of JavaScript’s ability to absorb and augment instances of objects using functional
inheritance:
// Define a pet object. Pass it a name and number of legs.
var pet = function (name, legs) {
// Create an object literal (that). Include a name property for public use
// and a getDetails() function. Legs will remain private.
// Any local variables defined here or passed to pet as arguments will remain
// private, but still be accessible from functions defined below.
var that = {
name: name,
getDetails: function () {
// Due to JavaScript's scoping rules, the legs variable
// will be available in here (a closure) despite being
// inaccessible from outside the pet object.
return that.name + ' has ' + legs + ' legs';
}
};
return that;
};
// Define a cat object, inheriting from pet.
var cat = function (name) {
var that = pet(name, 4); // Inherit from pet.
// Augment cat with an action method.
that.action = function () {
return 'Catch a bird';
};
return that;
};
// Create an instance of cat in petCat2.
var petCat2 = cat('Felix');
details = petCat2.getDetails();
action = petCat2.action();
petCat2.name = 'Sylvester';
petCat2.legs = 7;
details = petCat2.getDetails();
//
//
//
//
//
'Felix has 4 legs'.
'Catch a bird'.
We can change the name.
But not the number of legs!
'Sylvester has 4 legs'.
There is no funny prototype business here, and everything is nicely encapsulated. More
importantly, the legs variable is private. Our attempt to change a nonexistent public
legs property from outside cat simply results in an unused public legs property being
created. The real legs value is tucked safely away in the closure created by the get
Details() method of pet. A closure preserves the local variables of a function—in this
case, pet()—after the function has finished executing.
Code Reuse and Optimization | 3
In reality, there is no “right” way of performing inheritance with JavaScript. Personally,
I find functional inheritance a very natural way for JavaScript to do things. You and
your application may prefer other methods. Look up “JavaScript inheritance” in Google
for many online resources.
One benefit of using prototypal inheritance is efficient use of memory;
an object’s prototype properties and methods are stored only once, regardless of how many times it is inherited from.
Functional inheritance does not have this advantage; each new instance
will create duplicate properties and methods. This may be an issue if
you are creating many instances (probably thousands) of large objects
and are worried about memory consumption. One solution is to store
any large properties or methods in an object and pass this as an argument
to the constructor functions. All instances can then utilize the one object
resource rather than creating their own versions.
Keeping It Fast
The concept of “fast-moving JavaScript graphics” may seem like an oxymoron.
Truth be told, although the combination of JavaScript and a web browser is unlikely
to produce the most cutting-edge arcade software (at least for the time being), there is
plenty of scope for creating slick, fast-moving, and graphically rich applications, including games. The tools available are certainly not the quickest, but they are free,
flexible, and easy to work with.
As an interpreted language, JavaScript does not benefit from the many compile-time
optimizations that apply to languages like C++. While modern browsers have improved
their JavaScript performance enormously, there is still room to enhance the execution
speed of applications. It is up to you, the programmer, to decide which algorithms to
use, which code to improve, and how to manipulate the DOM in efficient ways. No
robot optimizer can do this for you.
A JavaScript application that only processes the occasional mouse click or makes the
odd AJAX call will probably not need optimization unless the code is horrendously
bad. The nature of applications covered in this book requires efficient code to give the
user a satisfactory experience—moving graphics don’t look good if they are slow and
jerky.
The rest of this chapter does not examine the improvement of page load times from
the server; rather, it deals with the optimization of running code that executes after the
server resources have loaded. More specifically, it covers optimizations that will be
useful in JavaScript graphics programming.
4 | Chapter 1: Code Reuse and Optimization
What and When to Optimize
Of equal importance to optimization is knowing when not to do it. Premature optimization can lead to cryptic code and bugs. There is little point in optimizing areas of an
application that are seldom executed. It’s a good idea to use the Pareto principle, or
80–20 rule: 20% of the code will use 80% of the CPU cycles. Concentrate on this 20%,
10%, or 5%, and ignore the rest. Fewer bugs will be introduced, the majority of code
will remain legible, and your sanity will be preserved.
Using profiling tools like Firebug will quickly give you a broad understanding of which
functions are taking the most time to execute. It’s up to you to rummage around these
functions and decide which code to optimize. Unfortunately, the Firebug profiler is
available only in Firefox. Other browsers also have profilers, although this is not necessarily the case on older versions of the browser software.
Figure 1-1 shows the Firebug profiler in action. In the Console menu, select Profile to
start profiling, and then select Profile again to stop profiling. Firebug will then display
a breakdown of all the JavaScript functions called between the start and end points.
The information is displayed as follows:
Function
The name of the function called
Percent
Percentage of total time spent in the function
Call
How many times the function was called
Own time
Time spent within a function, excluding calls to other functions
Time
Total time spent within a function, including calls to other functions
Average
Average of Own times
Min
Fastest execution time of function
Max
Slowest execution time of function
File
The JavaScript file in which the function is located
What and When to Optimize | 5
Figure 1-1. Firebug profiler in action
Being able to create your own profiling tests that work on all browsers can speed up
development and provide profiling capabilities where none exist. Then it is simply a
matter of loading the same test page into each browser and reading the results. This is
also a good way of quickly checking micro-optimizations within functions. Creating
your own profiling tests is discussed in the upcoming section “Homespun Code Profiling” on page 7.
Debuggers like Firebug can skew timing results significantly. Always
ensure that debuggers are turned off before performing your own timing
tests.
“Optimization” is a rather broad term, as there are several aspects to a web application
that can be optimized in different ways:
The algorithms
Does the application use the most efficient methods for processing its data? No
amount of code optimization will fix a poor algorithm. In fact, having the correct
6 | Chapter 1: Code Reuse and Optimization
algorithm is one of the most important factors in ensuring that an application runs
quickly, along with the efficiency of DOM manipulation.
Sometimes a slow, easy-to-program algorithm is perfectly adequate if the application makes few demands. In situations where performance is beginning to suffer,
however, you may need to explore the algorithm being used.
Examining the many different algorithms for common computer science problems
such as searching and sorting is beyond the scope of this book, but these subjects
are very well documented both in print and online. Even more esoteric problems
relating to 3D graphics, physics, and collision detection for games are covered in
numerous books.
The JavaScript
Examine the nitty-gritty parts of the code that are called very frequently. Executing
a small optimization thousands of times in quick succession can reap benefits in
certain key areas of your application.
The DOM and jQuery
DOM plus jQuery can equal a brilliantly convenient way of manipulating web
pages. It can also be a performance disaster area if you fail to observe a few simple
rules. DOM searching and manipulation are inherently slow and should be minimized where possible.
Homespun Code Profiling
The browser environment is not conducive to running accurate code profiling. Inaccurate small-interval timers, demands from events, sporadic garbage collection, and
other things going on in the system all conspire to skew results. Typically, JavaScript
code can be profiled like this:
var startTime = new Date().getTime();
// Run some test code here.
var timeElapsed = new Date().getTime() - startTime;
Although this approach would work under perfect conditions, for reasons already stated, it will not yield accurate results, especially where the test code executes in a few
milliseconds.
A better approach is to ensure that the tests run for a longer period of time—say, 1,000
milliseconds—and to judge performance based on the number of iterations achieved
within that time. Run the tests several times so you can perform statistical calculations
such as mean and median.
To ensure longer-running tests, use this code:
// Credit: based on code by John Resig.
var startTime = new Date().getTime();
for (var iters = 0; timeElapsed < 1000; iters++) {
// Run some test code here.
Homespun Code Profiling | 7
Tài liệu liên quan
Computer Graphics Primitives
Tài liệu Javascript
Tổng quan về JavaScript
Ngôn ngữ Javascript
Learning JavaScript A Hands-On Guide to the Fundamentals of Modern JavaScript
MATLAB Graphics
Advanced Graphics
Three-Dimensional Graphics
NHẬP MÔN JAVASCRIPT
BIẾN TRONG JAVASCRIPT
Tài liệu bạn tìm kiếm đã sẵn sàng tải về
(11.28 MB) - 560 supercharged javascript graphics
Tải bản đầy đủ ngay
×
9houz | https://text.123doc.org/document/5030608-560-supercharged-javascript-graphics.htm | CC-MAIN-2018-47 | refinedweb | 4,567 | 51.48 |
Looping in C# is a mechanism in which some instructions repeatedly execute until a particular condition reaches. C# supports looping mechanisms like while, do while, for loop, foreach loop
In C# programming, For loop is a range based loop. While loop and do while loops are condition-based loops.
If we know the range of how many times the loop should execute, then we use the for loop. If we don’t know the range, we use a while loop and do while loop. For example, if we want to print odd numbers from 1 to 10. We know that the loop should execute ten times, so we go with for loop.
But there will be a case where we have to fetch particular data from the database. In that case, we don’t know how many records are available in the database. So we have to use a while loop or do while loop to iterate the tables until the data fetched.
In C#, every loop will have three sections
Initialization: It is nothing but assigning a value to a variable.
Syntax:
<Datatype> <variable name> = value;
Ex: int i = 10;
Condition: This condition compares two or more values or expressions, and it will return a Boolean value.
Ex: 5 <= 7 – 2; which returns true.
Increment/Decrement: Incrementing or decrementing a variable value.
Ex:
int i = 5;
i++; it will increment i by 1.
i = i – 2; it will decrement i by 2.
C# For Loop
The C# For loop is a range-based loop, i.e., we can use for loop when we know how often the loop has to repeat. Within the C# for loop syntax, all the three sections initialization, condition check, and the increment/decrement will be in the same line with comma separation.
for(<initialization>; <boolean expression>; <increment/decrement>) { Statements; }
Apart from the C# for loop syntax, the for loop’s working is the same as the while loop. It means that once the variable is get initialized, it will check for the boolean expression. If the boolean expression evaluates to true, it enters the loop. It then executes the statements inside the loop and the next Increment/decrement of that variable. Again checks for the condition.
This process repeats until the boolean expression evaluates to true. Once it returns false, control comes out of the loop. It then continues the execution of the statements after the closing brace of the loop.
C# For Loop Example
Let us see an example code using for loop to print even numbers from 0 to 10.
using System; namespace CSharp_Tutorial { class Program { static void Main() { for (int i = 0; i <= 10; i++) { if (i == 10) break; if (i % 2 != 0) continue; Console.Write("{0} ", i); } Console.ReadLine(); } } }
OUTPUT
In this C# For loop example, i is an integer variable initialized with 0. The control enters the loop and checks if i==10, which returns false.
It checks 0 % 2 !=0 is false, hence continue is not executed and prints 0.
i incremented, i.e., i = 1. The control enters the loop and checks if i ==10 which returns false.
It checks 1 % 2 !=0, that is true, hence continue is executed and skips the print statement.
i incremented i.e., i = 2. The C# control enters the loop and checks if i==10, which returns false. Next, it checks 2 % 2 !=0 is false, hence continue is not executed and prints 2.
……..
When i increments 10, the control enters the loop and checks if i == 10, which returns true. So the break statement is executed, and control comes out of the loop. | https://www.tutorialgateway.org/csharp-for-loop/ | CC-MAIN-2021-17 | refinedweb | 604 | 75.2 |
Ever since Windows Phone came out, I have always contended that Live tiles are the coolest feature and one that is :
1) Not on any other platform (Yes, I know that Android has widgets… not the same thing)
2) A great way to drive people into your application. (Which you want if it is add based.)
I will do another post later about why you should do Live Tiles from a Monetizing standpoint, but for this post, I just want to show you how easy it is to work with live tiles.
To begin with, live tiles have been around since 7.0 but to really take advantage of them you had to use Push Notifications. While this is not THAT difficult, it did add quite a bit of complexity and the need to host your own service (or use scheduled tiles). In the Mango release, we have made 4 great additions to live tiles.
1) You can change the live tiles from your code.
2) You can create secondary tiles to deep link into specific pages of your application
3) You can write on the back of tiles and have them flip
4) You can use background process to have them change when not even in your application
To create and modify live tile is fairly simple.
This firs thing we want to do is create a simple windows phone page that has three buttons on it:
- Create App Tile
- Create Second Tile
- Delete Secondary Tile
Next we need to go to code behind and add a using statement for the phone shell.
using Microsoft.Phone.Shell;
Then inside the first button click we add the following code :
private void button1_Click(object sender, RoutedEventArgs e) { //Tile is always the first Tile, even if not pinned . ShellTile TileToFind = ShellTile.ActiveTiles.First(); if (TileToFind != null) { StandardTileData NewTileData = new StandardTileData(); NewTileData.Title = "My Cool Tile"; NewTileData.BackgroundImage = new Uri( "CoolTile.jpg", UriKind.Relative); NewTileData.Count = 5; NewTileData.BackTitle = "Tiles Got Back"; NewTileData.BackBackgroundImage = new Uri( "CoolTileBack.jpg", UriKind.Relative); TileToFind.Update(NewTileData); } }
- The first thing we do is get a reference to the Live Tile that comes with your application. (TileToFind)
- Once we have a reference to it we can create our new tile data using the StandardTileData class.
- We set the properties including the image we want on the live tile (a 173 by 173 png or jpg… make sure that your image is set to “content” in your project or you will not see it)
- Next we set the back of the tile
- And finally call the update method to change the live tile.
That is all you need to do to change your live tile.
If you want to create a secondary tile, it is slightly different.
for the second button click event we do the following
private void button2_Click(object sender, RoutedEventArgs e) { ShellTile SecondTile = ShellTile.ActiveTiles.FirstOrDefault( x => x.NavigationUri.ToString().Contains("Page2.xaml")); StandardTileData NewTileData; NewTileData = new StandardTileData(); NewTileData.Title = "Secondary Tile"; NewTileData.BackgroundImage = new Uri( "CoolTile.jpg", UriKind.Relative); NewTileData.Count = 5; NewTileData.BackTitle = "Second Tiles Got Back"; NewTileData.BackBackgroundImage = new Uri( "CoolTileBack.jpg", UriKind.Relative); if (SecondTile == null) { ShellTile.Create(new Uri( "/Page2.xaml", UriKind.Relative), NewTileData); } else { SecondTile.Update(NewTileData); } }
There are a couple of noticeable change. To find the secondary tile, we need to search for it since we are not guaranteed that it exists. We do this by searching the ActiveTiles collection for the NavigationUri of the tile that we set lower in the event. The only other change is creating the tile if it does not exist. Otherwise we update it like before.
If you want to run this code in the background so you can change the tile while users are not using the phone. You can check out my post on Background Agents
Enjoy | https://thesociablegeek.com/dev-stuff/live-tiles-in-wp-mango/ | CC-MAIN-2022-40 | refinedweb | 636 | 73.98 |
Preventing model elements from being deleted
- Friday, August 12, 2005 2:14 PM
DuncanP - not MSFTModeratorIs it possible to stop model elements from being deleted by a user? For example, I have a language model in which I want there to always be one and only one instance of ConceptA. I can ensure that all new diagrams will have an instance of the element when they are created, but how can I then stop the user from deleting the element?
Throwing an exception from withing "OnRemoving" appears to do the trick, but this is very crude, and causes problems since there appear to be times when the designer framework creates and removes elements behind the scenes (e.g. when initializing the toolbox).
Duncan
Answers
- Tuesday, August 16, 2005 6:56 PM
Grayson Myers MSFTHi Duncan,
Sorry it's taken a while to get a response on this one, I've been chewing it over for a bit. What it comes down to is that there are (or will be) multiple ways to accomplish this goal, depending on how strictly you want to enforce this in your model, and what you want the user experience to be. I'll outline three approaches below:
1. Strict enforcement in the model. You were on the right track here with the OnRemoving override, but a better place to do this is actually on the relationship which embeds the element you want to prevent removal of in the model. So, if you had an embedding relationship ConceptBHasConceptC connecting ConceptB (parent) and ConceptC (child), you could write the following code in a partial class:
This would prevent the ConceptC participating in this relationship from being removed, unless it's parent ConceptB was also being removed (this should alleviate the problems you were seeing before with the designer framework removing elements).
2. Enforcement in the model through constraints. In upcoming releases, we'll be enhancing and providing examples demonstrating use of our constraint framework. This gives you a way to write model constraints in C#, and have them run at a time specified by the DSL author, such as load, save, or when the user chooses a "Validate" menu item on your designer. Constraints which are violated appear as errors or warnings in the error list. This is not as strict as option #1.
3. Enforcement in the Designer UI. Overriding commands using the APIs we have today is tricky, but we are improving that, so in the future you'll be able to implement your own command status handler for the delete command easily, which will allow you to disable the delete command when certain shapes or model elements are selected in the designer (and delegate to the base implementation for everything else).
Hope this is helpful. If you try to implement option #1, let us know if you run into any difficulties. Designers we've written in the past (such as Whitehorse) have generally used strategies #2 and #3, sometimes in combination.
Thanks,
Grayson
All Replies
- Tuesday, August 16, 2005 9:06 PM
DuncanP - not MSFTModeratorThanks Grayson, that's very helpful.
So far I've been using a combination of #1 and #3, with limited success. I'll try option #1 based on the relationship rather than on the element directly.
Being able to specify a custom command status handler for delete would certainly be useful. I'd expect that customising the delete menu behaviour would be a pretty common task, so much so that I was wondering whether the default implementation could be a call to a "bool CanRemove()" method on the shape / element to decide whether or not to display the "delete" menu option.
This might give a neater way for DSL developers to implement domain-specific logic (i.e. in the appropriate model element) that would still give a better user experience by preventing the user from doing an inappropriate action, rather than showing them an error message afterwards. The custom domain logic could be as simple as always returning false for some element types, to complex rules based on the current state of the model.
Thanks again,
Duncan
- Tuesday, April 24, 2007 7:18 AM
Herru PerdanaHi Duncan,
Probably this is a bit an old issue, but I can't figure out to prevent the element being deleted. I tried Grayson's solution and I also tried deleting rule and throw InvalidOperationException. But the element is still deleted. I also tried RollBack the transaction, but it didn't work either. Can you please give me a clue on this? TIA.
Regards,
Hi Herru,
Both adding a deleting rule and overriding the "OnDeleting" method should work (the method name changed from "OnRemoving" to "OnDeleting").
The following two snippents of code both worked in my test language, based on the the Class Diagram template:
Method (1): Override OnRemovingCode Snippet
partial class ModelRootHasComments
{
protected override void OnDeleting()
{
base.OnDeleting();
// Allow the deletion if the parent (i.e. the model root)
// is being deleted.
if (!this.ModelRoot.IsDeleting && this.Comment != null)
{
throw new InvalidOperationException("Cannot delete comments");
}
}
}
Method (2): Adding a Deleting Rule
NB rule needs to be registered as usual.Code Snippet
[RuleOn(typeof(ModelRootHasComments), FireTime=TimeToFire.TopLevelCommit)]
public class StopCommentDeletionRule : DeletingRule
{
public override void ElementDeleting(ElementDeletingEventArgs e)
{
if (!e.ModelElement.Store.TransactionManager.CurrentTransaction.IsSerializing)
{
throw new ArgumentException("Cannot delete comments");
}
}
}
FYI There is also a (rather long) post on how to customize the explorer and diagram context menus to remove the "Delete" command at.
I'm not sure why these aren't working for you: is your rule being fired at all?
Duncan
- Tuesday, April 24, 2007 12:50 PM
Herru PerdanaThanks, Duncan.
Your Method (2) works perfectly to me now. My previous rule was registered, and fired properly.
For Method (1), I did basically the same as you wrote there. I was aware with the changes. Here is my code for the OnDeleting():
public partial class ModuleHasPorts
{
protected override void OnDeleting()
{
base.OnDeleting();
try
{
if (this.Module is CompositeModule)
throw new InvalidOperationException("Cannot delete.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
It showed the message, but the port was still deleted after. Thanks for the response,
Regards,
No problem.
The problem with your method (1) is that you are immediately catching your own exception, so it isn't propagating up the call stack and causing the transaction to be aborted. If you just take out the try-catch block, it should work. You don't need to explicitly display the error message using MessageBox.Show - this will be done for you.
Regards,
Duncan
- Tuesday, April 24, 2007 1:15 PM
Herru PerdanaOh, I see....
First I did not write the try-catch block. But it gave me warning that my exception is unhandled. and I thought this could be a problem. Anyway, many thanks Duncan!
Regards,
- Thursday, May 15, 2008 7:41 PM
benjamin.s
I wrote a small “library” to control the deletion of Model Elements by a function you can implement. The Delete command of the graphical DSL editor and the Model Explorer will be removed if the user is not allowed to delete the Model Element. See for more information.Benjamin | http://social.msdn.microsoft.com/forums/en-US/vsx/thread/eb51bb0f-74d3-4605-b60e-e08b7faaf164/ | crawl-002 | refinedweb | 1,192 | 54.32 |
Static Constructors (C# Programming Guide)
Updated: February 2009.
In this example, class Bus has a static constructor. When the first instance of Bus is created (bus1), the static constructor is invoked to initialize the class. The sample output verifies that the static constructor runs only one time, even though two instances of Bus are created, and that it runs before the instance constructor runs.
public class Bus { // Static variable used by all Bus instances. // Represents the time the first bus of the day starts its route. protected static readonly DateTime globalStartTime; // Property for the number of each bus. protected int RouteNumber { get; set; } // Static constructor to initialize the static variable. // It is invoked before the first instance constructor is run. static Bus() { globalStartTime = DateTime.Now; // The following statement produces the first line of output, // and the line occurs only once. Console.WriteLine("Static constructor sets global start time to {0}", globalStartTime.ToLongTimeString()); } // Instance constructor. public Bus(int routeNum) { RouteNumber = routeNum; Console.WriteLine("Bus #{0} is created.", RouteNumber); } // Instance method. public void Drive() { TimeSpan elapsedTime = DateTime.Now - globalStartTime; // For demonstration purposes we treat milliseconds as minutes to simulate // actual bus times. Do not do this in your actual bus schedule program! Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.", this.RouteNumber, elapsedTime.TotalMilliseconds, globalStartTime.ToShortTimeString()); } } class TestBus { static void Main() { // The creation of this instance activates the static constructor. Bus bus1 = new Bus(71); // Create a second bus. Bus bus2 = new Bus(72); // Send bus1 on its way. bus1.Drive(); // Wait for bus2 to warm up. System.Threading.Thread.Sleep(25); // Send bus2 on its way. bus2.Drive(); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Sample output: Static constructor sets global start time to 3:57:08 PM. Bus #71 is created. Bus #72 is created. 71 is starting its route 6.00 minutes after global start time 3:57 PM. 72 is starting its route 31.00 minutes after global start time 3:57 PM. */ | https://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.90).aspx | CC-MAIN-2015-14 | refinedweb | 344 | 62.24 |
> > I am trying to install Lynx version 2.6 on HPUX 10.10 > > ... > > I used "make snake3" ... > > This is the Error being listed > > =============================== > > > > (Bundled) cc: warning 480: The -O option is available only with the C/ANSI > > C product; ignored. > > I believe this is the crux of your problem ... HP has 2 C compilers ... a > "bundled" one it ships will all systems so you can re-build the kernel > when needed and a different, far better but "for optional cost" compiler > which handles ANSI C (the "free" one does not.) It appears you are using > the bundled one. the development version (afaik) builds with either - though I have no 10.x system to verify this. (Lynx's source-code can be built with either a K&R or ANSI compiler). > You could try to get/install the ANSI C compiler or we can "talk" off-line > from this list and I can try to arrange a way we can get my compiled > version to you. > > (BTW, that build is set up for installation into the now-more-standard for > HP-UX 10.X+ "/opt/lynx" directory, rather than "/usr/local/bin".) > > If you do decide to continue to build it yourself, be aware that you may > be in for some other problems, too. From my "Notes" file: > > 2. Due to a bug in the delivered HP-UX curses package, this version of > lynx was built with ncurses. In order to accomplish that, find the > 'snake3' portion of lynx2-7/Makefile and make it reference ncurses by > changing to these lines: > > -DSNAKE -I../$(WWWINC) $(SITE_DEFS) -I/opt/ncurses/include" \ > LIBS="-L/opt/ncurses/lib -lncurses -ltermcap \ there's more than one version of HP curses as delivered (the default one, I'm told, is the one with a broken 'select()' call - but Hcurses and curs_color may also work). You need an ANSI compiler with ncurses, but I don't know about the others. > (There may be other, better ways to do this, but this worked.) > > 3. To make it compile on HP-UX, make the following > change to lynx2-7/WWW/Library/snake/Makefile: > > CFLAGS = -O -DDEBUG -DUNIX > > ... [deleted notes about changes for "/opt/..." install] ... > > And just in case there are some Domain/OS users who read this far: I've not seen any for a while (are there any on lynx-dev?) > 7. For those who still have Apollo Domain/OS systems and would want to use > lynx 2.7 there, the original source would not have compiled since on that > system S_IFIFO is the same as S_IFSOCK. To correct this, I made one > additional change to prevent the S_IFSOCK code from being compiled on > Apollo systems. For this fix, change the code in the S_IFSOCK area of file > lynx2-7/WWW/Library/Implementation/HTFile.c to look like this: > > #ifndef apollo > #ifdef S_IFSOCK > case S_IFSOCK: type = 's'; break; > #endif /* S_IFSOCK */ > #endif /* apollo */ a little better, perhaps, (uglier but handles more than apollo): #ifdef S_IFSOCK # ifdef S_IFIFO # if S_IFIFO != S_IFSOCK case S_IFSOCK: type = 's'; break; # endif # else case S_IFSOCK: type = 's'; break; # endif #endif > Dave Eaton -- Thomas E. Dickey address@hidden | http://lists.gnu.org/archive/html/lynx-dev/1998-01/msg00498.html | CC-MAIN-2014-10 | refinedweb | 521 | 72.46 |
gdshortener 0.0.2
A module that provides access to .gd URL Shortener
Python Module for is.gd - v.gd URL Shortener.
What is this?
GD Shortener allow Python software to access is.gd - v.gd URL shortener service.
Using this module you could shorten an URL to a small one like Twitter does for its link.
This service is provided by is.gd - v.gd and, thru the classes in this module, you could view stats on shortened URLs and obtain reverse lookup on URLs.
Install
To install GD Shortener, run the following command:
pip install gdshortener
Usage
After install, to use GD Shortener is sufficient to import the package, choose the implementing class ISGDShortener or VGDShortener (it maps to is.gd or v.gd) and use the following code:
import gdshortener s = gdshortener.ISGDShortener() print s.shorten('')
If you want statistic usage on a URL use:
print s.shorten(url = '', log_stat = True)
If you want a custom URL use:
print s.shorten(url = '', custom_url = 'Pippus')
If you have an already shortened URL and want a reverse lookup:
print s.lookup('')
License
GD Shortener is licensed under LGPL. See LICENSE.txt for details.
- Downloads (All Versions):
- 22 downloads in the last day
- 137 downloads in the last week
- 338 | https://pypi.python.org/pypi/gdshortener | CC-MAIN-2015-14 | refinedweb | 210 | 69.68 |
22 October 2008 16:42 [Source: ICIS news]
LONDON (ICIS news)--Chemicals shares fell further on Wednesday as European stock markets dropped over renewed fears of a global recession and a deepening of the financial crisis.
At 14:29 GMT, the UK-based index FTSE was down 4.36%, ?xml:namespace>
Chemicals shares have dropped significantly during the past few weeks, with the Dow Jones Eurostoxx chemicals index losing more than 30% of its value in a month.
German chemicals and pharmaceuticals major Bayer’s shares were down 4.14% to €41.40 on Wednesday, while BASF’s shares were 4.58% lower at €23.75.
In the
The Bank of England’s governor Mervyn King has said that the
The country’s Prime Minister Gordon Brown also said the economic downturn was likely to cause a recession.
On Tuesday, the International Monetary Fund (IMF) said more European banks may fail due to continued worries about the viability of their business models.
In a six-monthly study it said private funding was virtually unavailable and that banks were forced to reply on public intervention, asset sales and consolidation.
It also warned that growth in the eurozone would almost grind top a standstill next year.
($1 = €0.76/Swfr1. | http://www.icis.com/Articles/2008/10/22/9165642/europe-chems-share-fall-as-investor-fears-resume.html | CC-MAIN-2013-20 | refinedweb | 208 | 62.27 |
Important: Please read the Qt Code of Conduct -
[solved] Custom QGraphicsPixmapItem
Hello
I'm trying to create a QGraphicsPixmapItem that would allow me to switch the image via a signal/slot connect as well as to react to mouse clicks. I've come this far (see below) but can figure out what is wrong. First of all, the code doesn't seem to react to mouse clicks. I've not yet been able to test if the image switching works. Any help how to construct such an class is highly welcomed and appreciated. Thank you!
Best regards
Richard
@
#ifndef imgElement_H
#define imgElement_H
#include <QGraphicsPixmapItem>
#include <QString>
#include <QPoint>
#include "node.h"
#include "mainwindow.h"
class imgElement : public QObject, public QGraphicsPixmapItem
{
public:
imgElement(const QPixmap &pixmap, QGraphicsItem *parent = 0,
QGraphicsScene *scene = 0);
~imgElement();
private:
QPixmap mainImage;
QPoint mousePos;
QGraphicsScene *scene;
protected:
virtual void mousePressEvent ( QMouseEvent * e );
virtual void mouseReleaseEvent ( QMouseEvent * e );
private slots:
void switchImage(QString imgPath);
};
#endif // imgElement_H
#include "imgElement.h"
imgElement::imgElement(const QPixmap &pixmap, QGraphicsItem *parent,
QGraphicsScene *scene)
: QGraphicsPixmapItem(pixmap, parent, scene){
this->scene = scene;
this->mainImage = pixmap;
}
imgElement::~imgElement(){}
void imgElement::mousePressEvent ( QMouseEvent * e )
{
mousePos = e->pos();
}
void imgElement::mouseReleaseEvent ( QMouseEvent * e )
{
// Do some interesting stuff
}
void imgElement::switchImage(QString imgPath){
mainImage.load(imgPath);
this->setPixmap(mainImage);
}@
*added to code tags by request (wasn't aware of them)
Hello,
It would be more readable if you put you code in the code tags....
thanks ;)
I tried the SIGNAL/SLOT but it failed as the "Q_OBJECT" was missing. The problem is, if I add it
@class Jhumar : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
public:
Jhumar(const QPixmap &pixmap, QGraphicsItem *parent = 0,
QGraphicsScene *scene = 0); ...@
I get errors saying "undefined reference to 'vtable for imgElement". How can I make it derrive from the object class, making the slot visible? This would probably solve the "event issue" as well... Thanks!
I got rid of the vtable error by rerunning qmake () but the mouse evets still doesn't work (the image switch does however :D )
I don't really know why you don't pass in the mousePress Event
However, if your object inherits QGraphicsPixmapI, you don't have to makes it inherit with QObject, since QGraphicsPixmapI itself is a QObject... could you try without it ?
Hello. Don't know why, but when I remove the QObject inheritance the slot stops working... Yet, actuallyjust got it working, the trick to the mouse even was to use
@void mousePressEvent (QGraphicsSceneMouseEvent *event);@
instead of
@void imgElement::mousePressEvent ( QMouseEvent * e )@
Hopefully this will help someone avoid the same mistake. :)
your constructor doesn't mention QGraphicsPixmapItem....--
Hello
Correct me if I'm wrong, but shouldn't this part handle the initialization of the QGraphicsPixmapItem ?
@: QGraphicsPixmapItem(pixmap, parent, scene)@
I think that if your element is a child of QGraphicsPixmapItem, your constructor must have an initialisation with some QGraphicsPixmapItem.... | https://forum.qt.io/topic/9739/solved-custom-qgraphicspixmapitem | CC-MAIN-2020-40 | refinedweb | 472 | 51.48 |
Forest ReservesINowIgnoring compiler warnings. When there are many of them in the list, you risk easily missing genuine errors in the lately written code. That's why you should address them all.
Issue 2In the conditional statement of the if operator, a variable is assigned a value instead of being tested for this value:
if (numb_numbc = -1) { }The code is compiled well in this case, but the compiler produces a warning. The correct code is shown below:
if (numb_numbc == -1) { }
Issue 3The statement using namespace std; written in header files may cause using this namespace in all the files which include this header, which in turn may lead to calling wrong functions or the occurrence of name collisions.
Issue 4Comparing signed variables to unsigned ones:
unsigned int BufPos; std::vectorKeep in mind that mixing signed and unsigned variables may result in:
ba; .... if (BufPos * 2 < ba.size() -Neglecting usage of constants may lead to overlooking hard-to-eliminate bugs. For example:
void foo(std::string &str) { if (str = "1234") { } }The = operator is mistakenly used instead of ==. If the str variable were declared as a constant, the compiler would not even compile the code.
Issue 6PointersBufferBufferIncorrectComparing a variable to a value it can never reach. For example:
short s; ... If (s==0xaaaa) { }The compiler produces warnings against such things.
Issue 12Memory is allocated with the help of new or malloc, while forgotten to be freed through delete/free correspondingly. It may look something like this:
void foo() { std::vectorPerhaps it was the pointer to std::vector
*v1 = new std::vector ; std::vector v2; v2->push_back(*v1); ... }
void foo() { std::vector
v1; std::vector v2; v2->push_back(v1[0]); ... }
Issue 13Memory is allocated through new[] and freed through delete. Or, vice versa, memory is allocated through new and freed through delete[].
Issue 14Using uninitialized variables:
int sum; ... for (int i = 0; i < 10; i++) { sum++; }In C/C++, variables are not initialized to zero by default. Sometimes code only seems to run well, which is not so - it's merely luck.
Issue 15AValuesNeglecting usage of special static and dynamic analysis tools, as well as creation and usage of unit-tests.
Issue 18BeingArrayPriorities.
You need to be a member in order to leave a comment
Sign up for a new account in our community. It's easy!Register a new account
Already have an account? Sign in here.Sign In Now | https://www.gamedev.net/articles/programming/general-and-gameplay-programming/grounded-pointers-r3357/ | CC-MAIN-2018-39 | refinedweb | 398 | 56.96 |
Linux Content
All Articles
Interviews
Linux in the Enterprise
Security Alerts
Administration
Browsers
Caching
Certification
Community
Database
Desktop
Device Drivers
Devices
Firewalls
Game Development
Getting Started
Kernel
LDAP
Multimedia
Networking
PDA
Programming
Security
Tools
Utilities
Web Design and Development
X Window System
Perhaps you rarely face it, but once you do, you surely know what's wrong: lack of free memory, or Out of Memory (OOM). The results are typical: you can no longer allocate more memory and the kernel kills a task (usually the current running one). Heavy swapping usually accompanies this situation, so both screen and disk activity reflect this.
At the bottom of this problem lie other questions: how much memory do you want to allocate? How much does the operating system (OS) allocate for you? The basic reason of OOM is simple: you've asked for more than the available virtual memory space. I say "virtual" because RAM isn't the only place counted as free memory; any swap areas apply.
To begin exploring OOM, first type and run this code snippet that allocates huge blocks of memory:
#include <stdio.h>
#include <stdlib.h>
#define MEGABYTE 1024*1024
int main(int argc, char *argv[])
{
void *myblock = NULL;
int count = 0;
while (1)
{
myblock = (void *) malloc(MEGABYTE);
if (!myblock) break;
printf("Currently allocating %d MB\n", ++count);
}
exit(0);
}
Compile the program, run it, and wait for a moment. Sooner or later it will go OOM. Now compile the next program, which allocates huge blocks and fills them with 1:
#include <stdio.h>
#include <stdlib.h>
#define MEGABYTE 1024*1024
int main(int argc, char *argv[])
{
void *myblock = NULL;
int count = 0;
while(1)
{
myblock = (void *) malloc(MEGABYTE);
if (!myblock) break;
memset(myblock,1, MEGABYTE);
printf("Currently allocating %d MB\n",++count);
}
exit(0);
}
Notice the difference? Likely, program A allocates more memory blocks than program B does. It's also obvious that you will see the word "Killed" not too long after executing program B. Both programs end for the same reason: there is no more space available. More specifically, program A ends gracefully because of a failed malloc(). Program B ends because of the Linux kernel's so-called OOM killer.
malloc()
The first fact to observe is the amount of allocated blocks. Assume that you have 256MB of RAM and 888MB of swap (my current Linux settings). Program B ended at:
Currently allocating 1081 MB
On the other hand, program A ended at:
Currently allocating 3056 MB
Where did A get that extra 1975MB? Did I cheat? Of course not! If you look closer on both listings, you will find out that program B fills the allocated memory space with 1s, while A merely simply allocates without doing anything. This happens because Linux employs deferred page allocation. In other words, allocation doesn't actually happen until the last moment you really use it; for example, by writing data to the block. So, unless you touch the block, you can keep asking for more. The technical term for this is optimistic memory allocation.
Checking /proc/<pid>/status on both programs will reveal the facts. Here's program A:
$ cat /proc/<pid of program A>/status
VmPeak: 3141876 kB
VmSize: 3141876 kB
VmLck: 0 kB
VmHWM: 12556 kB
VmRSS: 12556 kB
VmData: 3140564 kB
VmStk: 88 kB
VmExe: 4 kB
VmLib: 1204 kB
VmPTE: 3072 kB
Here's program B, shortly before the OOM killer struck:
$ cat /proc/<pid of program B>/status
VmPeak: 1072512 kB
VmSize: 1072512 kB
VmLck: 0 kB
VmHWM: 234636 kB
VmRSS: 204692 kB
VmData: 1071200 kB
VmStk: 88 kB
VmExe: 4 kB
VmLib: 1204 kB
VmPTE: 1064 kB
VmRSS deserves further explanation. RSS stands for "Resident Set Size." It explains how many of the allocated blocks owned by the task currently reside in RAM. Also note that before B reaches OOM, swap usage is almost 100 percent (most of the 888MB), while A uses no swap at all. It's clear that malloc() itself did nothing more than just preserve a memory area, nothing else.
Another question also arises. "Even without touching the pages, why is the allocation limit 3056MB?" This exposes an unseen limit. For every application in a 32-bit system, there is 4GB of address space available for usage. The Linux kernel usually splits the linear address to provide 0 to 3GB for user space and 3GB to 4GB for kernel space. User space is a room where a task can do anything it wants, while kernel space is solely for the kernel. If you try to cross this 3GB border, you will get a segmentation fault.
The conclusion is that OOM happens for two technical reasons:
Thus the strategies to prevent those circumstances are:
When you ask for a memory block, usually by using malloc(), you're asking the runtime C library whether a preallocated block is available. This block's size must at least equal the user request. If there is already a memory block available, malloc() will assign this block to the user and mark it as "used." Otherwise, malloc() must allocate more memory by extending the heap. All requested blocks go in an area called the heap. Do not confuse it with the stack, because the stack stores local variable and function return addresses. These two sections have different jobs.
Where is the heap located in the address space? The process address map can tell you exactly where:
$ cat /proc/self/maps
08048000-0804c000 r-xp 00000000 16:41 130592 /bin/cat
0804c000-0804d000 rwxp 00003000 16:41 130592 /bin/cat
0804d000-0806e000 rwxp 0804d000 00:00 0 [heap]
b7d95000-b7f95000 r-xp 00000000 16:41 2239455 /usr/lib/locale/locale-archive
b7f95000-b7f96000 rwxp b7f95000 00:00 0
b7fa9000-b7faa000 r-xp b7fa9000 00:00 0 [vdso]
bfe96000-bfeab000 rw-p bfe96000 00:00 0 [stack]
This is an actual address space layout shown for cat, but you may get different results. It is up to the Linux kernel and the runtime C library to arrange them. Notice that recent Linux kernel versions (2.6.x) kindly label the memory area, but don't completely rely on them.
cat
The heap is basically free space not already given for program mapping and stack; thus, it narrows down the available address space. It's not a full 3GB, but it's 3GB minus everything else that's mapped. The bigger your program's code segment is, the less space you have for heap. The more dynamic libraries you link into your program, the less space you get for the heap. This is important to remember.
How does the map for program A look when it can't allocate more memory blocks? With a trivial change to pause the program (see loop.c and loop-calloc.c) just before it exits, the final map is:
0009a000-0039d000 rwxp 0009a000 00:00 0 ---------> (allocated block)
005ce000-08048000 rwxp 005ce000 00:00 0 ---------> (allocated block)
08048000-08049000 r-xp 00000000 16:06 1267 /test-program/loop
08049000-0804a000 rwxp 00000000 16:06 1267 /test-program/loop
0806d000-b7f62000 rwxp 0806d000 00:00 0 ---------> (allocated block)
b7f73000-b7f75000 rwxp b7f73000 00:00 0 ---------> (allocated block)
b7f75000-b7f76000 r-xp b7f75000 00:00 0 [vdso]
b7f76000-bf7ee000 rwxp b7f76000 00:00 0 ---------> (allocated block)
bf80d000-bf822000 rw-p bf80d000 00:00 0 [stack]
bf822000-bff29000 rwxp bf822000 00:00 0 ---------> (allocated block)
Six Virtual Memory Areas, or VMAs, reflect the memory request. A VMA is a memory area that groups pages with the same access permission and/or the same backing file. VMAs can exist anywhere within user space, as long as that space is available.
Now you might think, "Why six? Why not a single big VMA containing all blocks?" There are two reasons. First, it is often impossible to find such a big "hole" to coalesce the blocks into a single VMA. Second, the program does not ask to allocate that approximately 3GB block all at once, but piece by piece. Thus, the glibc allocator has complete freedom to arrange the memory however it wants.
glibc
Why do I mention available pages? Memory allocation occurs in page-sized granularity. This is not a limit of the operating systems, but a feature of the Memory Management Unit (MMU) itself. Pages have various sizes, but the normal setting for x86 is 4K. You can discover the page size manually by using getpagesize() or sysconf() (with the _SC_PAGESIZE parameter) libc functions. The libc allocator manages each page: slicing them into smaller blocks, assigning them to processes, freeing them, and so on. For example, if your program uses 4097 bytes total, you need to use two pages, even though in reality the allocator gives you somewhere between 4105 to 4109 bytes.
getpagesize()
sysconf()
_SC_PAGESIZE
libc
With 256MB of RAM and no swap, you have 65536 available pages. Is that right? Not really. What you don't see is that some memory areas are in use by kernel code and data, so they're unavailable for any other need. There is also a reserved part of memory for emergencies or high-priority needs. dmesg reveals these numbers for you:
dmesg
$ dmesg | grep -n kernel
36:Memory: 255716k/262080k available (2083k kernel code, 5772k reserved,
637k data, 172k init, 0k highmem)
171:Freeing unused kernel memory: 172k freed
init refers to kernel code and data that is only necessary for the initialization stage; thus the kernel frees it when it is no longer useful. That leaves 2083 + 5772 + 637 = 8492KB. Practically speaking, 2123 pages are gone from the user's point of view. If you enable more kernel features or insert more kernel modules, you'll use up more pages for exclusive kernel use, so be wise.
init
Another kernel internal data structure is the page cache. The page cache buffers data recently read from block devices. The more caching work you do, the fewer free pages you actually have--but they are not really occupied, as the kernel will reclaim them when memory is tight.
From the kernel and hardware points of view, these are the important things to remember:
There is no guarantee that allocated memory area is physically contiguous; it's only virtually contiguous.
This "illusion" comes from the way address translation works. In a protected mode environment, users always work with virtual addresses, while hardware works with physical addresses. The page directory and page tables translate between these two. For example, two blocks with starting virtual addresses 0 and 4096 could map to the physical addresses 1024 and 8192.
This makes allocation easier, because in reality it is unlikely to always get continuous blocks, especially for large requests (megabytes or even gigabytes). The kernel will look everywhere for free pages to satisfy the request, not just adjacent free blocks. However, it will do a little more work to arrange page tables so that they appear virtually contiguous.
There is a price. Because memory blocks might be non-contiguous, sometimes the L1 and L2 caches go underused. Virtually adjacent memory blocks may be spread across different physical cache lines; this means slowing down (sequential) memory access.
Memory allocation takes two steps: first extending the length of memory area and then allocating pages when needed. This is demand paging. During VMA extension, the kernel merely checks whether the request overlaps existing VMA and if the range is still inside user space. By default, it omits the check whether actual allocation can occur.
Thus it is not strange if your program asks for a 1GB block and gets it, even if in reality you have only 16MB of RAM and 64MB of swap. This "optimistic" style might not please everybody, because you might get the false hope of thinking that there are still free pages available. The Linux kernel offers tunable parameters to control this overcommit behavior.
There are two type of pages: anonymous pages and file-backed pages. A file-backed page originates from mmap()-ing a file in disk, whereas an anonymous page is the kind you get when doing malloc(). It has no relationship with any files at all. When the RAM becomes tight, the kernel swaps out anonymous pages to swap space and flushes file-backed pages to the file to give room for current requests. In other words, anonymous pages may consume swap area while file-backed pages don't. The only exception is for files mmap()-ed using the MAP_PRIVATE flag. In this case, file modification occurs in RAM only.
mmap()
MAP_PRIVATE
This is where the understanding of swap as RAM extension comes from. Clearly, accessing the page requires bringing it back into RAM.. | http://www.linuxdevcenter.com/pub/a/linux/2006/11/30/linux-out-of-memory.html?page=1 | CC-MAIN-2015-32 | refinedweb | 2,108 | 62.88 |
Expert Python Programming — Save 50%
Best practices for designing, coding, and distributing your Python software.
Where do you get it?
Before getting started, you’ll need to download IronPython 2.0.1 (though the contents of this article could just as easily be applied to past or even future versions). The official IronPython site is. Here you’ll find not only the IronPython bits, but also samples, source code, documentation and many other resources. After clicking on the "Downloads" tab at the top you will be presented with three download options: IronPython.msi, IronPython-2.0.1-Bin.zip (the binaries) or IronPython-2.0.1-Src.zip (the source code). If you already have CPython installed—the standard Python implementation—the binaries are probably your best bet. You simply unzip the files to your preferred installation directory and you’re done. If you don’t have CPython installed, I recommend the IronPython.msi file since it comes prepackaged with portions of the CPython Standard Library.
Figure 1. IronPython installation directory.
There are a few items I would like to highlight in the IronPython installation directory displayed in Figure 1. The first is the FAQ.html file. This covers all of your basic IronPython questions, from licensing questions to implementation details. Periodically reviewing this while you’re learning IronPython will probably save you a lot of frustration. The second item of importance is the two executables, ipy.exe and ipyw.exe. As you probably guessed, these are what you use to launch IronPython; ipy.exe is used for scripts and console applications while ipyw.exe is reserved for other types of applications (Windows Forms, WPF, etc). Lastly, I’d like to draw your attention to the Tutorial folder. Inside the Tutorial folder, you’ll find a Tutorial.html file in addition to a number of other files. The Tutorial.html file is a comprehensive review of what you need to know to get started with IronPython. If you want to be quickly productive, be sure to at least review the tutorial. It will answer many of your questions.
Visual Studio or a Text Editor?
One thing that neither the ReadMe nor the Tutorial really covers is the tooling story. While Visual Studio 2008 is a viable Python development tool, you may want to consider other options. Personally, I bounce between VS and SciTE, but I’m always watching for new tools that might improve my development experience. There are a number of IDEs and debuggers out there and you owe it to yourself to investigate them. Sometimes, however, Visual Studio IS the right tool for the job. If that’s the case then you’ll need to install the Visual Studio SDK from.
Let’s Write Some Code!
To get started, let’s create a simple python script and execute it with ipy. In a new file called "sample.py" (Python files are indicated by a ".py" extension), type "print ‘Hello, world’". Open a command window, navigate to the directory where you saved sample.py and then call ipy.exe passing "sample.py" as an argument. Figure 1 displays what you might expect to see in the console window.
Figure 2. Executing a script using the comand line
Not that executing from the Command Line isn’t effective, but I prefer a more efficient approach. Therefore I’m going to use SciTE, an editor I briefly mentioned earlier, to duplicate the example in Figure2. Why SciTE? I get syntax highlighting, I can run my code simply by hitting F5 and the stdout is redirected to SciTE’s output window. In short, I never have to leave my coding environment. If you performed the above "hello, world" example in SciTE, the example would look like Figure 2.
Figure 3. Executing a script using SciTE
Congratulations! You’ve written your first bit of Python code! The problem is it doesn’t really touch any .NET namespaces. Fortunately, this is not a difficult thing to do. Figure 3 shows all the code you need to start working with the System namespace.
Figure 4. You only need a single of code to gain access to the System namespace
With that simple import statement, we now enjoy access to the entirety of the System namespace. For example, to access the String class we simply would type System.String. That’s great for getting started but what happens when we want to use something like the Regex class? Do we have to type System.Text.RegularExpressions.Regex?
Figure 5. Using .NET regular expressions from IronPython
No! The first line of Figure 5 introduces a new form of the import statement that only imports the specific items you want. In our case, we only want the Regex class. The code in line 3 demonstrates creating a new instance of the Regex class. Note the lack of a "new" keyword. Python considers "new" redundant since you have to include parentheses anyways. Another interesting note is the syntax—or is it the lack of syntax—for creating a variable. There’s no declaration statement or type required. We simply create a name that we set equal to a new instance of the Regex class. If you’ve ever written any PHP or classic ASP, this should feel pretty familiar to you. Finally, the print statement on line 6 produces the output shown in Figure 6.
Figure 6. Output from the Regex example
The last example was easy because IronPython already holds a reference to System and mscorlib. Let’s push our limits and create a simple Windows form. This requires a bit more work.
Figure 7. Using the clr module to add a reference
A Quick Review of Python Classes
Figure 7 introduces the clr module as a way of adding references to other libraries in the Global Assembly Cache (GAC). Once we have a reference, now we can import the Form, TextBox and Button classes so we can start constructing our GUI. Before we do that though, we have a couple of concepts we need to cover.
Figure 8. Introducing classes and methods
Up until this point, we really haven’t needed to create any classes or methods. But now that we need to create a form we’re going to need both. Figure 8 demonstrates a very simple class and an equally simple method. I think it’s clear that the "class" keyword defines a class and the "def" keyword defines a method. You probably correctly assumed that "(object)" after "MyClass" is Python’s way of expressing inheritance. The "pass" keyword, however, may not be immediately obvious. In Python, classes and methods cannot be empty. Therefore, if you have a class or method that you aren’t quite ready to code yet, you can use the "pass" statement until you are ready.
A more subtle characteristic of Figure 8 is the whitespace. In Python we indent the contents of control structures with four spaces. Tabs will also work, but by convention four spaces are used. In our example above, since "my_method" has no preceding spaces, it’s clear that "my_method" is not part of "MyClass".
So how would we make "my_method" a class method? Logically, you would think that simply deleting the "pass" statement under "MyClass" and indenting "my_method" would be enough, but that isn’t the case. There’s one more addition we need to make.
Figure 9. Creating a class method
As Figure 9 demonstrates, we need to pass "self" as a parameter to "my_method". The first—and sometimes the only—parameter in a class method’s parameter list must always be an instance of the containing class. By convention, this parameter should be named "self", though you could call it anything you’d like. Why the extra step? That’s because Python values the explicit over the implicit. Hiding this detail from the developer is at odds with Python’s philosophy.
Creating a Windows Form
Now that we have an understanding of classes, methods and whitespace, Figure 10 continues our example from Figure 7 by creating a blank form.
Figure 10. Creating a blank form
The code in Figure 10 should be fairly understandable. We create the "MyForm" class by inheriting from "System.Windows.Forms.Form". We create a new instance of "MyForm" and pass the resulting object to the "Application.Run()" method. The only thing that may give you pause is the "__init__()" method. The "__init__()" method is what’s called a magic method. Magic methods are designated with double underscores on either end of the method name and are rarely called directly. For instance, when the code in Line 10 of Figure 10 executes, the "__init__()" method defined in "MyForm" is actually being called behind the scenes.
Figure 11. Populating the form with controls and handling an event handler
Figure 11 adds a lot of code to our application, most of which isn’t very interesting. The exception here is the Click event of the goButton. In C#, the method would get passed as an argument in the constructor of a new EventHandler. In IronPython, we simply add a function with the proper signature to the Click event. Now that we have a button that will respond to a click, Figure 12 shows a modified version of our regular expression sample code from earlier inserted into the click method. Note the "__str__()" magic method is the equivalent of ToString().
Figure 12. Populating click with our regular expression example
When we run the code, you should see the form displayed in Figure 13. You can enter dates into the top textbox, press the button and either True or False will appear in the lower textbox indicating the results of the IsMatch() function.
Figure 13. Completed form
Conclusion
During the course of one brief article, you went from knowing little of IronPython to using it to build Windows Forms. We were able to move so quickly because we leveraged your existing .NET knowledge. We spent most of our time talking about the very intuitive Python syntax. Go through sample or even production code you've written in the past and duplicate it in IronPython. You’ll find working with familiar .NET libraries will speed your learning process, making it more fun. Before you know it, Python will become second-nature!
About the Author :
Darrell Hawley
Darrell Hawley is a Microsoft C# MVP developing engineering software while researching Python and agile development techniques. He has streamlined business processes as well as administered company networks and SQL Server installations. He also has proficiencies in code generation, web services, ASP.NET, Smart Clients, VB.NET, Visual Basic, VBA, VBScript and ASP. He is a board member of the Ann Arbor .NET Developers Group and frequently speaks at user groups and conferences around Ohio and Michigan.
Books From Packt
Post new comment | http://www.packtpub.com/article/getting-a-jump-start-with-ironpython | CC-MAIN-2014-15 | refinedweb | 1,804 | 66.33 |
im_LabQ2Lab, im_Lab2LabQ, im_LabQ2LabS, im_LabS2LabQ, im_Lab2LabS, im_LabS2Lab - pack and unpack LABPACK images.
#include <vips/vips.h> int im_LabQ2Lab(in, out) IMAGE *in, *out; int im_Lab2LabQ(in, out) IMAGE *in, *out; int im_Lab2LabS(in, out) IMAGE *in, *out; int im_LabS2LabQ(in, out) IMAGE *in, *out; int im_LabS2Lab(in, out) IMAGE *in, *out; int im_LabQ2LabS(in, out) IMAGE *in, *out;
These functions pack and unpack LAB images. LabQ is Lab packed in to 4 unsigned chars, with the Coding field set to LABPACK. It counts as a coded type, since most operations will not give the correct result on an image of this type. This is the MARC image type. Bits are allocated as 10 for L and 11 for each of a and b. The first three bytes contain the 8 most significant bits of Lab respectively, the final byte has 2/3/3 bits (MSB on left) of Lab respectively. im_LabQ2Lab() and im_Lab2LabQ() convert LABPACK images to three band float images, scaled to look sensible to humans. This is the most convenient LAB format for development work, but is rather slow. im_LabQ2LabS() and im_LabS2LabQ() convert LABPACK to and from three band signed short images. L is shifted and masked to be in the range [0,32767], a and b are shifted and masked to lie in [-32768,32767]. This is the best computational LAB format, combining precision and speed. Programs such as conv(1X) and similarity(1X), which can operate directly on LABPACK images, unpack to LabS for computation.
The functions return 0 on success and -1 on error.
im_col_XYZ2rgb(3), im_dE_fromdisp(3), im_XYZ2disp(3).
National Gallery, 1990 - 1993
J. Cupitt - 21/7/93 2 Decemder 1992 IM_XYZ2disp(3) | http://huge-man-linux.net/man3/im_LabS2Lab.html | CC-MAIN-2018-13 | refinedweb | 278 | 72.97 |
Stuart Celarier, Fern Creek, .NET/XML Consultant, course author, trainer
Please email comments and corrections to faq@ferncrk.com.
Updated January 24, 2005, 6:24 PM Pacific Standard Time
.NET Compact Framework (General) | .NET Compact Framework 1.0 | .NET Compact Framework 2.0
.NET Compact Framework 2.0 Releases
Spotlight: In the News
.NET Compact Framework 2.0 Development (General)
Windows Forms
Controls
Data
COM Interoperability
Emulators
Debugging
Deployment
Visual Studio 2005 and Other Tools
Topics in this FAQ are organized into a series of pages. This key is your guide to the organization of topics into pages and the relations between them.
.NET Compact Framework (General)
.NET Compact Framework (General)covers general topics in developing managed applications for mobile devices, including how to get started, information about devices and native operating systems, as well as debugging and deploying software.
Related sections. See .NET Compact Framework 1.0 for developing with the .NET Compact Framework (CF) 1.0 and Visual Studio .NET.
See .NET Compact Framework 2.0 for developing with pre-release versions of the .NET Compact Framework 2.0 and Visual Studio 2005 (formerly codenamed "Whidbey").
.NET Compact Framework 1.0
.NET Compact Framework 1.0 covers development topics on the .NET Compact Framework (CF) 1.0, as well as Visual Studio .NET 2002/2003 and other tools. There is also information about releases and service packs for CF 1.0.
Related sections. See .NET Compact Framework (General) for general information about developing for mobile devices that is not specific to a version of the .NET Compact Framework.
.NET Compact Framework 2.0
.NET Compact Framework 2.0 covers development topics on the pre-release versions of .NET Compact Framework (CF) 2.0, and using Visual Studio 2005 (formerly codenamed "Whidbey") and other tool. There is also information about different pre-release versions, as well as which features are available in current versions.
Related sections. See .NET Compact Framework 1.0 for information that may be identical in .NET Compact Framework 2.0.
See .NET Compact Framework (General) for general information about developing for mobile devices that not specific to a version of the .NET Compact Framework.
Where can I get a Beta or Community Technology Preview (CTP) of the .NET Compact Framework 2.0?
Betas and CTP releases are available to MSDN subscribers in the Subscriber Downloads.
Daniel Moth, 8 December 2004#
No product version has been specified for this FAQ item. Please report status updates here.
What devices currently include the .NET Compact Framework 2.0?
None at this point: since the .NET Framework 2.0 (include .NET Compact Framework 2.0) is in Beta testing, it cannot possibly be included into any shipping device ROM.
Alex Feinman, 12 December 2004#
Can existing devices download the .NET Compact Framework 2.0?
Yes, those based on Windows Mobile 2003 and newer.
What versions of Visual Studio support developing for the .NET Compact Framework 2.0?
Only Visual Studio 2005 supports .NET Compact Framework 2.0 development.
What is the expected release date for .NET Compact Framework 2.0?
The .NET CF 2.0 will likely RTM with Visual Studio 2005 in the first half of 2005. However, the .NET CF 1.0 had a "go live" license that enabled developers to redistribute a prerelease build prior to RTM. It's possible this may happen again.
It's also possible that .NET CF 2.0 will ship in ROMs on Windows Mobile 2003 devices after it becomes available. It all depends on whether Microsoft provides an adaptation kit for the OEMs and whether the OEMs will opt to use it.
Also you might anticipate a free SDK for .NET CF 2.0. I don't think anything has been announced, but I know that Microsoft has taken the feedback about not having one for .NET CF 1.0 very seriously.
Ed Kaim, 13 December 2004#
How do I get support for the .NET Compact Framework 2.0 and Visual Studio 2005?
Use the Microsoft Visual Studio 2005 newsgroups which you can use through the web interface or follow the directions on that that page for using an NNTP reader. For .NET Compact Framework 2.0 support, see the microsoft.private.whidbey.smartdevices newsgroups.
Stuart Celarier, Fern Creek, 1 January 2005#
Deploying CF applications is broken in Visual Studio 2005 November CTP. Is there a fix?
Symptoms. Using the Visual Studio 2005 November Community Technology Preview (CTP), if you try to deploy your .NET Compact Framework application using F5 or Ctrl+F5 it will fail to deploy.
Solution:A patch has been made available, on an as-is basis, that fixes this problem. You are strongly encouraged to read the instructions on the Visual Studio for Devices blog before downloading and installing the patch.
This issue has not been fixed in the December CTP, as reported here. In fact the Device bits in the December CTP are older than those in the November CTP, as explained here.
Stuart Celarier, Fern Creek, 8 January 2005#
This FAQ item is current to the Visual Studio 2005 November CTP release. Please report status updates here.
Is ClickOnce in .NET Compact Framework 2.0?
Unfortunately, Visual Studio 2005 will not support ClickOnce for Smart Device projects.
Ori Amiga, Visual Studio for Devices, Microsoft, 6 August 2004#
When will generics be available in the .NET Compact Framework 2.0?
We are actively working on support for generics in the .NET Compact Framework. We currently anticipate generics to be part of Visual Studio 2005 Beta 2 which I would expect to release in Q1 CY05.
What new controls are in .NET Compact Framework 2.0?
.NET Compact Framework (CF) 2.0 has both DateTimePicker and MonthCalendar controls. UserControl is supported in CF 2.0 which should make building controls with designer functionality easier. I'm not sure how much is implemented in the current build.
Peter Foot, MVP, Windows Embedded, 16 July 2004
Additional new controls include DocumentList, Notification, and DataConnector. UserControl and CustomControl are both supported current CF 2.0 release, you can create a UserControl as you do in desktop projects, having a UserControl designer and allow you to add controls to it. You can either add a UserControl to the project or adding a Windows Control Library project to your solution.
Keep in mind that Smartphone platform does not support UserControl so you would need to use CustomControl instead on that plaform.
David So, 16 July 2004#
What is the new Smart Device CAB Project in Visual Studio 2005?
There's a new project type for creating richer CAB files for device projects: it can be found under Other Project Types | Setup and Deployment | Smart Device CAB Project. It now allows you to visually create CABs by dragging-and-dropping registry and file entries, etc.
What kinds of mobile applications are supported by Visual Studio 2005?
Visual Studio 2005 (Whidbey) Beta 1 includes Smart Device development. However the Visual Basic and C# Express packages do not.
Only PocketPC 2003, Smartphone 2003, CE 5 and above, and future Windows Mobile and Smartphone versions will be supported by Visual Studio 2005. If you need to develop for any earlier version of PocketPC, then you need Visual Studio .NET 2003 Pro or above.
Peter Foot, MVP, Windows Embedded; and Ginny Caughey, MVP, 30 August 2004#
Can I deploy a .NET Compact Framework 2.0 application to a Pocket PC 2002?
No, .NET Compact Framework (CF) 2.0 supports Pocket PC 2003 and upwards only. For previous versions you should continue to develop with CF 1.0 and Visual Studio 2003.
For understanding which tools support which platforms and configurations, the Windows Mobile Development Tool Support Matrix on the Windows Mobile Team Blog should make things a little clearer.
Peter Foot, MVP, Windows Embedded, 30 September 2004#
When should I use GC.Collect?
Scott Holden of the .NET .NET Compact Framework Team has an extensive post on his blog titled The perils of GC.Collect (or when to use GC.Collect), including links to some other team members' articles, and notes on improvements to garbage collection in .NET Compact Framework 2.0.
Can I use MSMQ on a Pocket PC and in the emulator as well?
I have a MSMQ sample application that was originally developed on Windows 2000/2003 and then ported to Pocket PC 2003. I was able so successfully build it and load it into the Pocket PC 2003 Emulator. But as soon as it tries to enumerate the queues I get an exception.
How can I set up MSMQ on the Pocket PC Emulator? Or how can I make the Pocket PC Emulator see my local machine and the MSMQ on my local machine?
Klaus Salchner, 29 August 2004
To use System.Messaging on emulator or real device, native MSMQ needs to be installed and configured first. Native MSMQ is not included in Visual Studio and needs to be installed separately. It comes with PPC 2003 SDK and located in \Support\msmq folder.
You have to copy MSMQ files to \windows folder on emulator or device, and configure MSMQ as described in Application Installation of MSMQ (Platform Builder for Microsoft Windows CE 5.0) in the MSDN Library. At that point you can use System.Messaging.
Ilya Tumanov, Microsoft, 30 August 2004
MSMQ does work on the .NET Compact Framework 2.0. I have a series of blog posts that will help you, System.Messaging (MSMQ) in CF 2.0, Parts 1, 2, 3 and 4. I got this tested and working on a pre-Beta 1 build using the emulator.
Also note that to get more detail exception messages you will need to install the resource assembly. Please see What is the "Could not find resource assembly" error message? for more info on this.
Mark Ihimoyan, Microsoft, 7 September 2004#
Does the .NET Compact Framework 2.0 support asynchronous delegates?
I'm puzzled by the Beta 1 documentation statement that the .NET Compact Framework (CF) doesn't support asynchronous delegates. This can't still be true with CF 2.0, can it?
Peter Bernhardt, SharpSense Software LLC, 11 August 2004
At this time we do not plan on supporting general purpose asynchronous delegates in .NET CF 2.0. I believe only Windows Forms callbacks, BeginUpdate and EndUpdate, will be supported in this release.
Ori Amiga, Visual Studio for Devices, Microsoft, 11 August 2004#
Is there cryptography support in .NET Compact Framework 2.0? Where can I find some examples?
Yes cryptography is supported in .NET Compact Framework (CF) 2.0. The object model follows that of the full .NET Framework, so you should find plenty of examples.
Also Casey Chesnut has been working with cryptography on .NET CF for a long time and produced his own library for .NET CF 1.0 which has an object model that matches the System.Security.Cryptography namespace. Checkout Casey's articles for examples you can put to use with NET CF v2.0, see .NET Compact Framework and Rijndael / AES by Casey at DevBuzz.com.
Peter Foot, Windows Embedded MVP, 7 October 2004#
Is there BinaryFormatter support in .NET Compact Framework 2.0?
The documentation for the BinaryFormatter class in the Visual Studio 2005 Beta Library lists the .NET Compact Framework as a Supported Platform. Is that correct?
The prerelease documentation you're referring to is incorrect, there's no BinaryFormatter class in the .NET Compact Framework.
Ilya Tumanov, Microsoft, 29 October 2004#
Change in Form Finalize?
There seems to be different behavior in identical running code dependent on whether it is targeting the .NET Compact Framework (CF) 1.0 SP3 or current .NET CF 2.0 Beta bits. Simply create a new Form and override the Finalize method.
Insert two lines of code before calling the base finalizer
1. Debug.Writeline //works on CE devices
2. MessageBox.Show
Under CF 1.0 you will see both the console output and the Message Box just after closing the form. Under CF 2.0 there is no output. Does the finalizer not run anymore or am I missing something?
Daniel Moth, 31 July 2004
The reason why the Finalize method was called for forms in the .NET Compact Framework v1.0 is that the Form.Dispose method was never called when a form was being destroyed. That was a bug in v1.0 that could potentially result in memory leaks.
This bug has been fixed in the .NET Compact Framework v2.0. Now, whenever a form is being destroyed, the Dispose method of that form is called. The Dispose method, in its turn, calls the GC.SuppressFinalize method, which prevents automatic finalization (as a result, the Finalize is not called by the system). The .NET Framework on desktop has the same behavior.
Sergiy Kuryata, Microsoft, 6 August 2004#
Is DataNavigator in the .NET Compact Framework?
No, despite what the documentation states, DataNavigator (which is going to be renamed) support is not planned for .NET Compact Framework. The final documentation will reflect that.
Ilya Tumanov, Microsoft, 1 September 2004#
How do I create a WebBrowser that can be used with just a keyboard?
I'm writing an application where we'd like to interface a menu via HTML. I'm using the WebBrowser control. We do not have a mouse hooked up the device, so we need to be able to interface with it using the keyboard. Is there a way to have the WebBrowser control select different items within the HTML page when the keys are hit. Currently if I hit tab nothing happens.
Luke Jason, 15 July 2004
You need to make sure you set the TabStop to false for all other controls when WebBrowser control is in focus or else the Tab key will be handled by the Form and used to focus on other controls.
David So, Microsoft, 19 July 2004#
Can I get the WebBrowser.TextDocument property?
IntelliSense say that I can get and set the DocumentText property on a WebBrowser control. But when I try to do a get it will not compile.
Casey Chestnut, 30 July 2004
This is a bug in the IntelliSense documents. The Get accessor is not supported for the DocumentText property due to the behavior of the native WebBrowser control.
It may be possible to workaround this in native code. You might be able to do a Select All and send a WM_COPY message to the control and then read the clipboard. Pocket IE supports copying text to the clipboard so that should be supported.
Sergiy Kuryata, Microsoft; and Peter Foot, MVP, Windows Embedded, 9 August 2004#
How do I export a SQL Server database to a SQL Mobile database?
I'm working with SQL Server 2005 Beta 2 and VS 2005 Beta 1. How do I export an existing SQL Server 2000 database or SQL Server 2005 database to a SQL Mobile database on my desktop? And how would I do that same thing programmatically?
Helen Warn, 22 December 2004
This functionality is not available in Visual Studio 2005 Beta 1, sorry. You'll have to wait for Beta 2.
Ilya Tumanov, Microsoft, 4 January 2005#
Is COM interop supported yet?
I remember reading that the .NET Compact Framework (CF) 2.0 is going to support COM interoperability. Does anyone know how to take advantage of this using CF 2.0?
Luke Jason, 12 July 2004
Visual Studio 2005 Beta 1 does have a known issue where you cannot create the interop assembley (IA) directly from the IDE. That is, you can't quite drag-and-drop a component in the Solution Explorer and have the IA automatically created for you. Apart from that, COM interop should be working.
The workaround is to simply run TLBIMP manually at the command line, and then in your project use Add Reference in Visual Studio 2005 to add a reference to the resulting assembly.
One caveat, in Beta 1 you will not be able to do this for COM components which have a dependency on other DLLs.
Ori Amiga, Visual Studio for Devices, Microsoft, 15 July 2004#
Can I use the emulator in a Virtual PC (VPC)?
We expect the emulator to work inside VPC. However there are a few rough edges that were left in Beta 1.
In order for the emulator to establish communication with Visual Studio, it needs to obtain an IP address. It does so by sending a DHCP discover packet to the DHCP server and expecting DHCP offer packet back. If it doesn't receive an offer within certain amount of time, it repeats the DHCP discover packet. If all its discover packets go unanswered, the guest OS selects the DHCP not found address which is 169.x.x.x. If the host OS (in your case this is the OS running inside the VPC) also fails to contact DHCP server and ends up with 169.x.x.x address then communication with the emulator works.
Due to a security feature in the component used to multiplex the network adapter, an emulator running inside VPC never receives any packets sent to it from outside VPC. This means that if the host OS has a statically assigned IP or has obtained IP from the DHCP server, then the communication with the emulator will fail.
There is a pretty easy workaround, which involves installing a Loopback adapter inside the host OS. Here are the steps:
1. For each emulator image you'd like to use - Choose ConnectTo Option from the Tools menu and let it boot. (This step is a workaround for another limitation of the network adapter multiplexer a.k.a. Virtual Switch. It fails to provide the guest OS with a MAC address if it multiplexes a loopback or a bridge. However we cache the guest MAC address for reuse to prevent an overload of the DHCP server, so connecting over another network adapter initializes the cache.)
2. Install the Loopback adapter as described in How To Install Microsoft Loopback Adapter in Windows 2000.
3. Go to Tools | Options | Device Tools | Devices | Pocket PC 2003 SE Emulator | Properties | Emulator Options | Network and select Microsoft Loopback adapter in the drop down box for NE2000 Network Card.
All emulator scenarios should now work, however the emulator can not access the network resources (Virtual Switch Limitation).
Vladimir, Microsoft, 13 July 2004#
What does the "Could not find resource assembly" error message mean?
There Viewing Error Messages During Development (Smart Device Projects) in the MSDN Library.
Sandeep Prabhakar, .NET Compact Framework Team, Microsoft, 6 August 2004#
How do I create a CAB file?
In Visual Studio, select the File | New | Project menu item. Select the Other Project Types, select Setup and Deployment, then select Smart Device CAB Project.
You can now use the CAB visual editor to drag and drop files, create folders, shortcuts, registry entries, etc., similar to creating an MSI on the desktop.
Ori Amiga, Visual Studio for Devices, 23 August 2004#
Is the .NET Compact Framework supported in any of the Visual Studio 2005 Express Editions?
At this time, Smart Device development is not included in any of the Visual Studio Express versions: Visual Basic, C#, or C++.
Ori Amiga, Visual Studio for Devices, 20 August 2004#
Do SmartPhone projects still require the .NET Compact Framework 1.1?
I've just installed the latest drop of Whidbey 8.0.40607.16 (beta1.040607-1600) on a plain XP Pro VPC image.
I'm trying to create a smart phone project but the IDE can not find the necessary compilers and resources, as it keeps looking into ...\Framework\v1.1.4322\... and failing to compile the project. I also seem to have v1.0.3705 and v1.1.4322 directories but I do not have the runtimes in those locations (as expected given I've only installed v2 with the IDE).
My understanding is that the current editions of SmartPhones only support .NET Compact Framework (CF) 1.0, including the IDE emulator. I know you can compile against the older CF 1.0 assemblies but given that I've just installed the latest drop I thought the current compilers would be configured to compile against the older CF 1.0 assemblies (if they were shipped with the Whidbey IDE). Do I need to install the v1.1.4322 SDK or is there a workaround for Smartphone projects?
Peter Stanski, 20 July 2004
Yes, you do need to install the redistributable for v1.1.4322 (.NET Framework 1.1). The reason for this is that Smartphone project current only supports .NET Compact Framework 1.0 SP1 in Whidbey, and you will need to have .NET 1.1 compiler to compile the project. This is addressed in the readme file.
David So, 21 July 2004# | http://msdn.microsoft.com/en-us/netframework/aa497277.aspx | crawl-002 | refinedweb | 3,459 | 68.87 |
Tkinter, being the large and expansive GUI library that it is, offers us a wide range of widgets to take input in Python. One of these many widgets is the Tkinter Text Widget, which can be used to take multiline input. It also has a ton of amazing features that allow us to create complex GUI applications such as Notepad’s and Syntax Highlighters.
Another very popular alternative is the Tkinter Entry widget, used to take single line input. For most cases, it will be your preferred choice of input.
Creating the Text Widget
We’ve added in some extra parameters such as Height and Width for a custom size. We have also passed in
expand = True and
fill = tk.BOTH parameters into the frame and text widget, so that if we resize the window the size of the Text widget will expand in “both” the X and Y direction to adjust accordingly.
import tkinter as tk class Window: def __init__(self, master): self.master = master self.frame = tk.Frame(self.master) self.frame.pack(expand = True, fill = tk.BOTH) self.label = tk.Label(self.frame, text = "My NotePad") self.label.pack() self.text = tk.Text(self.frame, undo = True, height = 20, width = 70) self.text.pack(expand = True, fill = tk.BOTH) root = tk.Tk() window = Window(root) root.mainloop()
Below is the output of the above code:
Indexes
The first thing you need to do, is to understand the indexing system in the Text widget.
"1.0" for instance, refers to “Line 1” and “character 1”. So character 1 on line 1. (And yes, remember that indexing starts from zero, but that only applies on the characters, not the lines). Similarly,
"3.7" refers to Line 3, character 8.
There are a bunch of other words we can use, like
"end" which means the last character in the Text widget. There is also
linestart and
lineend, which give us the first and last character respectively of a line.
"2.4 linestart" will return the index of the first character on line 2.
Insert Text
Using the
insert() method on the text widget we created, allows us to directly insert text at a specified index. It takes two parameters, an index and the data to be inserted.
self.text.insert("1.0", "This is some Sample Data \nThis is Line 2 of the Sample Data")
As you can see in the code above, and the image below, you can add newline characters to ensure proper formatting as well.
Here is another example of inserting some data. This code will add the text to the end of the Text widget.
self.text.insert("end", "\nThis is some Sample Data \nThis is Line 2 of the Sample Data")
Retrieve Text
Since we can insert text into widgets, it makes sense for us to be able to retrieve them as well. Using the get() function, we can retrieve text by specifying a starting index and a ending index. All the data between those two points will be returned.
self.text.get("1.0", "end - 1 chars")
The code above returns all the text in the tkinter widget, except for the last newline character. Since the last character in the text widget is a newline character, doing
end - 1 chars will give us the position of the character before the newline character. (You don’t have to do this, I just wanted to demonstrate this capability)
self.text.get("1.0", "end - 1 lines")
Similarly, the above code returns all of the text in the text widget, with the exception of the last line.
self.text.get("1.0", "1.0 lineend")
The above code returns the first line of text in the text widget.
self.text.get("1.0", "1.0 + 3 lines")
The above code returns the first 3 lines of code in the text widget.
Delete Text
If you’ve been paying attention, you’ll realize immediately that the below code uses the
delete() function to remove all the text in the text widget.
self.text.delete("1.0", "end")
Here is another interesting way of using indexes in Text widget. Imagine that you have the index of the first character of a word, and you want to delete the whole word. Now, you don’t know the full size of the word, and thus can’t specify the end range.
This is where the
wordstart and
wordend features comes in. Just like
end, it will automatically find the start and end of the word.
self.text.delete("1.3 wordstart", "1.3 wordend")
The above code will delete the whole word, situated at the index 1.3 (line 1, character 3).
Adding Images
With a combination of the Tkinter PhotoImage and
image_create() functions, we can load, create and insert an image into the Tkinter Text widget.
self.img = tk.PhotoImage( file = "crown.png") self.text.image_create("end", image = self.img)
In the code above, we load up the
"crown.png", and insert it at the end of the text widget.
self.img = tk.PhotoImage( file = "crown.png") self.text.image_create(tk.INSERT, image = self.img)
Here is another very interesting piece of code which uses the
tk.INSERT index. The unique thing about this is that it returns the index of the “Insert” cursor. (You can see it in the image below, near the top). Wherever this cursor of yours is, it will insert the image there.
Adding Scrolling
Another handy thing we can do is add a scrollbar to the Text widget. This is actually part of the Tkinter ScrollBar tutorial, but I decided to include this here too.
class Window: def __init__(self, master): self.master = master self.frame = tk.Frame(self.master) self.frame.pack(expand = True, fill = tk.BOTH) self.label = tk.Label(self.frame, text = "My NotePad") self.label.pack() # Creating ScrollBars self.scrolly = tk.Scrollbar(self.frame) self.scrolly.pack(side = tk.RIGHT, fill = tk.Y) self.scrollx = tk.Scrollbar(self.frame, orient = tk.HORIZONTAL) self.scrollx.pack(side = tk.BOTTOM, fill = tk.X) # Creating Text Widget self.text = tk.Text(self.frame, wrap = tk.NONE, undo = True, yscrollcommand = self.scrolly.set, xscrollcommand = self.scrollx.set) self.text.pack(expand = True, fill = tk.BOTH) # Config the Scrollbars self.scrolly.config(command = self.text.yview) self.scrollx.config(command = self.text.xview)
If you want an explanation for the above code, just refer to the Scrollbar tutorial, otherwise the output is shown below.
Video
Here, we have a short video series on the Tkinter Text Widget. It’s great if you want more depth and demonstration on the various options and code that we discussed in this tutorial. It’s also great for understanding how exactly we can use the Tkinter Text widget in real life applications.
Be sure to check out the last video, where we create an actual Syntax Highlighter using the Tkinter Text Widget.
List of Options
A complete list of options availible for the Tkinter Text Widget.
Text Methods
Being a larger than usual widget, the Tkinter Text has many functions that you can use on it.
Tag related methods
Tags are in important part of the Text Widget, and have their own sets of methods dedicated to them.
This marks the end of the Tkinter Text Widget Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below. | https://coderslegacy.com/python/tkinter-text-widget/ | CC-MAIN-2021-21 | refinedweb | 1,241 | 66.94 |
JS Party – Episode #152
Automate the pain away with DivOps
featuring Jonathan Creamer
What the what is DivOps?! That’s the question Jonathan Creamer is here to answer. In so doing, we cover the past, present, and future of frontend tooling.
Featuring
Sponsors
AWS Amplify – AWS Amplify is a suite of tools and services that enable developers to build full-stack serverless and cloud-based web and mobile apps using their framework and technology of choice. Amplify gives you easy access to hosting, authentication, managed GraphQL, serverless functions, APIs, machine learning, chatbots, and storage for files like images, videos, and pdfs. Learn more and get started for free at awsamplify.info/JSParty.
Notes & Links
Transcript
Click here to listen along while you enjoy the transcript. 🎧
Hello, everybody! We’re so excited to be back this week, episode #152. It’s my first time MC-ing, so if the show is horrible, you can just blame me.
It’s gonna be amazing.
Apologies in advance. But we’re really excited to have a very special guest here today… Jonathan Creamer is gonna be here with us, and we’ll get into his back-story in a little bit. On the panel with me today is Divya…
Hello, helloo…!
And Nick.
Hoy-hoy!
Hey-hey. And we’re so excited to have Divya here on a show that’s about DivOps… We’ll have to get all the bad puns out of the way now…
Div-yeah…!
Div-oh-yeah… [laughs]
There you go…
Yeah… Yeah, I think Jonathan came prepared for that one…
Very good, very good.
So Jonathan is here because we had a show with Ben Ilegbodu a few weeks ago, where we were talking about TypeScript… And Ben brought up this term called DivOps. We all leaned into that, we were like “DivOps?!” and he’s like “Yeah. You know, I have a friend, and he’s trying to make it a thing, and I’m trying to help him…” I’m like “Well, it’s a thing now…”
It’s a thing.
Yeah, so welcome, Jonathan. Can you tell us a little bit about yourself?
Yeah, thanks. So Ben and I worked at Eventbrite together; he actually brought me on to Eventbrite, which was really fun… So that’s how we’re friends. We used to see each other at conferences all the time, where we’d talk about DivOps things at the time, but we hadn’t quite coined that term… So yeah, the DivOps thing happened because inside of Eventbrite I’m on the frontend infrastructure team, and that’s kind of one of the more common terms you hear for describing a team that does the kind of work that we’ll talk about, what DivOps does… But Kyle Welch, my co-worker and now manager - we used to talk about this all the time.
[00:04:17.27] So I’m on frontend infrastructure, I’m technically a frontend developer. I’ve been writing code for ten years, a lot of backend stuff, C#, ColdFusion, then to Node and JavaScript. Tons of JavaScript. But frontend-wise, I actually don’t write that much frontend code anymore. I prefer TypeScript now to do that…
Yes…!
Yes, of course! But I don’t actually write much client-side facing frontend code anymore. I use frontend tools to build; tools that allow other frontend engineers to do their job… Because we’re a big React shop, so it’s complicated. There’s a lot of stuff that goes into building a web page today… And I know we’ll talk about it here in a minute, what led up to that.
So yeah, we were sitting there, talking, and we were like [unintelligible 00:05:06.21] So I sort of tweeted out, and asked the community; we got a couple different answers, and some people said frontend SRE, frontend ops, [unintelligible 00:05:18.09] The most popular one actually was frontend DevOps, and [unintelligible 00:05:22.18] And that still was like “Well, that’s fine… Frontend DevOps sort of makes sense…” But then actually what happened was this guy Enrique was the one – Enrique Staying on Twitter; he said “Frontend engineers who manage infra should be called <div>ops”, and he actually put the angle brackets in there… And I just latched on to that immediately, and I was like “Oh my god, that is AMAZING. DivOps.”
And the moment that that came up, I started going to some conferences… We went to this conference called Connect.Tech in Atlanta, and I started pitching the idea there, and everybody was like “Oh, this is amazing. Yeah, do something with it!”
So Kyle and I started this DivOps community on Slack, and I sort of blogged about it on my personal blog… And there is a divops.dev website; it’s terrible, because I’m not a frontend engineer…
Because you’re ops, right? I would expect nothing les…
I did an amazing GitHub Actions build pipeline though, to merge from master… So the CI is fantastic. But yeah, so DivOps to me is what goes in all this tooling that we have to write to get all the other folks that work on frontend stuff get their stuff to the internet, so people can see it. Nobody sees my stuff necessarily, but people see the stuff that I help get out there.
Yeah, you’re the pipeline.
Yeah, we build the pipeline. It’s WebPack, it’s Babel, it’s maybe looking into Parcel, it’s Docker, it’s CI, it’s Jenkins, it’s deploying things, it’s S3, it’s Kubernetes, it’s all that stuff. So it’s a whole lot. I could go on all day about it. But that’s in a nutshell how it came to be.
I’m just really happy you’re adding semantics to the least semantic HTML tag.
Yeah… [laughter]
I mean, I would expect nothing less, again, from the ops world… [laughs]
Sure, sure.
“HTML what…?” So Jonathan, that’s super-cool. If you think about it, this is definitely a job that wasn’t a thing ten years ago, or even five years ago perhaps… And so it’s interesting how much the tooling landscape and the mindshare required has shifted the job market and focus of developers. And for companies working at scale, with huge frontend teams, there’s typically a frontend infrastructure team, and typically a frontend platform team that’s supplying a bunch of components, and then folks working on builds and pipelines and all the DX (developer experience) workflows. So it’s really great to see Eventbrite has made that a thing as well.
[00:08:05.00] Yup. I feel like most people who are doing it now sort of fell backwards into it. We were all writing jQuery code eight years ago, and doing things like the revealing module pattern, and using IIFEs… And all of a sudden you’ve just got all these cool – you know, guys writing about JavaScript architecture back then, Nicholas Zakas, books on all that… And then Backbone came out, and that was like “Oh my god, Backbone is amazing! Now we’ve gotta build all this infrastructure around that; models, collections…”, and then Marionette… And then RequireJS. Then you had to learn not only how to stop concatenating files, and do all that… And we just started this natural evolution; it became more and more complicated… And a lot of us just sort of fell backwards into it, and I just was like “This is awesome. I just wanna do this.” I don’t really wanna write code as much that people see; I like building this [unintelligible 00:09:00.02] way better.” It’s just fun.
When I think back on all the things that led me here, it’s like – and funny enough, we’re actually still deprecating Backbone code here at Eventbrite, but that was really where I first started getting into having to figure out, like “We’ve got all these Backbone models…” I remember the dumbest thing – I remember in 2010 having this ginormous, long, 10,000-line Backbone application, because I didn’t know how to actually concatenate things at the time. I still have a Stack Overflow post from ten years ago, where I’m like “How do I take all these files and put them into one?” And I don’t even remember what the answer was at the time, but somebody turned me on to something way back then…
Probably Grunt, I guess…
It wasn’t. It was before Grunt. It was some Java thing that would compile… What was that? I don’t remember; I’ll have to go back and look on Stack Overflow.
Wow…
But yeah, I had to build that pipeline to take a bunch of files and squish them into one; that’s where the revealing module pattern and all those early JavaScript patterns came in, so that you weren’t leaking into the global namespace, and all that.
And then when Grunt came out, obviously, that was the game-changer. Suddenly, we were like “Oh wow, now I have an official way of doing this whole thing. I’m gonna take now all these RequireJS modules and trace the dependencies, run r.js, uglify things, build my CSS, Grunt all the things… Yeah, that was really one of the first times when I realized “This is becoming a thing.”
Yeah, it really is. Taking a step back into the history of these tools - Grunt was the first JavaScript task runner; it was created by Ben Alman, cowboy on GitHub, or on the internet in general. Ben is just a really brilliant engineer; I think he’s currently a principal engineer at Toast, I believe… But he worked at Bocoup for a number of years, which is a company that I worked at.
And the IIFE pattern is also something that Ben kind of invented and socialized throughout the community, so it’s interesting to see the history there…
So we had Grunt, and then we had Gulp… It’s interesting to see what the evolution was, because Grunt ran everything serially, and then Gulp was “better”, because it–
Streams…
Yeah, it streams, and lets you do more concurrent–
And piping.
Piping, yeah. And then you could write in JavaScript; there wasn’t this weird other syntax that you needed to learn, and you could integrate… So it’s interesting to see how that evolution has come through…
Yeah, definitely.
…all the way to React, where I think that was one of the first, if not – yeah, I think it was the first JavaScript library that really couldn’t copy-paste into the web. You can’t just take that source code and – you can’t just take JSX and just copy-paste into the browser; a compiler is always required. That was a very big shift for the community, and one that I’m still personally – I think [unintelligible 00:12:12.17] still pending for me on whether it’s a good thing or not… But I don’t know, what do you think, Divya?
[00:12:20.26] What was the question? I totally missed what you said in the beginning.
Oh, you spaced out?
That’s okay, I forgive you.
[laughs]
The question was like… React - do you think the fact that React is a tool that you can’t even run in the browser… You can’t write React code without a compiler; so it’s not even–
Well, you could…
I was gonna say, you could… It’d be pretty gnarly though.
You could with CDN. You need access to the internet in order to [unintelligible 00:12:43.01]
You’d have to create element, and blah-blah… You’d have to write very weird code. You would write code that you would traditionally think of as React.
It would be gross.
I saw a comment about that on Twitter today; I won’t call the individual out, just because they probably don’t wanna be, but they were talking about that pattern of - instead of writing JSX, writing the function React.createElement() s actually like a Hyperscript function that takes in three arguments and does things with them… And they called out writing that for the past couple of years and really enjoying that, and thinking they made the best decision, versus just writing JSX directly.
Oh, wow.
Interesting.
Wow… Yeah, that is very interesting. That is, I would say, a person who is very patient. Maybe should consider a role in teaching…
Does not have a lot of nested components as well… [laughter] It’s just React.createElement(). [laughter] I understand the appeal of it; I would definitely rename it to something else, like H, but… I don’t know, at the end of the day it’s just faster… It’s easier to analyze code, for my eyes specifically… So I’m talking anecdotally, but it’s easier for me to just look at JSX and know what’s going on… Whereas I feel like I would be lost looking at Hyperscript calls over and over.
I think what led up to React, when I was at appendTo, building RequireJS and doing all these things - we sort of painted ourselves into a corner of needing build tools anyways for stuff… Even if you’re able to write JSX vanilla React in the browser, are you gonna – I mean, maybe now you could go vanilla CSS, too; it’s a little easier to write CSS now than ever before… But that wasn’t true until not that long ago. And we still have a lot of IE11 traffic, unfortunately. We’re finally on the cusp of turning that stuff off, but something has to run first to make your code be able to run everywhere, and it just sort of has to happen… So why not just also throw JSX compilation into the mix, too? It’s not even that slow, really; it’s just converting some ASTs [unintelligible 00:14:50.08] function call.
So yeah, to me it’s just kind of – build tools is just a part of it now, part of the job, like it or not, at some level.
Yeah, it’s like a necessary part of the job anyway, in order to write code that can be supported on multiple browsers, and performs well… I don’t personally see a world where we aren’t running build tools on our JavaScript code. I think the concern is more like – the local development workflows personally for me have greatly been impacted by this, and I think we’ll get into some of the tooling in the next segment…
I think there’s also a bunch of skills needed to have an entry point into modern web dev now… And that’s not very inclusive, because you’re asking people who are learning the language and learning the jargon to now learn ops, learn how to manage config files.
[00:15:56.17] Yeah. And that’s where this whole thing came up… Because it’s like “I don’t want my devs having to come in and learn all that stuff. I’ll take care of that for you. Put that on me. I love that stuff; I’ll do that all day. I’ll write you a WebPack config right now if you want one.” I love doing that stuff, I don’t know why. I geek out so hard on it.
I want the junior engineers coming out of wherever, or just starting – if you’re listening to this podcast and you’re like “I don’t know all this stuff…”, that’s okay. Come to me and let’s talk. I’ll help you get going, and then over time I can teach you more about this, and why it’s important, and how it works… But ultimately, definitely within the context of my company - I just want my feature teams to go make Eventbrite the best possible live events experience on the internet; and I don’t want you to have to worry about your WebPack config, and your Babel config, and your ES modules, and whatever. It’s like, I got you; that’s my job.
There’s something to be said about the increase in the number of zeroconfig type tooling. For example - sure, 10-20 years ago writing frontend code was fairly straightforward. You’d write a single file, maybe a CSS file, and then later on you’d throw in JavaScript, or whatever… You don’t need tooling for that. And then obviously, it’s become more complex, where you have WebPack, and earlier there was Grunt and Gulp, and so on…
But in the advent of tooling, at least at the beginning stages, there was not a lot of boilerplate code that you could just use and run with. You’d still have to write your own Grunt, you’d still have to run your own Gulp, and WebPack, and so on. But I think – and this is sort of me endorsing frameworks to an extent, because I think frameworks have actually helped… There’s an argument both sides, but I think in terms of Create React App let’s say, it has given people the ability to just run Create React App, it creates a boilerplate for you, and then you can just run with it.
Obviously, there’s an overhead in terms of learning JSX, and whatever, but that tends to come with frameworks. I mean, it’s sort a trade-off - would you rather learn JS, or would you rather understand who to write a WebPack config? And for a lot of people, JSX is very similar to HTML. Not the same, obviously, but it is a path to working faster than it is to understand all the config. And I think that’s actually really interesting, in terms of how the industry has moved towards…
I think that’s a positive, because it means that people don’t have to learn a lot of this… And if they want to, they can, because at least with Create React App you are working off of that boilerplate, and then if you really want to, you can extend the config. And if you wanna go one level further, you can just eject completely, which is obviously not recommended, because you don’t get further updates. But if you have very specific needs, you can do that. And that obviously means that you’re full on in the deep end, which is like what you do, Jonathan, which is completely updating WebPack, understanding every intricacy of that process. So I think there’s a wide spectrum in terms of the way in which you can enter frontend today.
Yeah. And what’s interesting about that, too - you’re right, frameworks, that’s part of why Next.js and Gatsby are so good and so popular; it’s like, you don’t have to worry about that stuff. But I think a lot of what’s interesting is that companies like Eventbrite and like Google or whoever, people that have been around for a minute - we’ve had to go through transformations… We started with Backbone and Marionette; actually, before that it was, like I said, IIFEs… To Backbone, to Require, then to React, and shoving React inside Backbone, and then now taking React out and only doing React… It was sort of hard to find a breaking point, to just say “Hey, we’re switching to Angular here, and Angular can do everything.” We picked up React, because we saw React was happening… And really back then, four years ago, when Eventbrite switched to React, there wasn’t a good React framework back then. Create React App wasn’t a thing, and Next.js definitely wasn’t a thing; maybe it was…
[00:19:56.22] So I think from that perspective we sort of just all had to find the ways to take what we had done and build our own little frameworks around them, and that’s where teams like [unintelligible 00:20:07.04] taking us into the future, taking the company into the future with React.
Cool. Just to kind of close up this section, I had one more question… Where would you delineate the difference between DevOps and DivOps? Is it strictly JavaScript tooling is DivOps, and then everything else might be DevOps? Repo management can be something that a team takes advantage of, for example. Which side would that be on? And what are your thoughts on YAML?
[laughs] Well, we’re switching–
Shots fired…
Yeah, we’re switching to CircleCI right now, so we do a lot of YAML.
Nice.
So I would say that it’s a very blurry line. The ideal line, and this is one that I had at LonelyPlanet, where I came from before Eventbrite, which is really great… We partnered with our DevOps team to have them help us create some infrastructure patterns and paradigms to where they sort of did for us what I’m doing for my engineering customers from frontends. They would create – you know, if you copy this Jenkins file, there’s a couple macros in here that will build your stuff… And then just took this Kubernetes manifest…
So that sort of give and take between DevOps and then my world – it’s like, I understand the DevOps flows and how to create my own infrastructure when I need to; I don’t necessarily need to get into networking VPCs, and routing HTTP traffic. I can, and I like to understand that stuff, but that partnership with DevOps or SRE is, I think, the ideal place where we can create an API, like anything else. And same thing I’m talking about with this tooling stuff. It’s like, “How do I work with the DevOps team? What levels, what touchpoints do we have?” and sort of building that understanding between the two.
That’s super-cool, Jonathan. I think what’s really interesting for me is this convergence of these two worlds that in previous lives never talked to each other. You have opsy, infra, cloud, CI folk, and you have folks who are writing JavaScript that are maybe at the tip of the spear… It’s this really nice full circle with DivOps, so thank you so much for talking to us about this cool topic. We’ll get into tooling and all the other fun stuff you kids can’t wait for next.
Jonathan…
That was a really cool insight into DivOps. And with Divya mentioning this separation of concerns, where Create React App has been create to abstract away all of the complexity around managing your configs, and lets you focus on just learning the tool… It’s really nice that the community at large is starting to take that. We’ve seen even just with WebPack 4, many years ago there was – I think they introduced the zeroconfigs there, as well.
[00:24:17.25] I’ve been around long enough to remember Karma was a tool that was super-widely adopted, and is still widely adopted today because of the way legacy stuff works… But I was the one person that had to set up all the configs for all my teams, because no one ever really got it. Docs were pretty poor… We’ve come a long, long way in terms of tooling, defaults etc. But can you give us an overview of what you consider to be really the best in class tooling landscape for frontend teams in 2020? If I was starting a project today, what would I need, and how should we go about setting it up?
Yeah. So what’s interesting is WebPack 5 just came out a few days ago, and it introduced a lot of things. You brought up WebPack 4 kind of converting into the – you basically [unintelligible 00:25:09.01] wepback -p or webpack -d and it just sort of has the same defaults, which is great. So from that perspective - yeah, you’ve got a lot of options now. Parcel is another big one; I think that was sort of the whole mantra behind Parcel, noconfig. At least at first. I know then Kyle came in and kind of added a little bit of config, because there were some needs there… Parcel 2 is gonna be even more incredible in terms of what they’re looking to do with Parcel 2. So I think Parcel is big…
I know eventually for teams that cannot support legacy stuff, Snowpack sounds pretty dang cool. I think IE11 is still a crutch there; or at least it was the last time I checked. I don’t remember. But yeah, so there’s a lot of great things out there still, and coming out, new things.
Babel, obviously, has gotten so good now that it can even transpile TypeScript, generally. You guys talked a little bit about that last week with Ben… Because the TypeScript compile is really good, but it’s like, it doesn’t match sometimes with what – I’m already doing all this sort of stuff in Babel, so the fact that I can now do TypeScript is fantastic.
And then in terms of other tooling that they were using at Eventbrite that I would say is pretty useful industry-wide and pretty good standards is - we have a big monorepo actually of our frontend code, which… Say what you want about monorepos; there’s definitely contentiousness about monorepos versus multi-repos, but for us, what we have chosen to do with our tooling stack, and all this DivOps stuff, is - we’re using a tool called Bolt, which is very similar to Lerna, built by the same guy, Jamie… And we’re able to… Basically, we have about 150 different frontend packages, and we can go in and say – our design system is in there, our tiny little packages that control widgets on the page are in there… And then entire applications are in there.
We have tools built that can detect – you know, if I change the button in my component system, I can see the downstream effects across my entire repo… Which is actually really hard in a multi-repo setup, unless you’re gonna write some crazy tooling to go about all these different repositories.
If I change the button, I get a list of every app in every package downstream that it touches, that the button is affecting. So I can run my Jest tests against everything downstream to make sure I haven’t broken everything. Same for WebPack. Now if I change the button, I can go run the WebPack builds of all the apps that use the button…
[00:27:52.13] And the opposite is true - if I’m only touching one small widget used by 2-3 different applications, then the blast radius is a lot smaller. So you get some better CI wins for that, because most of your builds are pretty smooth and pretty quick, because most of the teams are focused on what they’re focused on…
But then, when we have teams that come in and want to make repo-wide sweeping changes, we’ve built that in to be able to confidently say “I can change this card display widget and make sure that everything else alongside it gets tested”, which is really cool and super-fun. It took us a minute to get right, but it’s been really fun. And that’s the kind of tooling that – I just love building that stuff. I just love seeing how that affects people’s day-to-day, and the excitement that people get when we ship an update to it that makes it even better, and they’re like “Oh, this is so great!”
So yeah, the monorepo thing has been big… And I think industry-wide, that’s another tool that we’ve seen grow in popularity because of Lerna; Bolt was kind of a next step for that, that we’re using… Nx is another big, popular monorepo tool; there’s a couple of different ones out there, but I think the monorepo for frontends is pretty big.
Yeah, Microsoft has released Rush recently…
Yup, Rush.
It looks pretty good, actually, and I think they’re using it internally inside Microsoft, which is awesome, because that means you’re getting good support…
And Google has Bazel, which is their thing for it… A lot of the big companies have monorepos. But does a startup just shipping code need one of those? Probably not… But for a team of 150 engineers, it’s pretty nice to have the tooling of your monorepo to help shape it all and make it all make sense… So yeah, I’d say if you’re a big company and you’re having trouble keeping everything in sync, the monorepo is a good pattern, I would say, for modern build tools. it’s very helpful. It adds some shape and clarity around making changes; and confidence. So I really like that strategy a lot.
What else, industry-wide, tooling-wise…?
While you’re thinking, I can clarify something for folks. We’ll get into Snowpack in a bit, but… Snowpack does have – I guess we can get into it now. Snowpack has interoperability with WebPack, so that you can use Snowpack for – it’s really geared towards your local development… And because you need to support older browsers that maybe don’t have VSM, and whatever else; you can actually just literally use – you just plug in your WebPack… They have a plugin essentially for production; you just use WebPack to build your production bundles.
So for folks who are wondering, “What is Snowpack?” - well, we had Fred on the show a little while ago; I don’t’ remember what episode number, but we’ll link it in the show notes… But Snowpack essentially is this awesome bundler that lets you – it’s ESM-first, so you don’t need to bundle your JavaScript… So it’s using native modules, and it drastically improves your local developer workflow, because you’re able to build things file-by-file, and your spans and not gonna spin when you’re doing a watch, and having to constantly update your whole bundle, update your whole bundle, update your whole bundle…
So Snowpack is really great; a lot of frontend teams are starting to adopt it. We’re also considering adopting it for my team, and teams at large at my company… So Id’ highly recommend looking into it, just at minimum for local development workflow; it’s a game-changer.
[00:32:01.05] Yeah, I’ve definitely seen stuff about that. It’s one of the ones that’s like “Man, I need to look at that.” I’ve got it in my ever-long to-do list of articles and things I need to learn about.
Right. I’m gonna throw Nick a bone here, because I’m gonna talk about TypeScript… But how do you – there’s configs around linting, and there’s this kind of suite of tools that are what I like to call in the same cluster; they’re things that have a lot of peer dependencies… Whether it’s a Babel preset that requires these versions of Babel core, or whether it’s a TypeScript linting rule… There’s all these clusters which really for me make upgrades extremely challenging. For example, when WebPack comes out with a major release, there’s a ton of tools built around WebPack, and have peer dependencies set. What are recommendations for how to manage that?
Yeah, I love that question so much.
And TypeScript, because Nick. [laughs]
Yes, because Nick. So what we have enforced, which is a little different, and one of the things that Bolt does at its core - which, Bolt is one thing, it’s like a thing, but at its core what we wanted to enforce with our monorepo was there’s a consistent version of every package across the entire repo. You can’t have multiple versions of React in our world. We don’t support it; we don’t want it. We want everything to be consistent, so that way we can predict things better, and there’s not forking Node module folders, where one of the packages in my repo required React 16.9 and the next one required 16.12. That causes all these other downstream – it’s just crazy.
So literally, if you would ask for a Babel plugin at 6.17.1, that’s the only one that’s gonna exist in the repo at any moment, period. We don’t allow it; we’ll fail the build. You can’t do that. So we enforce that pretty strictly…
And in terms of that, going to the next build pattern or the new upgrade and dealing with those breaking changes… And even – we do a ton of migrating things; we’ve gone from WebPack 2, to 3, to 4, and how did that work; we’ve moved code around… We write a lot of Babel plugins for doing code mods, actually, which is really powerful, and fundamental to how Babel itself actually works. It’s this concept of an abstract syntax tree (AST), if you’re not familiar. ASTexplorer.com kind of describes it. It’s basically a way for you to write code, and that code can then get compiled down into a tree of like “This is a variable. This is a function etc” And then you can easily go in and replace a function call with something else, or whatever… Which is actually how Babel works under the covers, and why all of a sudden I didn’t have to use tsc to compile my TypeScript anymore, because Babel released their own AST parser for TypeScript… Which was super-handy, because now I can use babel/preset-env and babel/present-typescript, and babel/preset-commonJS to whatever, or dynamic imports… And you can kind of combine these Babel plugins into something that makes sense for what your team’s targeting. We’ve still gotta support IE11, at least for a minute; hopefully we’re gonna kill that, maybe in 2021, hopefully. We’ll see. And we wanna support private fields, or whatever. You can do all that kind of stuff, because under the covers you’re using these cool AST things.
So our team actually has written several different ASTs to help us convert from old things to new things, and do those upgrades, by going to – oh gosh, one of the biggest projects I worked on here at Eventbrite was actually taking us from [unintelligible 00:35:53.08] to 16. It was actually kind of hard; it took a while, because you’ve gotta make sure nobody’s using the wrong [unintelligible 00:36:00.01] thing anymore, then you’ve gotta go in and upgrade some of these different libraries… So we had to write some code that writes code, to help that upgrade path. So if you’re a team who manages a lot of code, like we do in frontend infrastructure, I cannot stress the importance and the usefulness of doing something like ASTs.
[00:36:22.07] It even helps because ESLint actually is also using ASTs, too. You can write ESLint plugins to verify if there’s certain patterns at your company that you want to enforce, you can write ESLint plugins to have enforce that kind of stuff. There’s all kinds of cool stuff that you can do.
Yeah, automation for the win. I think you’re preaching to the choir. In this group we all love ASTs… [laughs] And generally, using automation as much as possible, for sure.
I think automation is the key there. So the question was “How do you manage upgrading things?” It’s automation and verification.
And repeatability, I guess, is the best thing with ASTs, because you can just run it on your whole codebase; if you get something wrong, just git checkout, update your transform, run it on your whole codebase again…
Yeah. And it’s funny… I didn’t use to feel this way. I used to get really nervous, but I do like 9,000-file-long commits all the time now. It’s like “Eh, whatever.” It’s no big deal anymore. [unintelligible 00:37:22.29] Because I have that confidence now that I’m not gonna screw anything up. And it’s not just like finding and replacing, which - half the time I try to do that, I just break VS Code. I try to find and replace something across every file in our repo and it took 30 minutes for VS Code to do it. And it took an AST that I ended up running like 30 seconds to just scan the entire repo and change it. BRRRP, done!
Safe updates, right? ASTs are amazing for precision. One thing I wanna know for folks wondering why the Babel compiler is better for transpiling your TypeScript… We talked about this a little bit in Ben’s show, but we can get into it now. Basically, Babel has a lot – they’re essentially an implementer on the TC39. The same way V8 implements JavaScript, Babel is considered an implementation of JavaScript, because they actually make polyfills, and they do transpiling… And they also deal with managing bugs and idiosyncrasies between browsers, right? So there’s so much wealth there… Trying to replace Babel at this point is – you know, you have to catch up to all the bug fixes… There’s so much that they’re handling, it’s a good separation of concerns to use Babel to transpile and TypeScript to type-check, and not TypeScript to compile. You just get a lot more benefits there… So I was really glad when the babel/types merged; that was great.
Yeah, I agree. That’s the workflow we also adopted.
Same.
TypeScript did a lot of really cool things around – if you just wanna use TypeScript and you just wanna ship something and you don’t care all that much, tsc is probably gonna be fine, especially with some of the composite project stuff that they have now, where it will only recompile the stuff you change. They have that built into TypeScript now, in terms of making things faster [unintelligible 00:39:31.29] It’s pretty good. But yeah, as part of a larger ecosystem, we use tsc to type-check and dump d.ts files out to the filesystem that we can ship with our packages… Because that’s the one thing that Babel can’t do yet that I’m aware of, is generate the TypeScript definition files… Which is very useful, because if you are creating a package that you want those type definitions to be on for your autocomplete and your IDE, it’s important to do that tsc step to get those type definitions.
[00:40:07.01] And the funny thing is tsc is running in the background of VS Code anyways for you. That’s why VS Code rocks as hard as it does - it’s because whether or not you’re using TypeScript at your company… If you’re just like “I use JavaScript!” and then I’m like “Are you using VS Code?” and they’re like “Yeah”, I’m like “No, you’re actually using TypeScript.” Because whether or not you like it, it’s taking your JavaScript and running it through the TypeScript compiler, analyzing your code, and telling you “Hey, you misspelled this.” That’s TypeScript; that’s the power of their compiler…
Which is powered by ASTs.
Which is powered by ASTs, exactly.
Bringing it all back… [laughs]
Yeah, they have like a – if you ever just go look… I’ve just dug into TypeScript before, the compiler - it’s insane. God, it’s insane. And it’s a massively different way of looking at ASTs than Babel does, too. It’s literally just this huge, long file, the TypeScript compiler; it’s crazy. It’s fun though, I love it.
I have a question from a workflow standpoint. So when you’re setting up these tools, and maybe as somebody who works more directly on the frontend, but they have a change that they wanna make - maybe a config change, or a tooling change, or bringing in some new tooling… How does that work? Does it go to you as a ticket? I’m just curious about the delineation… I asked about DevOps and DivOps; now frontend and DivOps.
Yeah, sure. That’s a great question. We leverage the code owner’s file pretty heavily at Eventbrite. We on the frontend infrastructure team own everything that is not owned explicitly by a team. So we have certain teams that own the packages, whatever, this folder; or this folder, that folder. And then everything else falls through to us. But what that means is – we just had a guy from our [unintelligible 00:41:55.07] office come in and say “Hey, I’ve noticed that the Storybook Addons ticket that you guys have put into GitHub a while ago has a help wanted tag. Can I help?” I’m like, “Absolutely. That’s why I’ve put that label on it.”
I want to manage this stuff, I wanna own this stuff, but we want to treat our monorepo as like an open source project. We are the owners of it, but we want our teams who are interested in it, and have a bend towards the same mindset that I do as [unintelligible 00:42:23.05] Come and contribute, yeah. Absolutely.
My name is gonna get attached to the pull request as a code owner, and I’ll see it, and then yeah; just approve, merge me. We have a merge pipeline that we manage [unintelligible 00:42:38.26] and it sends it off to Jenkins and merges it in, and then there you go. And then that person gets to have contributed to the entire frontend ecosystem at Eventbrite.
So yeah, very encouraged. We definitely push hard on telling teams “Don’t just treat this as Jonathan, Kyle and Alex’s project. This is everyone’s thing. If you find areas where it sucks, tell us, and fix it with us, and work at it together.”
Wow… That’s so incredible. I also love that y’all are using the GitHub owner’s files, because I’m assuming – because you’re a monorepo, so you use the GitHub owner’s file to figure out who should be tagged on pull requests, and who should approve XYZ. That’s a little bit into DivOps a tiny bit, right
Yeah, definitely.
Do you guys lock down certain files, like your package.jsons? I’m curious who gets tagged on certain reviews always, from your team.
We have a – Jamie built a codeowners-enforcer package that actually helps with it, too. So if something goes into the repository that doesn’t get added to the codeowners file, the build fails. Every folder has to have an owner.
Every single folder?
Well, at least at the top level.
Top level, okay. I was gonna say…
Every package; not like down to source components or whatever, but the package at that level does.
Yeah, that’s amazing. Well, the DivOps, automating code ownership. This is super-cool.
[00:44:11.29] Yes, it’s all about automating.
Automate it all.
Kyle likes to say that he likes to automate the pain away.
That’s amazing. I think I need to give Kyle my phone number. [laughter]
What you described is actually very similar to what happens at the company I’m at. We have a team like that that works on also a monorepo. We’re using Lerna for that, but very much a monorepo to make sure we’re all on the same version of React, using the same version of TypeScript, things like that.
Some of the things that they do are kind of – I’d say like almost doing spikes to figure out the future of things, or maybe analyzing where things might go from an architectural standpoint across all of the projects that we’re doing. Is that something that you would also put into the role of DivOps traditionally?
Yeah, this is something that we’ve been trying to figure out even within our own team - how do we draw the lines between the systems sort of side of DivOps, and the actual architecture side of DivOps. I love both sides of that, so it’s actually very hard still in my own head; I like doing both, so I don’t know. I will say, functionally, yes, we do have a lot of input into the architecture that goes into the monorepo itself.
Not only are we trying to help make sure that the build tools and systems (putting everything together) work, we are also trying to help steer… You know, right now we have 95 different applications; they’re all using React, they’re all using Redux… Like, should we squish those into a few and maybe have Next.js orchestrate those things together? And should we use Redux Form anymore? We use Redux Form pretty heavily; should we switch to something else?
We’ve been having a lot of conversations in our frontend guild meetings about stopping using Redux Form as much in switching to hooks, because now we can use hooks. For a long time we couldn’t use hooks, because we were stuck on React 15.8, or whatever it was. So that side of my head [unintelligible 00:47:22.23] on its game a lot of the time too, because I get asked about those questions… And then I get asked to do mentoring. Because I’ve been doing this for ten years, and then I’m also mentoring folks on how application architecture should work, while also maintaining that stack…
So yeah, I think it does fit in. It’s a wide umbrella, this DivOps thing, which is part of why I like calling it out, and just that awareness of everything that I have to deal with… Just writing it down; it’s like, “Okay, those are the things”, and I can just visualize it all now, which is great.
Yeah, I really like the idea of a team dedicated to improving the productivity of everybody else on the team, because otherwise that stuff just kind of gets pushed to the side a lot, or it happens not as part of your regular assigned task, and it’s hard to get that assigned. So it’s really good that there’s somebody looking out for that, or a team looking out for the best interests of the development experience, while not taking away from the developers actually working on the user experience, and things like that. So it’s really beneficial from that standpoint.
Right. And what’s so interesting about what you’ve just said also - my team is doing all that we’re doing, and sometimes what we wanna do is to actually step away for a second and let the feature teams talk and discuss best practices that they’re seeing, and making sure that we’re facilitating communication across all the different frontend teams.
We’re dealing with frontend teams in Mendoza, Argentina, and frontend teams in Madrid, and frontend teams in San Francisco, and frontend teams in Nashville… So part of our role is also – we have these weekly guild meetings where everybody that’s really interested in frontend at large (not just infrastructure) comes together, we talk… And a lot of times it inadvertently becomes the frontend infra hour, which we don’t want it to be, because we want to hear from everyone using the stuff we’re using, so that we can help facilitate what is evolving as best practices inside of Eventbrite. And then also what we’re seeing in the industry, so we can kind of help shape those best practices for the teams, and maybe put in some new lint rules to help inform “This is not the right way to use hooks. Don’t do that.” So that way we get consistency.
People jump from team to team inside of Eventbrite, and we even want new hires to come in and see – not have to have a massive onboarding period of learning how frontend works at Eventbrite. No. We just want a standard access, so that anybody can come in, from any company, and just sort of get it. “Oh, okay. They’re using hooks. And here’s some Redux. The Redux is - whatever. But we get it. It makes sense.” So helping set up some fences around that architecture.
I love how customer-oriented you are, by the way…
[laughs] Thank you. That comes from my product manager, [unintelligible 00:50:14.08] He’s an incredible guy.
That’s awesome.
Throughout the course of my career I’ve been at the benefit of having a lot of good project and product managers, that helped me do that… So we constantly are focused – and inside of Eventbrite that’s one of our big mantras, trying to make the lives of our customers better… Whether that be on the feature team for the folks creating events, or in the case of our foundations teams, helping those engineers just live better lives, and have fun writing code. No one wants to wake up every morning – especially now we’re all at home, nobody wants to just wake up and hate the environment that you’re working in. We wanna make it better.
Yeah, that’s super-cool. I’m just impressed… The culture of good ops folks, traditional DevOps people - they’re extremely customer-oriented, and there’s this strong communication factor, because they’re typically the ones coordinating a bunch of teams that are very siloed, and you’re the common denominator…
Yeah.
So I just love that you’re advocating for that, and I think it’s just great for people to hear that y’all have that culture at Eventbrite, because it gives people hope. Siloing is a big problem the larger your company gets, and nobody has it perfect. If you look at Google, Google feels like 700 companies really, to the external person… Because it’s like “Wait, did they not know that messages exists already? Why are there seven other messaging platforms that seem to be cannibalizing each other.” But there’s just like… [laughs] Weird silos, you know?
The silo thing - boy, that rings so true to me. We had that problem where I came from at LonelyPlanet occasionally; we had folks in Australia–
It’s in the name. Just kidding. [laughs] Just kidding.
[00:52:07.14] Yeah, yeah. And when I got to Eventbrite, I was like “I don’t want that culture.” And especially now, everyone’s remote, everyone’s working from home… And I’ve been lucky also that I’ve done a lot of remote work, and when I was appendTo for years we were really good about staying in touch, and communicating… And yeah, we have folks seven hours ahead in Madrid. So I committed myself to waking up at 7 my time, and being online for 3-4 hours of crossover with that team, because I want to be able to help them solve their problems if they have it. Then I’m online for the last few hours of San Francisco’s day. I’m in a good timezone I guess too, luckily… Because then the Mendoza folks are an hour ahead.
So yeah, it’s facilitating that communication across teams, and making sure everybody’s on the same page…
One of the things I think people were afraid of when we started down this path was that we’re gonna force you to follow our standards, and just rule with this iron fist, like “This is how things are done!” But that’s quite the opposite of what we wanted. We want people to just feel like this is everybody’s thing, we’re working on all this together, we want input from anybody that wants to be involved, to help shape this. This is your work environment. We feel like we have the capability to stay in touch with industry best standards, and help keep moving us forward, so that way we’re trying not to have to maintain tons of legacy code, and maintainability, all that stuff. So yeah, no silos, please.
I think it’s interesting to think about, because it’s unique… The company that you’re at, you’re sort of split into – your focus is on tooling, and frontend tooling, and then the different teams that are probably more UI-focused, and building components, and whatever else…
But it’s interesting, because oftentimes when you think about the frontend tools that you use, it affects everyone. If you work on frontend, you’re gonna have to think about tooling at some point. But how do you make decisions? How much agency do teams have? Because you’ve mentioned you have a frontend guild, there are lots of people who get to chime in… But overall, how does the decision get made? Because you own the tooling in your team…
Sure.
…and then a specific frontend team that’s working on this particular component might be like “We need to use this particular tool to move forward.” But do they have the agency to do that, or is it something that they have to review with your team, and then your team approves, and then sort of moves to its implementation?
That’s an awesome question. We’ve had that happen quite a bit. One of the big efforts was a team really wanted to roll with some Cypress testing. It had been something on my radar for a good bit, and I hadn’t been able to experiment with it… And they just sort of showed up with some “Here, this is what we think would look good.” Then our team’s like “Cool!” And since we’re the owners of the stuff, we see all the PRs; we just talk with them, and we’re like “Yeah, this looks good. Approve. Go ahead and merge.” And then they help us maintain it.
Then standards-wise, we’ve actually recently started this practice of writing what we call ADRs (architecture decision records). There’s a couple of groups of Eventbrite right now meeting to come up with those. A salient example is like “Should it be __fixtures as a directory name?” And then we’ll write down some pros and cons of that, and have lots of people going in and read it, and approve it, and then we’ll all merge it together, so everybody’s sort of feeling good about that.
So we’ll write these ADRs about new ideas we have… That’s another good change agent for making sure people feel like they’re a part of shaping the thing, and it’s not just “Frontend infrastructure put this new thing in.”
[00:55:56.11] To the point earlier about being customer-centric, I think we’ve built up a lot of trust with folks… Because we do focus so much on the customers, and making sure everybody’s happy. In general, the frontend community trusts us to make the right call, which is huge. If we say “This is probably the right path”, we generally get good – and if there is an outlier that’s like “I don’t know, this doesn’t seem to make sense”, we just talk it out, and figure it out. It’s been really, really great, I feel.
I was just gonna ask if you have an RFC process, a few minutes ago…
Yeah, that’s it.
I was like “I wonder if you have that…”, because that’s the sanest way to do this, that’s democratic. It’s benevolent dictator, stressing on the benevolent part.
So yeah, that’s… Allowing for change.
So we have the ADR process… We also created some GitHub issue templates for folks that go in and create bugs or feature requests… We’ve got a feature request in for like “We need offline testing to try to speed up CI, because these integration tests take way too long.” It’s like, “Cool.” That combined with some stuff I had picked up from some conferences, and suddenly we’re doing this really cool Cypress testing thing where we’re doing user flow testing with scenarios… And that all sort of came from feedback that we got from the GitHub issue.
We use GitHub Projects to manage those issues that are coming in, and labels, and just letting people feel like they can contribute.
Yeah, that’s so wonderful.
This is why when I wish everything was open source, because I think people could really get insights into productive workflows at scale… It would be awesome.
That’s why I created this DivOps community…
That’s awesome.
…because I’m tired of like “You guys doing your thing over here…” And about silos again - we’ve siloed ourselves of different companies too, which is sort of unfortunate. I love when I get in – our DivOps, we’ve had a few meetings now… So Ben came to the DivOps group that we had a month ago and talked about what they’re doing at Stitch Fix. He pointed these specific things that I’m like “Oh, great. I’m doing that here, too.“I feel validated, like I’ve made the right choice.
So there’s that validation aspect of the community, too… Because sometimes it just feels like you’re just in this vacuum, like “I’m making stuff up as I go.” And then when you get a group of people that do the same thing together in the same room and you find out “Oh, they’re doing that, too? That’s awesome!” Or they’re doing that too, but slightly differently, and you’re like “Oh, I didn’t think about it from that angle.”
There’s a guy from the Shopify team in DivOps, and he was talking about their merge pipeline that they do, and I’m like “That’s awesome! We have a merge pipeline, too; it looks different from yours, but now you can help me sort of shape what it could look like at Eventbrite. I need some insights from other people, from different places. It’s all about diversity, and thoughts, and getting all kinds of different ideas.
Different inputs, yeah. That’s so cool. I didn’t realize that the community that you were starting was also kind of a mindshare between people for best practices…
It is.
…not just like a support group. Because I thought it was an emotional support group, quite frankly… [laughter] But that’s awesome. Consider me a new member, because I love nerding out about automation, and I use everything from Bash, to ASTs… I’ve been around the JavaScript world long enough to have just seen the patterns evolve… So it’s nice to have some of that grandma knowledge to bring to this group.
[00:59:47.18] I am curious though… One thing that does come up if you’ve been doing this for a while - you said you’ve been doing this for ten years, and Amal has been doing it for a really long time - one of the things, as someone who’s also been doing it for a while, going from Grunt, to Gulp, to WebPack, and now Snowpack… People talk about JavaScript fatigue a lot, which is this constant moving from tool to tool… Which also brings up the question which I think we touched on during the break a little bit, which is like “Are we adding complexity where complexity is not needed? And is there a way in which we can move forward where we’re not completely obliterating –” Because frontend infrastructure is gonna be a thing; people are gonna always wanna bundle, and transpile, and as long as that exists, this sort of work will exist. But is there a way and a path forward where we can make it streamlined?
I think it is a luxury to have a team dedicated to frontend infrastructure, and I don’t think that that’s something every team can do… So do you see a future in which this is easy for people to get into and deepen their knowledge, without having to know everything?
Right. I think it kind of comes back to – I heard this quote once when I was learning about all these different design patterns. Somebody said something like “Design patterns aren’t created, they’re discovered.” And I think that’s so true for this build stuff as well. Without us having gone crazy out there on these WebPack configs that are like 1,000 lines long, we wouldn’t have arrived on what that webpack -p mode does. We had to kind of go crazy for a little bit…
I sort of think we have reached a point at which the innovation has sort of leveled out a little bit. Snowpack is a more recent one, but… Finally, that JS fatigue – I remember going to conferences a couple years ago, and every talk was about JS fatigue. I’ve seen less of that now. I think we’re finally getting over that hump, to a certain extent, because people went off and innovated, and now we’ve sort of found those common denominators about what things need to be there… And now that’s why you’re seeing frameworks like Next, and Gatsby, and Create React App, and Create Next App, and all these things become more popular. And then maybe the evolution to that is – you know, we talked a little bit in the break again about where do we go in the future; maybe tools like Rust can come in and help speed things up, and who knows what’s gonna happen next.
Yeah, it’s interesting you brought that up, because we actually – especially with Babel, there are a lot of people talking about how Babel is complex, and sometimes it’s really slow, and there’s a lot of issues with it… And part of it is implementation, part of it is also just community, and how much time you can put into open source etc. But it’s interesting to see JavaScript tooling move in a direction that I just never thought that it would move into.
Now you see Rust coming into the fold, so you have things like SWC, that allows you to do TypeScript checking for you, which is way faster than Babel… Which I think, sort of almost to Nick’s question, moves into this completely – it sort of takes DevOps and DivOps and it’s almost like DivOps moves in that direction really quickly… Because as we see people moving towards picking other languages other than JavaScript to write tooling, then is that even frontend anymore? Because that’s almost full-on DevOps at that point.
Yeah, that’s a great call-out. And again, it just kind of comes back to the whole thing, like “What am I? What is my job description?” I’m a frontend infrastructure person not writing frontend at that point. But I think it’s just like picking a framework; some frameworks make sense for you, some don’t.
We did the pick-your-own-adventure game with React and Redux, and it kind of goes for tooling, too. If you’re hitting bottlenecks in your tooling – you’re probably not gonna be hitting bottlenecks in speed, just building some landing pages, marketing pages, little eCommerce sites; that’s probably not the problem. But a big company is like – we are where we’re dealing with 10,000 JavaScript files. If you’re hitting that performance bottleneck, something like Rust or Go might make sense. It’s a new thing to learn, but it’s gonna solve some of those performance bottlenecks. But it’s about picking and meeting the problem where it’s at, and not just creating problems that don’t exist yet.
[01:04:10.29] If you’re not dealing with 10,000, 50,000, 100,000 file-projects, Rust and Go probably don’t make sense yet. At least not yet. Maybe in a year or so there’ll be some more incredible Go and Rust tooling for frontend… We’re getting there though. But picking the tool that makes sense for you and your team where you’re at is what’s important, I think. Just like picking a framework.
Yeah. YAGNI never gets old. You ain’t gonna need it, but also don’t pre-optimize.
Right.
I personally think we really have a problem in our community that’s a side effect of being an engineer, I think. Everybody’s got this problem, but in varying degrees. Some people have it worse than others, but the need to kind of want to over-engineer…
One of my favorite talks from Kent C. Dodds is his a-ha thing where he’s like “Avoid hasty abstractions.” And it’s so true. Just don’t abstract until you need it. Don’t go crazy doing things until you find there’s a need. And doing small, little things is okay. Just iterate and add value as you go. You don’t have to boil the ocean at first.
Yeah. I honestly think code reviews have made that problem – I think people feel the need to have everything perfect on the first iteration… And I think you have to remind people that - first pass, second pass… There is a conflict with wanting to have the perfect PR, and wanting to deliver it in iterations; it’s difficult. I feel like the PR workflow doesn’t communicate well when something is the one. First pass. Versus final rubber stamp.
Exactly.
And it would be nice to be able to do some more iterative delivery and communicate that more clearly with people.
Definitely.
I just wanted to give you an opportunity to tell us about the logo that you have for DivOps, because it’s awesome.
Oh yes, yes. So I was sitting there doodling one day, and I drew the angle brackets and the hammer, and I was like “That kind of looks like Mjölnir, Thor’s hammer.” So I sketched something out that kind of looked like it. Also, when people ask me what I do that are not tech people, I tell them “Yeah, we’re kind of like a hammer builder. We build hammers for other people to build stuff.” That’s the easiest way I can describe to a non-tech person what I actually do in my job. So I saw the angle bracket, and the hammer, I saw the Mjölnir, and then my friend David Neal on Twitter - he’s a really great illustrator now, and also engineer. We’ve known each other for a really long time. So I threw it at him and he came back with that, and I was really excited about it. He’s awesome. If you don’t follow David, give him a follow, too. He’s great.
That’s awesome. We’ll try to link his profile. Thanks for calling out the logo thing, Nick, because I feel like logos are what make things official in JavaScript communities, you know?
Exactly.
Yeah, it’s true.
So… Not official until there’s a logo, and a website that ends in .dev or .io, because .com was taken.
And a Discord.
Yes, and a Discord. [laughter] And a Discorders Slack channel… Increasingly Discord more so than Slack.
Yup. So I’d love to continue conversations with whoever is interested in this stuff. You can search my name, I’m everywhere - Jonathan Creamer, @jcreamer898. And the DivOps community, like I said, I have a URL; it’s divops.dev. It’s gross. It’s just the most basic Gatsby thing ever… So if anybody wants to make it not gross, that’d be awesome.
[01:07:54.10] And then we’re doing the Slack community thing, and hanging out in there, just chatting about – somebody asked today some TypeScript questions, so I’ll probably go in there and answer some TypeScript questions. So yes, definitely feel free to join and chat online. This is what I’m passionate about.
Nice!
So I have a parting question before we end…
Okay.
How do we know that the Slack people are people in your channel, and not bots that have been created by all the DivOps folks?
[laughs] That’s a very good question.
How do we know? Do we know? Can we know, is the question, really… I see you typing already. Just kidding. [laughs]
Yeah, right, right… Most people that came in gave intros, and we said hey, and we meet every now and then to talk… But yeah, that’s a good question; they’re not sentient beings.
Well, thank you for answering my question in a serious way. I really appreciate that you took my question seriously. That’s awesome. [laughs] Thank you. So with that said, Jonathan, you are, I would say, gold for any team writing JavaScript. You and all of your teammates.
Thank you.
We need to clone you. I wish more companies had budget for this role, and this focus… it makes more sense at scale, but it’s a job that needs to be done for anyone that’s writing modern web applications. It just kind of sucks for smaller companies and smaller teams. Developers are just doing both jobs, and it’s nice to have the luxury of separating those concerns.
I think if you don’t, and you’re a company that doesn’t have that budget, it’s important to just sort of formalize it a little, at least yourselves. Just meet and talk, and write things down. That’s really the biggest thing. For the longest time everything was up here, in my head, just spinning around, and I didn’t put it on paper… [unintelligible 01:09:49.13] is massively important, not only for yourself. You can just offload your memory into a different place, and remember why you made decisions, and come back to them later, like “Oh God, why was it that I had to install this Babel Module Resolver plugin? I completely don’t remember.” And then you can go back and see “Oh yeah, this is why.” So write things down, talk, communicate… It comes back to communication; it’s key in all of this.
I also like that you formalize it in terms of just like a process… Because for so long, even for me, embarrassingly, when I work on tooling I think I’m not actually doing frontend. I’m just like “Oh, I’m doing a thing that will then allow me to do the work I need to do.” And so I’ll spend a week building a Rollup config, and I will be like “I was supposed to be building this, but I was building this…”
[laughs] Yak shaving.
…and felt like I actually didn’t do any work…
Yeah, I know.
Which is interesting, because if you think about it, that is sort of related.
It is.
And it’s not yak shaving, even though people think it is… To some extent it could be, but–
It’s important, yak shaving, though…
You might spend five hours messing around with the config, and then you’ve found one thing that was like “Oh, that was actually what I needed”, and you put it back, and that five hours of yak shaving exploration was actually massive important, because it simplified some part of your flow that maybe you didn’t know existed until you went and explored it… And now you’ve automated the pain away.
Yeah. I’m really glad that this tagline that I came up with is becoming–
It’s catching on.
Yeah. And I don’t even know - Nick, is it shared credit? I don’t know… All I know is that I should be on the bottom of whatever readme file, along with Nick and Divya. It was invented here. [laughs]
[unintelligible 01:11:33.29] Copyright.
Thank you.
We hope to have you back on the show again…
Yeah, anytime. I’d love to hang out.
Because it’s an evolving thing…
Yeah. Anytime you talk about WebPack, I’ll just show up and just hang out and listen and ask questions. Or build tooling.
Or build tooling, right. Well, we’ll link to everything that we talked about in the show notes, including the community, the blog post that kind of started it all, you’ll get to see the logo… We have so many links.
With that said, thanks everyone. We’ll see you next week!
Our transcripts are open source on GitHub. Improvements are welcome. 💚 | https://changelog.com/jsparty/152 | CC-MAIN-2021-21 | refinedweb | 12,365 | 76.05 |
Archived GeneralDiscussion.
Bewitched, bothered, and bewildered... -- Wed, 01 Oct 2003 03:47:58 -0700 reply
OK, I am havign a hard time getting it. Is there a manual? A book? I am hacking away on my Zwiki, but I have no clue about how to start a new page? How is it done? Can someone send help to dlp@psu.edu?
ZWIKI & Apache -- Wed, 01 Oct 2003 04:17:35 -0700 reply
I might sound like blasphemic - but is there a way to run ZWiki on a apache ?
ZWIKI & Apache --DeanG, Wed, 01 Oct 2003 07:04:00 -0700 reply
Yes, and not blashphemic, but it's a Zope issue more than Zwiki. See
clean site! and re: mailing list --laura trippi, Wed, 01 Oct 2003 13:03:04 -0700 reply
Hi, Simon and all,
Zwiki.org is looking great! Major reno and much appreciated (I'm trying not to be a Pollyanna here, can you tell?).
Quick note: the link from FrontPage on "mailing list" goes here:?
which doesn't mention anything about subscribing to the whole wiki mailing list. The WikiMail page says: "to learn how to use this site's mail features, see the FrontPage." I ended up going to my draft (not quite orphaned and badly named) WikiMailAtZwikiDotOrg to find the link to the all-wiki mailman list (to change my options).
Ah, I see that link lives on the subscribe form. Maybe edit FrontPage to read:
Most discussion happens on GeneralDiscussion. To monitor activity across the site, subscribe to the "whole wiki": list.
Since I'm not super active on the site, I'm never sure whether I should just throw a suggested onto a page and let Simon or someone edit it out if it's unwanted...?
thanks,
comment without content --DeanG, Wed, 01 Oct 2003 13:10:13 -0700 reply
Forgive my redundancy, but should comments without a subject and/or body be posted? Zwiki seem to get a few each week.
comment without content --DanMcmullen, Wed, 01 Oct 2003 15:27:19 -0700 reply
perhaps labelling the comment button "add this comment" would clarify things. (as well as doing nothing for empty comments.)
navigation tags --DeanGoodmanson, Thu, 02 Oct 2003 07:37:50 -0700 reply
Would the new navigation be well augmented with link tags?
Resources: ,
ZWiki hosting? --DanMcmullen, Thu, 02 Oct 2003 15:00:10 -0700 reply
hello all! i'm about ready to buy some web space somewhere that will let me install a customized ZWiki for a couple of prototype ecommunity sites i'm involved in. Zettai.net's "WebMaster" plan looks like it will do this, at $290/yr. () does anyone have any experience w/ them, good or bad? any other options worth considering? tia, dan
ZWiki hosting? --DeanG, Thu, 02 Oct 2003 15:23:22 -0700 reply
Did you, or your mail app add the escapes to the brackets on that URL? It caused the link to fail (easy correction, though.) Test 2:
ZWiki hosting? --DanMcmullen, Thu, 02 Oct 2003 15:57:54 -0700 reply
interesting. i did that manually in a web post. it's just a convention i use to disambiguate where URLs? begin/end. will avoid it in the future.
navigation tags --laura trippi, Fri, 03 Oct 2003 00:43:48 -0700 reply
Dean, do you mean the new nav links on the upper left?
Would the new navigation be well augmented with link tags?
You mean putting it in a div w/nice styles? I might not be getting this, but something to help the different links pop out would be good. They kind of blur together as they are.
I was giving a demo for a class last week and wanted to show them "RecentChanges?" at zwiki.org and couldn't find it. =}
I wasn't exactly focusing fully at the time but, still.
Hope that's not totally off topic.
navigation tags --DeanGoodmanson, Fri, 03 Oct 2003 09:06:35 -0700 reply
You mean putting it in a div w/nice styles?
Now that you mention it, that is a higher priority to me, but not what I was getting at. There are <link> tags that can get added for book-like sites that work with Mozilla & co. navigation bars. When I looked at it a year ago it was OK but we didn't have the next/previous stuff that is there now.
I agree that the top could use more word seperation. I like the text, though. I don't like MoinMoin's micro-toolbar of links.
Would you mind posting an example of how you might div up the header? It might help my momentum. :-}
stylin' ZWiki (was: navigation tags) --dan mcmullen, Sat, 04 Oct 2003 09:49:51 -0700 reply
navigation tag formatting seems to me to be part of a larger issue of how to make ZWiki more "stylesheet friendly" out of the ..., er, tarball as it were. rendering the nav tags in a div is an instance of this.
more generally, removing "hard coded" style specs embedded in particular elements of the page templates would help a lot. replacing them with functionally based class tags would be good. this might make it necessary to have a stylesheet by default.
another nice thing might be to refactor wikipage.pt as a collection metal macros for the various parts of the page. this could significantly simplify wikipage.pt, making customization easier.
this is an area i'm interested in & i'd be willing to help. also, might this be better discussed over in ZwikiOneReleaseDiscussion? seems it's part of the question of "what are the really necessary new features & fixes?" for after 0.23.
stylin' ZWiki --laura trippi, Sat, 04 Oct 2003 14:29:00 -0700 reply
On Saturday, October 4, 2003, at 09:53 AM, dan mcmullen wrote:
navigation tag formatting seems to me to be part of a larger issue of how to make ZWiki more "stylesheet friendly" out of the ..., er, tarball as it were.
Yes! Thanks for bringing that up, Dan. I agree it's best to tackle the nav tags w/in the context of the larger style sheet issue instead of piecemeal.
more generally, removing "hard coded" style specs embedded in particular elements of the page templates would help a lot. replacing them with functionally based class tags would be good. this might make it necessary to have a stylesheet by default.
Yes, and I think having a (simple, clear) zwiki style sheet by default is fine. By now, style sheets are, shall say, very much embedded in web coding practice. Unfortunately I can't help with this at the moment, and don't have a solid sense of how much effort would be involved.
Is there anyone else who can help? I'm swamped till the end of the semester....
another nice thing might be to refactor wikipage.pt as a collection metal macros for the various parts of the page. this could significantly simplify wikipage.pt, making customization easier.
Yes, otherwise, it's not really a ZPT so much as a DTML doc inside a page template? But since I have yet to grasp ZPT, and I'm no developer, I'm not really in a position to be lobbying for it. =}
this is an area i'm interested in & i'd be willing to help. also, might this be better discussed over in ZwikiOneReleaseDiscussion? seems it's part of the question of "what are the really necessary new features & fixes?" for after 0.23.
Makes sense to me but I'll leave that to Simon, Dean et al: What do you think?
hello, Zwiki 0.23rc4 released --SimonMichael, Sat, 04 Oct 2003 20:38:34 -0700 reply
I'm back from several wonderful days in the mountains. Meanwhile - excellent work, bug squad! No longer the restful trickle of issues I've been used to.. I'll need to adjust.. this is very good.
Laura it's good to hear you are finding the site cleaner. Your subscription clarification on FrontPage sounds good, please go ahead with that kind of thing, we'll refine it further if needed. I've tried to make FrontPage as simple as possible but it needs to explain things clearly.
Now, I've just chewed up a long saturday with great ease! :-/ More replies when bandwidth allows. Keep on the good work y'all.
Zwiki 0.23rc4 2003-10-04
- provide all the metadata recommended at in page brains. This may fix some problems.
- call setupCatalog automatically from the CMF install script, to simplify plone installation. This adds all the indexes and metadata that Zwiki expects from a catalog (see setupCatalog or for a list). NB these will apply for all catalogable plone objects, not just zwiki pages, but will (hopefully!) be empty/harmless for the non-pages.
- ensure pages() always returns brains with complete metadata, even when a partial catalog is present. This allows a number of things to keep working (at the cost of more zodb access), eg creating/renaming in a cmf/plone site where setupCatalog has not been called (IssueNo0623? and others)
- saving a page via ftp or webdav after removing the blank line between headers and text was giving an error. (Dan McMullen) This should fix the error (but may not do what's wanted..)
- convert more unit tests to ZopeTestCase?; make MockZWikiPage? a bit more useful
stylin' ZWiki --SimonMichael, Sat, 04 Oct 2003 21:10:45 -0700 reply
might this be better discussed over in ZwikiOneReleaseDiscussion?
Time for another "topic judgment".. (I guess we see these on mailing lists too, but less often.) That page mentions (via SimonsPlan2004) some general stylesheet things as part of the plan for 1.0. I would say that page is good for discussing what major things will/will not be in 1.0, and the timing of same. I would discuss specific stylesheet issues here (or on one of the more appropriate stylesheet pages, if it exists). Would anyone care to review and clean up the stylesheet pages ? I think the major ones are listed on WikiCleanup.
0.23rc5 released --SimonMichael, Sun, 05 Oct 2003 13:42:08 -0700 reply
Zwiki 0.23rc5 2003-10-05
- zwiki_plone: the experimental skin-based versions of DTML pages are now generated automatically and the tracker has been added (untested). These are: recentchanges, searchwiki, useroptions, issuetracker, filterissues.
- put the single-thread-per-page code behind a
fewer_threadsoption, disabled by default.
- first tests for CMF/Plone and page hierarchy; finally, a working test for rename(), in CMF/non-CMF; fix a bug in rename where children's parents field was not updated, leading to an error when you tried to view that child
Bewitched, bothered, and bewildered... --SimonMichael, Sun, 05 Oct 2003 13:54:13 -0700 reply
Did you find the FrontPage ? HelpPage ? FAQ ? When you went there did they help ?
I want to know if the docs are failing so we can make them better.
ZWiki hosting? --SimonMichael, Sun, 05 Oct 2003 14:04:05 -0700 reply
I haven't used Zettai but they look good. I also like Imeme, though I'm not so fond of freebsd - what OS does Zettai use ?
comment without content --SimonMichael, Sun, 05 Oct 2003 14:05:40 -0700 reply
We have seen a surpising number of junk comments lately haven't we. If changing the add a comment button, how about just "add comment" ? I agree we should ignore a comment with blank subject and body if we don't already.
navigation tags --SimonMichael, Sun, 05 Oct 2003 14:09:15 -0700 reply
wanted to show them "RecentChanges?" at zwiki.org and couldn't find it. =}
That's not good. :) I assume you're seeing it now though. It's on the FrontPage and (unless you're in minimal mode) at the top of every page - but it's just "changes" there now, I went with the CommonPlace-style links.
blog pearls, disorganized thoughts --SimonMichael, Sun, 05 Oct 2003 21:30:35 -0700 reply
I just did a little blog-surfing. Laura is writing such wonderful stuff - "[1]": "[2]?": "[3]?": "[4]?": . I'm feeling guilty for my techie ways!
Laura I hope we can clear up some of these wiki issues one of these days. Reading of your heroic efforts with the latest tech makes me think that sometimes we need to go simple, maybe drop a new tool or stay more on the beaten path with it for a few months till it improves. It's clear we need to pick our battles and conserve energy in this ongoing explosion of tech issues. This is not to discourage you, but give yourself credit - I've never heard of anyone integrating Movable Type and zope before. (Though I hear MT is excellent, from my point of view it's a dead end in this sense)
Having said that, anything that fixes the one-inch wide text column on your blog will a very good thing.
I can well see the potential for confusion with learning current wiki and plone mixed together - I would find that very confusing too. Each makes more sense, can be grasped more easily and is more mature when considered on it's own. If it were me I think I'd try and hide one or the other until students get the urge to explore their overlap. What's the Simplest Thing That Could Possibly Work ? What if you gave them a standard plone site and a standard wiki (outside of plone) side by side and let them figure out which works best for what and later, what integration might look like ?
Anyhow, thanks for your reports and insights, they make good reading. I'm sad to learn about Edward Said too.
blog pearls, disorganized thoughts --SimonMichael, Sun, 05 Oct 2003 21:53:29 -0700 reply
And when I say "we need to pick our battles" I don't mean "pitiful newbie, you are out of your depth again" :) I am, probably everyone else is, facing the very similar problems. The last two days I've been struggling to make ZopeTestCase?-based unit tests work with the testrunner script as advertised, as everyone claims it does, only to be mired in endless PYTHONPATH, SOFTWARE_HOME, rsync, import sequence problems with no success yet. I got lucky with a quick answer in the #perl channel this morning, but on the #zope channel they usually laugh at my feeble inquiries.. or at least that's what I imagine in the deafening silence. I did get a kind, serious attempt at solving the problem from janko (thanks!).. though futile.. and I got some sympathy while moaning about zope.org and old plone's horizontal-scrolling problems. I would say getting on IRC is a very good move, see you there.
More than one tracker or more attributes per issue ? --Hans Beck, Mon, 06 Oct 2003 05:50:12 -0700 reply
Hi,
Is it possible to have more than one Issue Tracker in a Zwiki, i.e. one for product A and one for product B ? Or if not, it is possible to add more attributes of issues (than category, serverity, status) by using ZMI ?
-- Hans
More than one tracker or more attributes per issue ? --DeanGoodmanson, Mon, 06 Oct 2003 09:38:16 -0700 reply
I'd suggest a SubWiki for more than one tracker.
More attributes via ZMI? That's a bit of a doozy. Adding a field isn't a simple operation, and doing it automatically sounds like a slippery slope. The biggest problem being presentation (text field, drop down, ??). If each of the custom fields were simply "text" (string, list, text,??), it might work by adding handling of *kw arguments to the add/edit/insert, but catalog and UI updating issues still present a big dilema, let alone security and ??? We can probably continue this at the ZwikiIssueTracker page.
PotentialPages? --DeanGoodmanson, Mon, 06 Oct 2003 12:33:46 -0700 reply
I've recently discovered canonical links. Anyone created a PotentialPages? page based on this? ( canonicalLinks - links )
This pages canonical links: ZWiki:GeneralDiscussion/canonicalLinks
0.23rc5 released --laura trippi, Mon, 06 Oct 2003 21:18:12 -0700 reply
Simon, I'm installing Zope/Plone/Zwiki on a new machine, using Plone 1.0.5: does this release fix some of the issues noted in your reply to Curtis:
I'm tempted to try it but this install is for my plone course site: what would you recommend?
thanks much,
PotentialPages? -- Mon, 06 Oct 2003 21:34:55 -0700 reply
Looks like canonicalLinks and links include all links, not just WikiNames, so a simple PotentialPages? is not possible.
More than one tracker or more attributes per
issue ? --Simon Michael, Tue, 07 Oct 2003 17:16:09 -0700 reply
Hi.. not with the current code, you'd have to extend/modify it. It's set up for one tracker per wiki at present.
0.23rc5 released --Simon Michael, Tue, 07 Oct 2003 17:18:43 -0700 reply
It fixes the issues with the catalog not being set up right, so all you should have to think about is enabling DTML (by renaming the no_dtml.dtml file) and granting the desired zwiki permissions.
0.23rc5 released --Simon Michael, Tue, 07 Oct 2003 17:20:52 -0700 reply
PS so what I'd recommend is (0. keep your Data.fs backed up, of course) 1. make a Products/old subdirectory 2. move Products/ZWiki to old 3. unpack the latest ZWiki in Products 4. restart zope and use it happily 5. but if for any reason you need to quickly revert, replace the one in old
Localization --Simon Michael, Tue, 07 Oct 2003 17:34:08 -0700 reply
I agree, we could/should/will do this.
Can't Edit Pages?? -- Wed, 08 Oct 2003 17:51:18 -0700 reply
I have installed ZWiki on a hosted site (Zettai are excellent by the way) and I am completely confused. The install seemed to go OK but none of the pages display the option to "edit". I am pretty sure that I have permissions set OK. When I "View" the page inside the Zope ZMI the edit option is displayed. When I view it normally it is not.
Any ideas?
comment without content -- Wed, 08 Oct 2003 18:36:17 -0700 reply
I think "add this comment" makes more sense than "add a comment" or "add comment". Also, the change required to the source for ignoring empty comments is pretty simple (below, but may not render quite right on this page) -- could it be done for the 0.23 release perhaps? It may not be the most elegant solution, but it definitely worked for me as a quick hack.
In ZWikiPage.py, replace the line in the "comment" procedure:
if subject != '[test]?' or self.getId() == 'TestPage':
with the following line:
if (text or subject) and (subject != '[test]?' or self.getId() ==
TestPage):
Option to disable mailout of page creations -- Wed, 08 Oct 2003 19:52:40 -0700 reply
Can this be added sometime?
Option to disable mailout of page creations --DeanG, Thu, 09 Oct 2003 06:55:44 -0700 reply
Are per-page mailout settings integrated yet? If that feature was there, you could work around your desire for no new notifications by only getting notifications on the pages you specify.
Bookmarks --DeanG, Thu, 09 Oct 2003 07:03:07 -0700 reply
I'm finding I miss bookmark functionality. Not that I want them back, but I want quick access to the list of pages I regularly visit/watch.
I'd prefer that my username be a wiki-linked somewhere on the page, so I can add said bookmarks to my personal page and get to it from there. This location may also server as an (additional) preferences link when no useroptions have been set.
PageType?: STX DTML HTML --DeanGoodmanson, Thu, 09 Oct 2003 07:51:12 -0700 reply
I'm running into a number of cases (code examples and narratives) where escaping wiki-linking is the majority of the page and cumbersome. I'm going to look into creating a new page type for this scenario that does NOT include wikilinks.
But...
- Is this technically reasonable or toying with the fundamentals.
- Are there caching/prerendering issues to watch out for?
UserOptions? oddity --DeanG, Thu, 09 Oct 2003 13:15:27 -0700 reply
UserOptions? only showed 1 item for me today.
http log question --PieterB, Fri, 10 Oct 2003 11:21:59 -0700 reply
On Fri, Oct 10, 2003 at 09:09:31AM -0700, DeanGoodmanson wrote:
I came across the following in my log file...would someone mind telling me what it is?:#.#.#.# - Anonymous (10/Oct/2003:10:49:05 -0500) "GET /p_/sp HTTP/1.1" 304 194 "" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Feedreader; .NET CLR 1.0.3705)"
In particular:GET /p_/sp HTTP/1.1" 304 194
-- forwarded from
I think it's got something to do with your RSS-feed because of the Feedreader user agent. The /p_/ and /misc_/ are used for serving Zope images (see )
BTW: why didn't your post show up at the GeneralDiscussion? I think it might be the bracket's in the logfile line, so I removed them.
http log question --DeanG, Fri, 10 Oct 2003 11:38:51 -0700 reply
Good to here from you, Pieter! You should crank up a blog again with PyDS and PyCS?. (although it's down today)
I chucked the post as I figured out what the object was. I'm very interested in a single-hit roll-back feature to clean up silly mistakes like that from the RecentChanges?, but OOPS! Mailing list. (Maybe a 5 minute validation before mailout ;-))
off to New Orleans --SimonMichael, Sat, 11 Oct 2003 09:10:42 -0700 reply
This has been a jam-packed week. Sorry for the delay in release - it'll be just the same as rc5. If you'll be at the plone conference, look for me there! I hope to be back online in a day or two.
ZWiki hosting? --Brian, Sat, 11 Oct 2003 14:55:29 -0700 reply
Zettai is great! I've been with them for over 6 months. George Donnelly is friendly, knows his stuff and email replies are always very quick with any issues that arise. His systems are kept very up to date but not at the expense of stability. Very pleased all around.
0.23 final released --SimonMichael, Sun, 12 Oct 2003 21:13:55 -0700 reply
and this one should be accessible on zope.org too.
I realized that it's been 4 years, not 5. Phew! More time. Also I think we have a way to go to make a good 1.0. SimonsPlan2004 may need to be pushed back.
#parents: -- Mon, 13 Oct 2003 06:21:41 -0700 reply
Not only contents/basic/* but also FilterIssues.stxdtml has #parents: tag.
setupCatalog -- Mon, 13 Oct 2003 08:39:49 -0700 reply
Zope-2.6 does not create Vocabulary automatically when adding ZCatalog(Zope-2.5 does). So I think it had better to create Vocabulary if it does not exists.
setupCatalog --Simon Michael, Mon, 13 Oct 2003 19:26:26 -0700 reply
How does this problem show up ? Do you get an error from setupCatalog ?
UserOptions? oddity --Simon Michael, Mon, 13 Oct 2003 19:27:03 -0700 reply
Looked ok to me. Working now ?
Re: can't comment via email? --Simon Michael, Mon, 13 Oct 2003 19:28:49 -0700 reply
dan mcmullen wrote:
i've tried unsuccessfully a couple of times to post to GeneralDiscussion via email. thought it might be because i subscribed as "bang+zwiki@" but send mail just as "bang@", but after changing the subscription i
Yes that would do it. As long as you are subscribed (somewhere) with the address you send from, this should work. Any luck ?
setupCatalog -- Mon, 13 Oct 2003 22:02:23 -0700 reply
setupCatalog itself works well. Is there any problem when searching TextIndex? field ? I do'nt know the detail about the relation between Vocabulary and TextIndex?. Zope-2.6 seems to recommed Lexcon/ZCTextIndex? pair instead of Vocabulary/TextIndex?.
More than one tracker or more attributes per issue ? -- Tue, 14 Oct 2003 11:20:36 -0700 reply
By coincidence, I just had this weird idea I wanted to bounce off the crowd. I was thinking of doing some crude BillSeitz:SalesForceAutomation, and wanted a simple way to add new object types (those words used sloppily). Take a look at BillSeitz:WikiForCollaborationWare and do a Find for
SFA.
#parents: --SimonMichael, Tue, 14 Oct 2003 20:13:50 -0700 reply
Yes, setupPages uses this tag to set the initial page hierarchy. You should omit the #parents line if you are copying and pasting these pages manually.
PageType?: STX DTML HTML --SimonMichael, Tue, 14 Oct 2003 20:21:06 -0700 reply
Is this technically reasonable
Hi Dean - certainly. I think we had a non-wiki-linking type at one point but I judged it not important enough to keep. I think though it would be nice to be able to easily disable wiki features all the way down to a static web page workalike.
Re bookmarks - add personal page to the top link bar, then ? Could be good, but what to call it, if not.. My Wiki ? :-)
move contents link to the number 2 position ? --SimonMichael, Tue, 14 Oct 2003 21:08:03 -0700 reply
I want contents to be r
looks like we lost some
New Comments with 0.21 -- Thu, 23 Oct 2003 00:02:04 -0700 reply
The problem and rendered page can be found in: ArnoCommentProblem
BTW: We should really try to do the most unexpectable - write a manual to this :) I noticed the new Subtopic Rendering - is there a place where this is described ?
Re: Making AllPages work under Plone -- Thu, 23 Oct 2003 01:04:44 -0700 reply
CMF/Plone's catalog is called portal_catalog. AllPages should use the newer pages() instead, which will take care of finding the catalog and restricting the results to the current wiki. Try that.
Thanks a lot. That took me a step forward. The code is now working in my test environment. Unfortunately, it still doesn't work in my real environment. The test environment is a clone of my real one, they both use the same ZWiki CVS head, and I am not able to give account of the different behaviour.
The real environment raises an AttributeError? in this statement:
< dtml-call "REQUEST.set(pageList,REQUEST.get(pageList,[])+[x_sequence_item])">
- Can you help me once more?
- Andreas
Re: Making AllPages work under Plone --Simon Michael, Thu, 23 Oct 2003 07:28:20 -0700 reply
Andreas - I can't see the problem. Can you post a link, or more detail (the traceback in the ZopeLogs might give more clues).
manual --Simon Michael, Thu, 23 Oct 2003 07:40:51 -0700 reply
Arno - great, can you help ? Here are two key places: WikiCleanup - cleaning up our existing raw docs; ZWiki - a book-style outline in progress.
Re: Making AllPages work under Plone -- Thu, 23 Oct 2003 13:05:27 -0700 reply
Can you post a link, or more detail (the traceback in the ZopeLogs? might give more clues).
This is the traceback for the error::
Traceback (innermost last): Module ZPublisher.Publish, line 98, in publish Module ZPublisher.mapply, line 88, in mapply Module ZPublisher.Publish, line 39, in callobject Module Products.ZWiki.ZWikiPage, line 283, in __call__ Module Products.ZWiki.CMF, line 122, in __call__ Module Shared.DC.Scripts.Bindings, line 252, in __call_ Module Shared.DC.Scripts.Bindings, line 283, in _bindAndExec Module Products.CMFCore.FSPageTemplate, line 167, in _exec Module Products.PageTemplates.ZopePageTemplate, line 228, in _exec Module Products.CMFCore.FSPageTemplate, line 139, in pt_render Module Products.PageTemplates.PageTemplate, line 95, in pt_render --- Andreas
Module TAL.TALInterpreter, line 200, in __call__ Module TAL.TALInterpreter, line 244, in interpret Module TAL.TALInterpreter, line 703, in do_useMacro Module TAL.TALInterpreter, line 244, in interpret Module TAL.TALInterpreter, line 726, in do_defineSlot Module TAL.TALInterpreter, line 244, in interpret Module TAL.TALInterpreter, line 592, in do_insertStructure_tal Module Products.PageTemplates.TALES, line 217, in evaluate - Line 28, Column 4 - Expression: - Names: {'container': , 'default': , 'here': , 'loop': , 'modules': , 'nothing': None, 'options': {'REQUEST': , 'RESPONSE': ZServerHTTPResponse(''), 'args': ( ,)}, 'repeat': , 'request': , 'root': , 'template': , 'traverse_subpath': [], 'user': zopeadm} Module Products.PageTemplates.ZRPythonExpr, line 48, in __call__ - __traceback_info__: here.render(here,request) Module Python expression "here.render(here,request)", line 2, in f Module Products.ZWiki.ZWikiPage, line 298, in render Module Products.ZWiki.ZWikiPage, line 383, in render_msg_Let, line 76, in render Module DocumentTemplate.DT_Util, line 201, in eval - __traceback_info__: pageList Module , line 2, in f AttributeError: set
Re: Making AllPages work under Plone --Simon Michael, Thu, 23 Oct 2003 15:20:58 -0700 reply
REQUEST has no set attribute - usually means it's None (put a dtml-var REQUEST in there). This can happen when calling the page from within another and forgetting to pass the REQUEST argument.
Problem gettting started - attribute error --Simon Michael, Thu, 23 Oct 2003 15:22:52 -0700 reply
Yes, this is one of the issues fixed in CVS.
Problem gettting started - attribute error --Simon Michael, Thu, 23 Oct 2003 15:32:04 -0700 reply
In other words.. ah.. the problem is an invalid parents attribute, so visiting PAGE/reparent should fix things.
interesting --SimonMichael, Thu, 23 Oct 2003 20:04:26 -0700 reply
The Great Library of Amazonia
Re: Making AllPages work under Plone -- Fri, 24 Oct 2003 04:16:14 -0700 reply
REQUEST has no set attribute - usually means it's None (put a dtml-var REQUEST in there).
The dtml-var REQUEST results in an empty string, whereas my test environment dumps an object.
This can happen when calling the page from within another and forgetting to pass the REQUEST argument.
Okay, this may be beyond my skills. :-) What can be the cause for this? The rest of the ZWiki and other pages containing DTML-Code (for example RecentChanges?) are doing fine. I also had AllPages already running in my test environment. But when I copy my Data.fs from the real system into the test environment, the test environment raises the same error.
I also tried to start from scratch in the test environment:
- Delete Data.fs
- Create a Plone site
- Install the ZWiki in the Plone site (external method ZWiki.Install, install)
- Add a folder to the plone site for the ZWiki
- Create a new ZWiki outside of the Plone site and copy its contents to the Plone-ZWiki
- Call setupCatalog on the FrontPage
- Insert AllPages into the FrontPage, create the page and paste the code from zwiki.org into the page
The result is still the same: AllPages raises an AttributeError? (REQUEST is empty), whereas the code for RecentChanges? does fine.
-- Andreas
Re: Making AllPages work under Plone --DeanGoodmanson, Fri, 24 Oct 2003 07:09:23 -0700 reply
but when I copy my Data.fs from the real system into the test environment, the test environment raises the same error.
Catalog snafu? Does it still happen after clearing and re-finding your zwiki pages?
Re: Making AllPages work under Plone -- Fri, 24 Oct 2003 07:54:30 -0700 reply
Catalog snafu? Does it still happen after clearing and re-finding your zwiki pages?
If you are asking if it still happens after clearing the catalog and recreating it from scratch (/setupCatalog), then the answer is yes. In my example above, I even started with a fresh and empty Data.fs.
-- Andreas
Re: Making AllPages work under Plone --Simon Michael, Fri, 24 Oct 2003 08:16:43 -0700 reply
We're missing something. REQUEST should not be empty. Put dtml-var REQUEST by itself in AllPages and a couple of other pages. What do you get ? Do you have an object named REQUEST in the zodb ?
update --Simon Michael, Fri, 24 Oct 2003 17:51:59 -0700 reply
A massive round of product clearance and upgrades today. This server is now running CMF 1.4.1 and the latest plone 2.0 branch, along with all it's dependencies and a few more (ArcheTypes?, FileSystemSite?, SkinnedFolder...).
I've replaced with a plone 2 site but it's not yet operational (no sidebars for some reason, unlike). There was a bug in CVS preventing wiki page creation, fixed.
Dean and I decided on IRC last night to close off the ZMI from anonymous visitors (and google) - ie the full history button in the diff screens. That ZMI screen wasn't too useful since I pack frequently, and anonymous isn't able to restore from history anyway due to a zope bug.
Increased activity in #zwiki (and the other zope channels) lately. I hope to be more present on IRC for the next while.
excerpts in search results --Simon Michael, Fri, 24 Oct 2003 17:52:34 -0700 reply
Dean, I've installed that new feature that you suggested, thanks for the code. I took the liberty of renaming and simplifying it as much as I could - then wrote some tests and it all blew up again as I grappled with the details, when I should have been dreaming! Here's where I got to, for your interest:
def test_excerptAt(self): self.page.edit(text='This is a test of the<br>\n excerptAt method,') self.assertEquals(self.page.excerptAt('excerptat',size=10,highlight=0), '\n excerptAt ') #self.assertEquals(self.page.excerptAt('this*',size=21,highlight=1), # '<span class="hit">This</span> is a tes') #self.assertEquals(self.page.excerptAt('br',size=4), # 'e<<span class="hit">br</span>>\n') # XXX temp self.assertEquals(self.page.excerptAt('this*',size=21,highlight=1), '<span class="hit" style="background-color:yellow">This</span> is a tes') self.assertEquals(self.page.excerptAt('br',size=4), 'e<<span class="hit" style="background-color:yellow">br</span>>\n') self.assertEquals(self.page.excerptAt('<br>',size=4,highlight=0), 'e<br>\n') self.assertEquals(self.page.excerptAt('nomatch'),'') self.assertEquals(self.page.excerptAt(''),'') security.declareProtected(Permissions.View, 'excerptAt') def excerptAt(self, expr, size=100, highlight=1): """ Return an excerpt of this page at the first occurence of expr. Intended when presenting search results. Does a straight case-insensitive string search, after first removing any * wildcard character (this may not agree exactly with the catalog index's search). SGML tags are quoted. If no match is found or expr is blank, returns an empty string. When highlight is true, each match within the excerpt is enclosed in a span with class "hit". This is not 100% reliable because we don't handle wildcards and due to the html quoting. """ string = re.sub(r'\*','',expr) m = re.search(r'(?i)'+re.escape(string),self.text()) if m and string: middle = (m.start()+m.end())/2 exstart = max(middle-size/2-1,0) exend = min(middle+size/2+1,len(self.text())) excerpt = html_quote(self.text()[exstart:exend]) if highlight: excerpt = re.sub( r'(?i)'+re.escape(html_quote(string)), #'<span class="hit">%s</span>' % html_quote(m.group()), # XXX temp '<span class="hit" style="background-color:yellow">%s</span>' % html_quote(m.group()), excerpt) return excerpt else: return ''
visual editing --Simon Michael, Fri, 24 Oct 2003 17:52:40 -0700 reply
The latest Epoz and epoz (the NG version, alpha 1 released today) are installed. I made a serious attempt at epoz NG with help from guido_w but don't have it doing anything useful yet. SkinnedFolder and FileSystemSite? work very nicely to provide CMF-like skins, without the CMF - perfect for epoz & zwiki - but epoz expects file suffixes which they hide.
Did I mention the Epoz proof-of-concept ? Andrew Ho (of OIO fame) prodded me into it. You can see the present state by following the link on TestPage, and any coding help is welcome; the method is in UI.py, and needs to be templatized in some appropriate way.
As it happens, at the moment I'm feeling that we've reached the limits of standard STX (due to performance and consistency issues). STX has never been optimized and never will be. I don't think RST is the answer either. At the plone conference I tried to come up with a design for a new, outliner-ish parser/formatter that could support the most useful bits of STX and RST and zwiki linking integrated cleanly as a single whole rather than half a dozen systems grafted together, therefore faster and more consistent-feeling.
I think this could be good, but I'm not sure it's the best use of time, when rich cross-platform visual editors are finally arriving. Mostly we want to fix things on a page, and make beautiful documents with a minimum of fuss, expecting the tools to keep a clean semantic representation underneath. So I'm feeling quite friendly towards HTML and pseudo HTML[1] just at the moment..
[1] HTML plus a few carefully-chose convenience markups - blank lines create paragraphs, zwiki-style linking, STX emphasis, RST headings ? Or, STX with much simpler rules.
excerpts in search results -- Fri, 24 Oct 2003 18:32:40 -0700 reply
. I took the liberty of renaming and simplifying it as much as I could
Thanks! I look forward to working with it.
excerpts in search results -- Fri, 24 Oct 2003 19:14:07 -0700 reply
I took the wiki liberty of plopping it on the SearchPage?. Looks good! As each page requires the page to be woken up, large hits may eat up RAM. :-/ I think I disabled this on the blank search.
Changing reST report_level --Kent Tenney, Sat, 25 Oct 2003 02:58:58 -0700 reply
In my reST pages, I'm getting messages
"system message INFO/1 .."
I want to suppress these. In ZwikiPage?.py I've changed report_level to 2 the line;
t = reStructuredText.HTML(t,report_level=2)#doesn't hide em
but I still get the messages.
- TIA for any suggestions
- Kent
reST report_level problem resolved --Kent Tenney, Sat, 25 Oct 2003 09:12:38 -0700 reply
After correcting a different problem (section heading underline too short), the page started supressing the message as it should.
- I don't get it, but now it is working
- Kent
0.24rc1 released --simon, Sat, 25 Oct 2003 16:55:54 -0700 reply
You know the drill, download from FrontPage or CVSRepository, bug reports welcome. This should be less troublesome than 0.23. See NewHierarchyControls if you haven't already.
I've been thinking about various release process adjustments. At the moment I think the one-month release cycle is still best, but I'm going to try and be more disciplined: new features and high-risk development during the first half of the month, primarily bugfixes during the second half. The test suite continues to improve slowly; we need more tests. I think we can continue to generate reliable monthly releases that way. A quarterly stable release might be nice but too much extra work I think. Any other ideas welcome.
memory meter --simon, Sun, 26 Oct 2003 01:45:14 -0700 reply
I've added a memory usage meter to the skin temporarily. MemoryUsage has the code if you want it. See also the pretty ColourTests.
just in time for Halloween... --DanMcmullen, Sun, 26 Oct 2003 13:20:49 -0800 reply
PerPageStylesHack - not for the faint of heart!
i'm not sure what to make of this myself. horribly cool?
:-) dan
re: NewHierarchyControls --DanMcmullen, Sun, 26 Oct 2003 15:48:56 -0800 reply
how do we manipulate the prev/next order of subpages?
server trouble --simon, Sun, 26 Oct 2003 23:32:05 -0800 reply
Tried to move the wiki to a SkinnedFolder, major project since it turns out the current Folder has more pages than it can handle within our quota (and most browsers have a hard time with the 2Mb ZMI table, ZEO doesn't have all the right authorization, etc..). Big waste of time, I ended up losing page creation times. Didn't backup first. :( I'm going to see if imeme have a recent one.
Re: Making AllPages work under Plone -- Mon, 27 Oct 2003 01:49:31 -0800 reply
Put dtml-var REQUEST by itself in AllPages and a couple of other pages. What do you get ?.
Do you have an object named REQUEST in the zodb ?
I haven't found one. Where should this object be found?
Thanks for your patience. :-)
-- Andreas
Mailman archiver --PieterB, Mon, 27 Oct 2003 14:22:14 -0800 reply
There is a discussion on the mailman-developers list on the requirements of an archiver: See: or my post at:
(new) Requirements for a new archiver --PieterB, Mon, 27 Oct 2003 14:46:58 -0800 reply
On Mon, Oct 27, 2003 at 05:28:50PM -0500, Barry Warsaw wrote:
Also have a look at the "SMART Archiver" project, didn't know about that one!
It's a similar university project of the Eindhoven University of Technology. The project has just been finished and I assume all sources are/will be available. I saw the author upload the code to sf.net, and probably our host gewis.nl will host a demo environment in a couple of weeks.
About coupling the archiver/mailinglist:
So I don't want to have to ask the archiver for that url. I want Mailman to be able to calculate it from something unique in the message, and have the archiver agree on the algorithm, so that it (or some other translation layer) can do the mapping back to the archived article. Or, Mailman should be able to calculate a unique id for the article and stuff that in a header for the archiver to index on.
Zwiki has implemented such functionality based on the time that the message is received/sent. E.g. a mailout for a webpost at the looks like this in the e-mail: (look at the generated signature, with a hyperlink to the message anchor)
There is a discussion on the mailman-developers list on the requirements of an archiver: See: or my post at: -- forwarded from
Off course, in this case the msgid, doesn't have to be shared between the archiver and mailinglist, because zwiki does both in one application.
Regards,
Pieter
cc: mailman-developers lists, zwiki GeneralDiscussion
-- When a broken appliance is demonstrated for the repairman, it will work perfectly.
NavigationToolbar --DeanGoodmanson, Tue, 28 Oct 2003 00:00:20 -0800 reply
I tried to get some navigation links built into the HEAD of zwikipage.pt , but keep stumbling over basic ZPT. Any thoughts?:
<link tal: <link tal:
The condition works, the attributes don't.:
Module Shared.DC.Scripts.Bindings, line 283, in _bindAndExec Module Products.PageTemplates.PageTemplateFile, line 103, in _exec Module Products.PageTemplates.PageTemplate, line 87, in pt_render <MyPageTemplateFile at /wiki/SearchPage/> Warning: Compilation failed Warning: TAL.TALDefs.TALError: Python expression error: invalid syntax (line 1) in expression "python:\n here.wiki_url() + '/externalEdit_/'\n modules['Products.PythonScripts.standard'].url_quote(here.id()) +\n '?borrow_lock=1'", at line 26, column 1 PTRuntimeError
RecentChanges? -- Everythings new --DeanGoodmanson, Tue, 28 Oct 2003 22:38:33 -0800 reply
Each item for me in the RecentChanges? is listed as New.
Newbie question --Dirk WESSEL, Wed, 29 Oct 2003 04:00:20 -0800 reply
Reply Requested When Convenient
I'am just new to Zwiki. In my project I have to create a Zwiki site on which users can create and update new documents.
I'am trying now to find an efficient way to structure the zwiki accommodating various documents and creating a table of content for the site as well as for each document.
How can this be achieved?
Newbie question --DeanGoodmanson, Wed, 29 Oct 2003 08:03:36 -0800 reply
Does the NavigationAids and new SubTopics? features help your site TOC?
For files... Want to mock-up what kind of information you expect to be displayed?
Stand alone Zwiki TestPage --DeanGoodmanson, Wed, 29 Oct 2003 12:09:54 -0800 reply
Is a Zwiki TestPage still intended to be added to a non-Zwiki folder in the ZMI? If so, I think the default .pt may fail when checking for enabled subtopics.
RecentChanges? -- Everythings new --Simon Michael, Wed, 29 Oct 2003 15:17:17 -0800 reply
DeanGoodmanson wrote:
Each item for me in the RecentChanges? is listed as New.
Yup, a mishap on my part mentioned the other day.. I have a backup from imeme now and I'll recover the creation times from there.
Stand alone Zwiki TestPage --Simon Michael, Wed, 29 Oct 2003 15:26:03 -0800 reply
Yes, 'ZWiki TestPage's are still supposed to work in any kind of folder. I think I know the problem you mean, but wasn't it fixed in 0.24rc1 ?
A separate issue: I changed
ZWiki Web in the ZMI add menu to
Wiki,
for clarity and consistency with CMF/Plone.
ZWiki TestPage had to remain
unchanged though to avoid tedious upgrade issues. So these two are now
widely separated in the add menu, and next to
Wiki there's a bogus
Wiki content entry that comes from CMF. So I think it's more confusing
and I'd better change it back to
ZWiki Web, even though that's a
made-up term.
Stand alone Zwiki TestPage --SimonMichael, Wed, 29 Oct 2003 15:34:39 -0800 reply
Or, it could be
ZWiki Wiki ? Or just
ZWiki ?
NavigationToolbar --Simon Michael, Wed, 29 Oct 2003 16:14:10 -0800 reply
Dean - I think you want a href, not the link tag which is for stylesheets etc.
Also, if it matters: that code will calculate the entire wiki hierarchy four times, which right now in a large wiki should be avoided. See navlinks() for an example of how to calculate it once and reuse.
Re: Making AllPages work under Plone --Simon Michael, Wed, 29 Oct 2003 16:22:49 -0800 reply
All: sorry my responses here are sluggish, email has been hellish lately. Look for me on #zwiki, it's sometimes more efficient..
Andreas - that's suspicious. Are you using the same AllPages code as on this site ?
Do you have an object named REQUEST in the zodb ?
I haven't found one. Where should this object be found?
That's good, you shouldn't find one there.
re: NewHierarchyControls --Simon Michael, Wed, 29 Oct 2003 16:43:29 -0800 reply
DanMcmullen wrote:
how do we manipulate the prev/next order of subpages?
We don't right now, we would like to be able.
- make zwiki pages archetypes and use archetypes relations feature to store relationships more effciently ?
- hierarchy defined in pages ? This is a bit drastic, but imagine there is no absolute page hierarchy - I put a table of contents on FrontPage, and when I click one of the links zwiki knows I came from FrontPage and looks there to figure out where we are in "the FrontPage hierarchy". If I visit the same page via a different table of contents on some other page, we would appear to be in "the other hierarchy". This would support re-use of "modules" in different "courses", as in the Connexions project. It also might deemphasize hierarchy in a positive sense - less chance of having to think about where a page belongs up front. I'm not sure if it's practical though, due to ugly urls or cookies.
Ideas welcome!
Newbie question --Dirk WESSEL, Thu, 30 Oct 2003 00:25:25 -0800 reply
Reply Requested When Convenient
It might be. But I haven't yet found a way to use it. Documentation is quite weak on that issue..
Does the NavigationAids and new SubTopics? features help your site TOC?Does the NavigationAids and new SubTopics? features help your site TOC?> DeanGoodmanson <zwiki-wiki@zwiki.org> 10/29/03 05:03PM >>>
For files... Want to mock-up what kind of information you expect to be displayed? -- forwarded from
Re: Making AllPages work under Plone -- Thu, 30 Oct 2003 01:08:26 -0800 reply
Are you using the same AllPages code as on this site ?
Yes, I am. I have copied and pasted the code from editform to editform.
-- Andreas
... -- Thu, 30 Oct 2003 03:22:25 -0800 reply
Kodos - The Python Regex GUI Debugger --PieterB, Thu, 30 Oct 2003 07:30:27 -0800 reply
I just happened to find a link to: Kodos - The Python Regex GUI Debugger, which might be usefull for some of you.
Kodos is a Python GUI utility for creating, testing and debugging regular expressions for the Python programming language. Kodos should aid any developer to efficiently and effortlessly develop regular expressions in Python. Kodos is an open source project released under the Gnu Public License (GPL).
(i was testing Scratchy, The Apache Log Parser and HTML Report Generator for Python, . It doesn't want to generete reports for some stupid reason).
History statistics --DeanG, Thu, 30 Oct 2003 07:36:00 -0800 reply
I'd like to get the number of page revisions listed on my page. (And use it to disable the /diff link when there is only 1)
Could someone point me to a Zope resource regarding this? (Besides the diff.py source, that is. ;-))
Note: The diff.py notes that only 20 revisions are available. That's OK for my needs.
Newbie question --Simon Michael, Thu, 30 Oct 2003 13:12:26 -0800 reply
Dirk WESSEL wrote:.
I'm interested in this too. We're still exploring how best to do this.
ZopeBookMirror? seems closest to what you want. It's a book with one (big) page per chapter. There's a per-page table of contents at the top of each chapter, which I added manually; in RestructuredText mode you could generate these automatically. The top page links to each chapter, but does not currently show the detailed contents.
There's a book outline on ZWiki, again with one page per chapter, but chapters are currently empty pages with other pages underneath. If you're in full mode (or is it always) they'll show a "table of contents" linking to the sub topics, each on it's own page.
Hope this helps.
Re: Making AllPages work under Plone --Simon Michael, Thu, 30 Oct 2003 13:15:21 -0800 reply
Yes, I am. I have copied and pasted the code from editform to editform.
Then I'm out of ideas. If you can make this page accessible to me, I can figure it out. And/or come and chat with me on #zwiki.
Kodos - The Python Regex GUI Debugger --Simon Michael, Thu, 30 Oct 2003 13:17:10 -0800 reply
This sounds great, thanks for these links PB
a rather amazing site --SimonMichael, Thu, 30 Oct 2003 22:38:55 -0800 reply
This guy has a lot of energy, well worth a look.
re: NewHierarchyControls --dan mcmullen, Fri, 31 Oct 2003 12:17:30 -0800 reply
Simon Michael wrote:
subpages?<subpages?<> DanMcmullen wrote: >how do we manipulate the prev/next order. <<<
why don't we do both: keep pages doubly linked to parent and children. this gives the best of both worlds, and would enable some simple way to edit the order of the child links. overhead for less frequent things like renaming seems relatively insignificant to me.
2. make zwiki pages archetypes and use archetypes relations feature to store relationships more effciently ? ... 3. hierarchy defined in pages ? <<<2. make zwiki pages archetypes and use archetypes relations feature to store relationships more effciently ? ... 3. hierarchy defined in pages ? <<<>
i'm for keeping it simple initially if we can get something useful working quickly.
best, dan
re: NewHierarchyControls -- Fri, 31 Oct 2003 16:02:49 -0800 reply
Well, you're right, renaming is infrequent. On the other hand, I've been pushing to make everything avoid touching pages in the zodb as much as possible. I'm afraid that if rename, reparent etc. have to touch a lot of pages they'll go back to being very slow in a large wiki.
re: NewHierarchyControls --dan mcmullen, Fri, 31 Oct 2003 16:38:52 -0800 reply
zwiki-wiki@zwiki.org wrote:
touch a lot of pages they'll go back to being very slow in a large wiki.<<<touch a lot of pages they'll go back to being very slow in a large wiki.<<<I'm afraid that if rename, reparent etc. have to
how significant will updating a typical number of child pages be compared to the search for backlinks to update? (this is where i assume the bulk of the time in rename/reparent goes?) if we keep a list if children in the parent we don't need to search for children to update.
Themes --DeanG, Fri, 31 Oct 2003 22:34:15 -0800 reply
I like the themes. I'd like to suggest a "custom" category where a path value is editable near the selection. It's a quick way to view Zwiki under other skins, like those in the CSS Zen Garden , without having to muck around your browser options and keep setting localized to the site. | http://zwiki.org/GeneralDiscussion200310?subject=Re%3A%20Making%20AllPages%20work%20under%20Plone&in_reply_to=%3C20031023010444-0700%40zwiki.org%3E | CC-MAIN-2019-39 | refinedweb | 8,856 | 74.29 |
std::basic_istream::sentry
An object of class
basic_istream::sentry is constructed in local scope at the beginning of each member function of std::basic_istream that performs input (both formatted and unformatted). Its constructor prepares the input stream: checks if the stream is already in a failed state, flushes the tie()'d output streams, skips leading whitespace if skipws flag is set, and performs other implementation-defined tasks if necessary. All cleanup, if necessary, is performed in the destructor, so that it is guaranteed to happen if exceptions are thrown during input.
Member types
Member functions
std::basic_istream::sentry::sentry
Prepares the stream for formatted input.
If is.good() is false, calls is.setstate(failbit) and returns. Otherwise, if is.tie() is not a null pointer, calls is.tie()->flush() to synchronize the output sequence with external streams. This call can be suppressed if the put area of is.tie() is empty. The implementation may defer the call to flush until a call of is.rdbuf()->underflow() occurs. If no such call occur before the sentry object is destroyed, it may be eliminated entirely.
If
noskipws is zero and is.flags() & ios_base::skipws is nonzero, the function extracts and discards all whitespace characters until the next available character is not a whitespace character (as determined by the currently imbued locale in
is). If is.rdbuf()->sbumpc() or is.rdbuf()->sgetc() returns traits::eof(), the function calls setstate(failbit | eofbit) (which may throw std::ios_base::failure.
If after preparation is completed, is.good() == true, then any subsequent calls to operator bool will return true.
Parameters
Exceptions
std::ios_base::failure if the end of file condition occurs when skipping whitespace.
std::basic_istream::sentry::~sentry
Does nothing.
std::basic_istream::sentry::operator bool
Checks whether the preparation of the input stream was successful.
Parameters
(none)
Return value
true if the initialization of the input stream was successful, false otherwise.
Example
#include <iostream> #include <sstream> struct Foo { char n[5]; }; std::istream& operator>>(std::istream& is, Foo& f) { std::istream::sentry s(is); if(s) is.read(f.n, 5); return is; } int main() { std::string input = " abcde"; std::istringstream stream(input); Foo f; stream >> f; std::cout.write(f.n, 5); std::cout << '\n'; }
Output:
abcde | http://en.cppreference.com/mwiki/index.php?title=cpp/io/basic_istream/sentry&oldid=62361 | CC-MAIN-2015-06 | refinedweb | 371 | 50.73 |
> -----Original Message-----
> From: Aaron Mulder [mailto:ammulder@alumni.princeton.edu]
> Sent: Wednesday, October 08, 2003 7:12 PM
> To: 'geronimo-dev@incubator.apache.org'
> Subject: Re: namespace targets
>
>
> On Wed, 8 Oct 2003, Cabrera, Alan wrote:
> > Since we're talking about XML, have we decided on the issue of
> > namespace targets? Am I the only one who thinks that
> modifying Sun's
> > elements and putting them back into Sun's namespace is a
> bad idea? If
> > I am, then why is this a non-issue?
>
> I'm with you, brother!
>
> Among other things, XMLBeans barfed complaining that
> the "geronimo-xxx" DDs duplicated elements in the "xxx" DDs.
> (i.e. we declare "enterprise-beansType" the type and
> "enterprise-beans" the element in the J2EE namespace in both
> ejb-jar_2_1.xsd and geronimo-ejb-jar.xsd). I think it was
> justified. One of the Geronimo DDs is already in its own
> namespace, and I think the rest should follow.
>
> We also need to solve the MxN issue of Geronimo
> releases and J2EE
> versions. Which is to say, if our Geronimo DD extends the
> J2EE DD, it has
> to be different for J2EE 1.2, 1.3, and 1.4, and I think that
> in order to
> pass the compatibility tests we need to eventually support
> all 3. Plus,
> as major Geronimo releases come and go (and presumably add or alter
> features and thus DD elements), we need to distinguish the
> schema sets for
> each release.
>
> Though, perhaps we can always require the Geronimo DDs
> to be written for the most current J2EE release. So even if
> you're deploying an EJB 1.1 EJB JAR, you'd use a "J2EE 1.4"
> geronimo-ejb-jar.xml DD, and we'd just populate any required
> elements or attributes that were not present in the older
> ejb-jar.xml (the mandatory "version" springs to mind). That
> way we'd avoid distinguishing based on J2EE versions, and
> only distinguish based on Geronimo versions.
>
> If we go that way, then we have three options for the
> namespaces and file names (example for Geronimo version 1.0):
>
> Namespace:
> Schema: geronimo-ejb-jar_1_0.xsd
>
> Namespace:
> Schema: geronimo-ejb-jar.xsd
>
> Namespace:
> Schema: geronimo-ejb-jar_1_0.xsd
>
> I'd personally prefer one of the latter two, if for no
> other reason that where we started the whole conversation,
> avoiding having multiple files in the same namespace define
> the same elements.
I personally dislike dots in namespace verions and prefer underscores, e.g.
1_0.. | http://mail-archives.apache.org/mod_mbox/geronimo-dev/200310.mbox/%3C79B184B0417FD41184DB00508BA540B8058C3583@corpmail01%3E | CC-MAIN-2014-52 | refinedweb | 414 | 66.74 |
Search: Search took 0.05 seconds.
Architect, EXTJS4 MVC and liferay
Integrating Google chart with ExtJs 4-MVC
- Last Post By:
- Last Post: 22 Oct 2012 8:53 AM
- by mitchellsimoens
Pass function to a store config option
ExtJS MVC belongsTo/hasMany unwanted properties
Refs in dynamic view and multiple controllers
MVC Architecture and "classic website" structure: should they be used toghether?Started by Fire-Dragon-DoL, 3 Oct 2012 7:54 AM
- Last Post By:
- Last Post: 5 Oct 2012 12:35 AM
- by a.premkumar
Poll: Is MVC really required?
- Last Post By:
- Last Post: 14 Oct 2012 7:00 AM
- by themightychris
how to set the click event to the label
- Last Post By:
- Last Post: 2 Oct 2012 8:48 AM
- by mitchellsimoens
Ext.application does not create App object/namespace
Packaging non-MVC apps with Phonegap-Cordova
Dynamic button on navigation view bar
- Last Post By:
- Last Post: 25 Sep 2012 5:26 AM
- by mitchellsimoens
View showing as 'display:none' when added to container (layout hbox) via items config
Sencha Architect MVC with related models
function to analyze store data then feed it to pie chart
Extjs - 4.1.1 - Moving between views in an Extjs appStarted by always.amita, 3 Sep 2012 4:26 AM
- Last Post By:
- Last Post: 17 Sep 2012 10:29 AM
- by always.amita
EXT JS 4 MVC - call from controller a click event on a div
- Last Post By:
- Last Post: 17 Sep 2012 6:32 AM
- by mitchellsimoens
Extjs 4.1.0 MVC - Grid continously shows loading mask while store has reloadedStarted by always.amita, 1 Sep 2012 12:33 AM
- Last Post By:
- Last Post: 3 Sep 2012 3:40 AM
- by always.amita
Results 76 to 100 of 180 | https://www.sencha.com/forum/tags.php?tag=mvc&pp=&page=4 | CC-MAIN-2015-40 | refinedweb | 295 | 66.07 |
Context
Traditionally applications have been single-target. When projects evolve, and the target and the team grow, working with a monolith project becomes very hard:
- The targets take too much time to compile.
- The is hard to reuse across platforms.
- There are many strong intra and inter dependencies.
Inspired by microsvervices, the Framework Oriented Programming project architecture pretends to reduce these issues by splitting the large application module, into smaller and atomic chunks.
In the next sections, we’ll dive into the definition of the architecture and how different code components would fit into all the modules of our projects.
The core idea of framework oriented programming is not something we’ve invented. You can find a lot of literature about scaling projects by splitting up your project in different services. Our aim is to apply all these principles, that help projects scale easily in other platforms, to scale our Xcode apps.
Why modularizing my apps?
- Workflow cycles are much faster. You work on your module and once finished, it’s hooked in the app.
- Boundaries will encourage good practices using APIs frameworks expose.
- If you have Swift and Objective-C in your project, frameworks will be the perfect place to start coding pure Swift in the project.
- Higher atomicity of features and teams and fewer dependencies.
- Your features become more reusable across products/platforms.
Index
Principles
- Your application is built by combining different modules. These modules can be dynamic frameworks (if you are using Swift), or static libraries.
- Modules have interfaces that expose to the consumers (apps & modules). The interface is the entry point to the framework, and everything exposed by the interface should be public. If the API does not expose something it should remain private.
- Modules can be platform specific if you plan to support only one platform, or they can be cross-platform. You can achieve using the build settings attribute
SUPPORTED_PLATFORMS.
- Sharing a base configuration is recommended since it’ll ensure consistency in the frameworks settings. Here you can find an example of a cross-platform framework configuration.
- Targets that build the modules can be in the same project or different projects. The benefit of having different projects in the same workspace is that the chances to suffer conflicts when modifying the same project file from different branches decrease.
- Although you can set up the stack manually, you can use tools like CocoaPods where your modules are defined with
.podspec. CocoaPods makes easier depending on external dependencies.
- Even though it’s possible to integrate external dependencies into the stack it’s discouraged. External dependencies come with unnecessary maintainability costs. Before bringing an external dependency, think about the value it brings to your application core.
- Module projects can come with an example app and a Playground. Playgrounds are very handy to document the usage of the APIs or onboard people into the module.
Core
Core is the framework at the bottom of the stack. It’s the responsible for providing the frameworks in upper levels with tools that they need to build their features. A few examples of these tools could be:
- A client to interact with your product API.
- A store for persisting and retrieving data from the disk or a database.
- A tool for reporting analytics events to an external provider.
- A logging wrapper with custom features, like verbosity level.
Notice that some of these tools will be a shared instance with a configuration that depends on the app. For example, your client will point to an URL that depends on the configuration that you are building. Similarly, the log level will be different in your
Release build compared to your
Debug build.
One possible way to get it done has a shared configuration that every new instance of the client will take by default:
class Client { static var appConfig: Config! let config: Config init(config: Config = Client.appConfig) { self.config = Client.config } }
Other tools, will be instantiated by the feature that needs it. Depending on the expensiveness of its creation, features might lazily load it, or get set up at startup time. A good example of these would be the
Store:
import Core class Feature { let store: Store<Entity> init() { store = Core.DiskStore(name: "feature") } }
Features
Features framework allows dependency inversion with features. Feature A and B don’t know about each other, but they know about their interfaces because they’ve been defined in the Features framework. Without the dependency inversion in place, accessing B from A, creates an implicit dependency between these two frameworks. With such dependency, you can’t use A without importing B in a different application.
All the models that these interfaces (or protocols) expose should be part of
Features as well.
Testing
Most times you’ll find yourself writing helpers or testing expectations that other teams might need as well. By extracting all of them in a framework, you make them reusable across all the feature frameworks.
UI
For consistency in your applications designs, there are certain UI elements that are shared across the features, elements like fonts, colors, or custom views. It’s also a good place for
UIKit and
AppKit extensions that you come up with.
These elements can be placed in an UI framework that the feature frameworks depend on.
Feature
Feature frameworks represent one or multiple related features of your apps. Features are composed by business logic (data) and presentation (views). While the business logic is common for all the platforms, the presentation layer might differ because for example:
UIKitis not available for that platform.
- The layout is different for that platform.
UIKitAPIs differ between platforms.
For that reason, features should be horizontally split into the Core and the UI frameworks.
Core
It contains the business logic of your features. It’s up to the teams to decide about the patterns that they want to follow inside the framework (MVC, MVVM, MVP, VIPER). Different use cases could be exposed as interactors that would be hooked from the feature UI framework.
UI
The UI of your features will be in this framework. Since UIs will most likely be different between platforms, it’s very recommended to have one framework per platform:
Feature_iOS Feature_macOS
Features can be a composition of views from other features. The result of that composition will be another view that will be exposed. These views should be able to respond to actions and trigger state updates.
If actions imply navigation to features in other frameworks, they should be delegated to the app.
Products
The product targets are the top element in the stack. The result of its build is the app or extensions that users will use on their devices. Since features will be defined in the frameworks and will provide the views and view controllers that represent them, the responsibility of the app is hooking up all of them and define the navigation of the app.
As mentioned earlier, the app will set up
Core tools at startup time and notify about the application lifecycle events to the components in lower levels that need to know about them.
Setup
Manual
Although all the targets for the frameworks can be on the same projects, keeping them in diferent project will make them completely independent from the others:
- For each framework you’ll need a project that includes the source and unit tests target. Optionally, these projects can also include a playground to onboard people or document the interface of the framework.
Frameworks/ FreatureA FeatureB
- To ensure all the frameworks share the same base configuration, create a
Framework.xcconfigand set it as the configuration for the frameworks. It’s important that you define the deployment target and the supported platforms in it.
Frameworks/ Configuration/ Framework.xcconfig
- Add all these projects to the workspace where the application is (if it’s not in a workspace, create one).
- Define the linking between the frameworks. Be careful here because when Xcode will most likely use absolute routes for the links. Make sure that the
.frameworkpaths are relative to the build products folder.
- Add a copy frameworks build phase in:
- The projects tests targets.
- The applications targets.
- Optionally you can define schemes for building and testing each of the frameworks individually, or create one that groups all of them.
If you are building cross-platform frameworks it’s very easy to break the support for the platforms you’re not building for in your workflow. To prevent this, you can define a continuous integration step in your pipeline, that build the frameworks for all the platforms that they are supposed to support.
CocoaPods
If you prefer to use CocoaPods to create the stack it’s also possible:
- Create the frameworks as pods with
pod lib create Feature.
- Update the
.podspecaccordingly specifying the
deployment_targetand defining their dependencies, either external or local.
- Add all the dependencies to the
Podfile, being the first one
Coreand the last one the
Features.
- Execute
pod install. It’ll update the workspace to include these dependencies. Notice that CocoaPods will create schemes for building these dependencies individually.
With CocoaPods it’s easier to bring external dependencies. Otherwise, you’d need to appeal to Carthage, Git Submodules or Swift Package Manager.
Tools
Framework generation
Every time you create a new project for a framework, you need to repeat the same steps. Hopefully, there are tools that help you automate the creation and save a lot of time:
Pandora
Once you start modularizing your apps you’ll notice that you repeat the same steps every time you are about to create a new framework. Create the project, set the config, connect dependencies, add the example app… Hopefully we’re developers and we can automate things! And that’s what we did with Pandora. Pandora is a command line tool written in Ruby to automate Framework tasks.
Example: Creating a framework
pandora create Search com.myorg
SwiftPlate
Easily generate cross platform Swift framework projects from the command line. SwiftPlate will generate Xcode projects for you in seconds, that support:
- [x] CocoaPods, Carthage, Swift Package Manager
- [x] iOS/ macOS / watchOS / tvOS / Linux
Example: Creating a framework
swiftplate
Dependency managers
Useful for fetching external dependencies and integrate them into your frameworks-based projects.
- CocoaPods: CocoaPods manages dependencies for your Xcode projects. You specify the dependencies for your project in a simple text file: your Podfile. CocoaPods recursively resolves dependencies between libraries, fetches source code for all dependencies, and creates and maintains a Xcode workspace to build your project.
- Carthage: Carthage is intended to be the simplest way to add frameworks to your Cocoa application. Carthage builds your dependencies and provides you with binary frameworks, but you retain full control over your project structure and setup. Carthage does not automatically modify your project files or your build settings.
- Swift Package Manager: The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.
- CocoaSeeds: Git Submodule Alternative for Cocoa. Inspired by CocoaPods.
Contribute
How to contribute?
- You can contribute to the project opening an issue on the repository. You can propose improvements, report mistakes, or just open a discussion.
- You can also fork the repository and apply the changes directly. You can propose a merge request afterwards that will be reviewed before getting merged.
How to setup the project
- Git clone theh repository with
git clone
- Install gem dependencies with
bundle install
- Run the server with
bundle exec jekyll serve
- Open
We’re looking forward to your improvements!
If your project were already using a similar modularized setup, or you moved towards this direction, you can share your experience in this section. Open a merge request and do not hesitate to share it!
Thanks
Special thanks to all the contributors listed below that have helped to make this reference possible and spread the idea of modularizing code:
- Felix Gabel - @blinker13
- Juan Cazalla - @juancazalla
- Isaac Roldán - @isaacroldan
- Matej Balantič - @MatejBalantic
- Raimon Lapuente - @Wolffan
Resources
Talks
- Framework Oriented Programming (Mobiconf2016):
- A journey into frameworks and Swift:
- Framework Oriented Programming (NSBudapest):
- Framework Oriented Programming:
Articles
Further reading
-
- Microservices - Link
- Framework Oriented Programming and It’s Relation to OOP - Link | http://frameworkoriented.io/ | CC-MAIN-2017-43 | refinedweb | 2,027 | 55.64 |
Secure Your Web Apps Using the Servlet API
Prior to Java Enterprise Edition (Java EE) 7, there were only a couple of ways to secure your servlets. These included HTTP Basic Authentication and oAuth. In either case, a callback mechanism was employed to prompt the user for his or her credentials. If the credentials—defined in the web.xml file—were accepted, the user would be "authenticated." On the server, his or her access rights had to be matched against the access rights required to access the resource. A successful match would allow the user to proceed; otherwise, he or she would receive a 403 error.
The Servlet API 3.1 introduced several new annotation types for use in Servlet classes, including @ServletSecurity, which is used to define access control constraints to servlets. By using annotations, we now can enforce security constraints without having to declare them in the web.xml file. In today's article, we'll configure a Banking servlet to invoke HTTP Basic Authentication using annotations.
Creating the Project
One of the best (if not the best) IDEs for Web application development is Eclipse. Its many amazing features and versatility make it a favorite among developers everywhere. We'll be using Eclipse Oxygen here today.
You'll also need a Web server that supports servlets. We'll be using Tomcat 9 in our project. It's an open source implementation of the Java Servlet, JavaServer Pages, Java Expression Language, and Java WebSocket technologies.
When you're ready:
- Launch Eclipse and create a new Dynamic Web project.
On the New Dynamic Web Project dialog:
- Enter a Project name of "AcmeBankingApp".
- Select "Apache Tomcat v9.0" for the Target runtime. If the "Apache Tomcat v9.0" item is not there, follow the steps listed in the next section, "Adding the Tomcat Runtime."
- Accept all of the defaults. The dialog should like this:
Figure 1: The Dynamic Web Project
- Click the Finish button to close the dialog and create the project.
Here's our new project in the Project Explorer:
Figure 2: The new project
Adding the Tomcat Runtime
If you haven't added your Tomcat server to the Eclipse Preferences page via Window -> Preferences -> Server Runtime Environments, you can add it from the Dynamic Web Project dialog by clicking the New Runtime...button.
On the New Server Runtime Environment dialog:
- Expand the Apache folder and select "Apache Tomcat v9.0" from the Runtime Environments list:
Figure 3: New Server Runtime Environment
- Click Next >.
- On the next page, use the Browse...button to navigate to the installation directory of your Tomcat server:
Figure 4: Tomcat Server
- Accept all of the other defaults and click Finish to add the Tomcat server runtime and close the dialog.
You now will be able to select the "Apache Tomcat v9.0" item from the Target runtime list.
The Index File
The index.jsp page will be the landing page of our app. On it, we'll place a button that invokes the account servlet's deposit() method.
- Right-click the WebContent folder in the Project Explorer and select New -> JSP File from the popup menu.
On the New JSP file dialog:
- Name the file "index.jsp" and click Finishto create the file.
Figure 5: The new JSP file
- In the Editor, paste the following code into the file:
<%@ page <title>ACME Banking App</title> </head> <body> <h1>Welcome to the ACME Banking App!</h1> <p>What would you like to do today?</p> <form action="account" method="post"> <button type="submit">Deposit $100.00</button> </form> </body> </html>
- Save the changes.
Clicking the Deposit button will send a POST request to the account servlet.
The Account Servlet
On the servlet, the doPost() method will handle the form request. To keep things simple, we'll calculate the new account balance within the doPost() and return it to the browser—first, without any security:
- Right-click the project root in the Project Explorer and select New -> Servlet from the popup menu.
On the Create Servlet dialog:
- Provide a Java package name of "com.acmebanking.servlet" and a Class nameof "AccountServlet":
Figure 6: Creating the servlet
- Click Finish to create the servlet.
- Add the following code to the AccountServlet.java file:
package com.acmebanking = "BankAccountServlet", description = "Represents an ACME Bank Account and its transactions", urlPatterns = {"/account", "/bankAccount" }) public class AccountServlet extends HttpServlet { private static final long serialVersionUID = 1L; private double accountBalance = 1000d; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.accountBalance = accountBalance + 100d; PrintWriter writer = response.getWriter(); writer.println( "<html> Balance of the account is: $" + this.accountBalance + "</html>"); writer.flush(); } }
Securing the Servlet
At this point, anyone can access the servlet via the "/account" or "/bankAccount" path.
Let's protect it by using the @ServletSecurity annotation:
@ServletSecurity( value = @HttpConstraint(rolesAllowed = {"Member"}), httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"Admin"})})
In the preceding code, we're assigning a general HTTP Constraint as well as one that applies specifically to the POST method. The rolesAllowed element accepts an array of zero or more role names. We haven't defined any security roles yet, so when you build the project, the server will display a warning stating:
WARNING: Security role name [Admin] used in an <auth-constraint> without being defined in a <security-role>
Setting Role Names and Accounts
Tomcat maintains the list of user accounts in the tomcat-users.xml file. You can find it in this directory: CATALINA_HOME/conf (where the CATALINA_HOME environment variable is the Tomcat installation directory).
Make sure that you add the Admin user role and Jane user account:
<?xml version="1.0" encoding="UTF-8"?> <tomcat-users> <role rolename="Admin"/> <user username="Jane" password="password" roles="Admin"/> <role rolename="manager-gui"/> <user username="tomcat" password="tomcat" roles="manager-gui"/> </tomcat-users>
Running the App
Let's take the app out for a test run now and see what happens.
- Right-click the project in the Project Explorer and select Run As -> Run on Server from the context menu.
On the Run on Server dialog:
- Make sure that your Tomcat server is selected and click Next >:
Figure 7: Running on the server
- On the next page, make sure that the AcmeBankingApp appears in the Configured list, and click Finishto launch the app:
Figure 8: Ready to launch the app
- That will show the index.jsp page in the browser. Click the Deposit $100.00 buttonto invoke the servlet:
Figure 9: Invoking the servlet
- Doing so will result in an "HTTP Status 403 - Forbidden" error:
Figure 10: Access is forbidden
Don't panic; that is exactly the result that we're looking for. This error happened because we have included annotations on the servlet to only allow users with the role of "Admin" to access the servlet via POST submission.
In the next installment, we'll configure the "user" and "web" XML files to have the server present an authentication form to access the Banking Servlet.
For reference, this entire project is hosted on GitHub.
This article was originally published on June... | https://www.developer.com/java/ent/secure-your-web-apps-using-the-servlet-api.html | CC-MAIN-2020-16 | refinedweb | 1,167 | 55.54 |
In this section you will find a program to find the length of array in java. An array is collection of similar data type. To find the length of array is a simple program in java. Using length function you can find the length of array.
Syntax : array-name. length
Example : int a[] = { 10,20,30,40,50};
If you have to find the length of an array a, you can use a.length, it will return the length of array i.e. 5.
Code to find the length of an array
public class Length { public static void main(String args[]) { int a[]= {12,23,0,90,76,40}; System.out.print("Length of array = "); System.out.print(a.length); } }
In the above code declaration and initialization of an array a, and finding the length of an array by a.length, returning the length of array a.
Output: When you compile and execute the code output will as below: Array Length
Post your Comment | http://roseindia.net/help/java/a/array-length-in-java.shtml | CC-MAIN-2016-40 | refinedweb | 164 | 75.2 |
What is the right way to treat argparse.Namespace() as a dictionary?
You can access the namespace's dictionary with vars():
import argparse args = argparse.Namespace() args.foo = 1args.bar = [1,2,3] d = vars(args) d{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
'baz'] = 'store me'args.baz'store me'd[
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
Straight from the horse's mouth:
If you prefer to have dict-like view of the attributes, you can use the standard Python idiom,
vars():
'--foo') args = parser.parse_args(['--foo', 'BAR'])vars(args){'foo': 'BAR'}parser = argparse.ArgumentParser() parser.add_argument(
— The Python Standard Library, 16.4.4.6. The Namespace object
Is it proper to "reach into" an object and use its dict property?
In general, I would say "no". However
Namespace has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.
On the other hand,
Namespace does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the
__dict__, but the limits of my imagination are not the same as yours. | https://codehunter.cc/a/python/what-is-the-right-way-to-treat-argparse-namespace-as-a-dictionary | CC-MAIN-2022-21 | refinedweb | 207 | 66.23 |
Name | Synopsis | Description | Return Values | Attributes | See Also
#include <stdio.h> #include <widec.h> int wsprintf(wchar_t *s, const char *format, /* arg */ ... ););
The wsprintf() function outputs a Process Code string ending with a Process Code (wchar_t) null character. It is the user's responsibility to allocate enough space for this wchar_t string.
This returns the number of Process Code characters (excluding the null terminator) that have been written. The conversion specifications and behavior of wsprintf() are the same as the regular sprintf(3C) function except that the result is a Process Code string for wsprintf( ), and on Extended Unix Code (EUC) character string for sprintf().
Upon successful completion, wsprintf() returns the number of characters printed. Otherwise, a negative value is returned.
See attributes(5) for descriptions of the following attributes:
wsscanf(3C), printf(3C), scanf(3C), sprintf(3C), attributes(5)
Name | Synopsis | Description | Return Values | Attributes | See Also | http://docs.oracle.com/cd/E19082-01/819-2243/6n4i099u5/index.html | CC-MAIN-2016-07 | refinedweb | 148 | 57.57 |
-touch handling using DirectX C++
This article explains how to handle multiple touches (multi-touch) from a C++ DirectX app or WinRT component.
Windows Phone 8
Introduction
Developers programming in C# and XNA will be used to having a number of handy pointer manipulation and gesture events. Unfortunately in these sorts of handy events are not available in C++. Gestures are not supported for Windows Phone 8.0 in C++ even though they are supported in Windows Store apps (as of November 2013).
In DirectX/C++, the DrawingSurfaceManipulationHost]'s PointerPressed, PointerMoved, and PointerReleased events are all that is available.
This article explains how the events work, and how to get enough information in order to build gesture recognition into your app.
How do the pointer events work?
The PointerPressed, PointerMoved, and PointerReleased events can be called more than once per frame. A single finger touching the screen will cause the PointerPressed event to fire once: a second finger touching the screen will cause the PointerPressed event to fire again. The fact that multiple events can be called for each of the events makes handling PointerMoved (in particular) non-trivial.
The events include a PointerEventArgs argument which contains a few items, the most important of which for our purposes is a PointerPoint representing the current point that is being touched. PointerPoint contains all the information we will need to perform calculations for translating, rotating, or scaling your model/camera/whatever.
We're going to be using three properties within the PointerPoint:
- FrameId contains an unsigned int that just counts up for each frame drawn. You can have more than one PointerPoint with the same FrameId.
- PointerId is also an unsigned int, but it represents one of the touch points. If you place your finger on the screen, it will have an PointerId of 1. If you remove and then touch the screen again, the PointerId will be 2 now. It increments for each new touch. If you place two fingers on the screen, they will have sequential PointerIds.
- Position contains your X and Y positions relative to screen resolution divided by the scale factor. This means that 720P screens will actually have positions up to only 480x800. WXGA screens are something like 480x768.
Implementation
First of all, we need to keep track of our touchIds and positions, so I came up with the idea to store the PointerPoint in a std::unordered_map using the TouchId as the key. Most implementations of multi-touch handling require you to know the previous touch positions, so I'm going to create a second std::unordered_map to hold the previous PointerPoint for a particular TouchId. Stick this in the header that contains the event handler declarations.
#include <unordered_map>
std::unordered_map<unsigned int, Windows::UI::Input::PointerPoint^> m_pointerIds;
std::unordered_map<unsigned int, Windows::UI::Input::PointerPoint^> m_oldPoints;
When the screen is touched and PointerPressed is called, store the PointerPoint in the m_pointerIds map using its PointerId as a key (the code also stores the point in the m_oldPoints map, but this may be superfluous). When the finger is released the PointerRelease event is called - remove that PointerId from both of the maps.
void Direct3DBackground::OnPointerPressed(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
{
m_pointerIds.emplace(args->CurrentPoint->PointerId, args->CurrentPoint);
m_oldPoints.emplace(args->CurrentPoint->PointerId, args->CurrentPoint);
}
void Direct3DBackground::OnPointerReleased(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
{
m_pointerIds.erase(args->CurrentPoint->PointerId);
m_oldPoints.erase(args->CurrentPoint->PointerId);
}
Handling PointerMoved is more complicated. If there is more than one touch, you need to make sure that every touch has called PointerMoved before doing any calculations using the currently stored positions.
void Direct3DBackground::OnPointerMoved(DrawingSurfaceManipulationHost^ sender, PointerEventArgs^ args)
{
if (m_pointerIds.size() == 1)
{
RotateWithOneFinger(args); // <- not shown in this article, you can see Microsoft's samples for this.
}
else if (m_pointerIds.size() == 2)
{
MoveWithTwoFingers(args);
}
}
void Direct3DBackground::MoveWithTwoFingers(PointerEventArgs^ args)
{
UINT changedPointId = args->CurrentPoint->PointerId;
UINT frameId = args->CurrentPoint->FrameId;
UINT otherPointId;
for (auto it = m_pointerIds.begin(); it != m_pointerIds.end(); ++it)
{
if (it->first != changedPointId)
{
otherPointId = it->first;
break;
}
}
m_oldPoints[changedPointId] = m_pointerIds[changedPointId];
m_pointerIds[changedPointId] = args->CurrentPoint;
if (m_pointerIds[otherPointId]->FrameId == frameId)
{
//the other point has been updated already and we are on the update of the 2nd point... store it in memory and do calculations
// IF NOT TRUE then
//the first point is being updated, we need to wait for the 2nd point to be updated... so just store it in memory for now
}
}
The way this works is we first check to see how many touches there are. If two (and you can extrapolate all of this to more than two), we're going to do a couple of things first:
- Find the PointerId of the other touch. We know the current one's Id because it's in the event argument.
- Move the current touch's stored PointerPoint in m_pointerIds to m_oldPoints.
- Copy the current touch's new PointerPoint (from args) to m_pointerIds
- Check to see if the other touch's PointerPoint stored in m_pointerIds has the same FrameId as the current touch's FrameId.
That last step is critical. If they are the same FrameId, it means they have both been updated now and you can use the values stored in m_pointerIds to do your calculations.
If they are NOT the same, then you do nothing and wait for the next call.
Summary
This article has explained how to events work in a C++ app, and how to get enough information in order to build gesture recognition into your app. I hope it helps!
Hamishwillee - Thanks Lee!
Hi Lee
Thanks very much for taking the time to contribute this article! I have fixed up the categories to wiki-standard and hope to give it a proper review in a couple of days.
BTW, your site profile is empty - see - you might want to add some detail, and make this public (ie in the privacy tab of your profile).
RegardsHamish
hamishwillee (talk) 01:47, 18 November 2013 (EET)
Hamishwillee - Subedited/Reviewed
Hi Lee
Thanks for updating your profile, and again for this article. Looks like you had some fun doing trial and error.
I've subedited this article for English and Wiki style. The wiki (mostly) uses a fairly dry style - do this and that, rather than explaining the "journey" (which is very much a blog style). The main change is that since you haven't explained how the C# and C++ event handling differs, I've moved most of that stuff into notes and tips - it isn't relevant to the story - though it would be if this article was "migrating to C++ from C#".
I've also removed most of your self-denigration :-) It is an important point that you're a novice C++ programmer but this only needs to be said once. It is also worth saying that you are a C# programmer because this gives developers some idea that you know what you're talking about.
Anyway, please check what I've written and confirm that I have not changed your article for the worse/lost information.
In terms of room for improvement, what would be awesome is a buildable project showing this at work - ie perhaps just recognising a swipe gesture (and yes, I realise that actual gesture processing goes further than this article). Do you think such an example would be possible? The reason I ask is that running code can make it much easier to understand, and it avoids any possible copy-paste errors you might have made, or omissions from "you should do this". Later on when someone comes along and says "this doesn't work" you can point them to the example "yes it does".
A really useful addition to the wiki. You can come share with us anytime :-)
regardsH
hamishwillee (talk) 06:38, 19 November 2013 (EET)
Leemcpherson -
I can do the sample project. Give me a week or so and I can make a basic one. I haven't browsed all of the C++ aricles yet, but if there isn't one on it, I could throw in my actual rotation and scaling transformation matrices and how I calculate them using the pointer data and quaternions.
And thanks for the corrections. It's been a while since I've tried to publish a paper so my writing skills are rusty. Everything looks fine to me.Given all the new stuff I'm trying with C++ and DirectX, I may be doing more of these.
leemcpherson (talk) 16:30, 26 November 2013 (EET)
Hamishwillee - Thanks very much
Thanks - a week or so would be absolutely fine - and I hope we do see more of these articles. Yes, your actual transformation matrices would be good too.
Regards HPS It is much easier to correct work than to create it in the first place, and also much easier to see issues with someone elses work than something you just wrote :-) Upshot, happy to spend the time to tidy for good content.
hamishwillee (talk) 05:13, 27 November 2013 (EET) | http://developer.nokia.com/community/wiki/Multi-touch_handling_using_DirectX_C%2B%2B | CC-MAIN-2014-52 | refinedweb | 1,494 | 61.77 |
Em 26-04-2012 11:25, Mauro Carvalho Chehab escreveu:> Em 26-04-2012 11:11, Borislav Petkov escreveu:>> On Wed, Apr 25, 2012 at 02:47:39PM -0300, Mauro Carvalho Chehab wrote:>>>> Now let's look at your output from earlier:>>>>>>>>> $ ./edac-ctl --layout>>>>> +-----------------------------------+>>>>> | mc0 |>>>>> | channel0 | channel1 | channel2 |>>>>> -------+-----------------------------------+>>>>> slot2: | 0 MB | 0 MB | 0 MB |>>>>> slot1: | 1024 MB | 0 MB | 0 MB |>>>>> slot0: | 1024 MB | 1024 MB | 1024 MB |>>>>> -------+-----------------------------------+>>>>>>>>>> Those are the logs that dump the Memory Controller registers:>>>>>>>>>> [ 115.818947] EDAC DEBUG: get_dimm_config: Ch0 phy rd0, wr0 (0x063f4031): 2 ranks, UDIMMs>>>>>>>> it says here 2 ranks>>>>>> The above output is for the Nehalem machine, with 4 dimms, all single ranked.>>>>>>>> [ 115.818950] EDAC DEBUG: get_dimm_config: dimm 0 1024 Mb offset: 0, bank: 8, rank: 1, row: 0x4000, col: 0x400>>>>> [ 115.818955] EDAC DEBUG: get_dimm_config: dimm 1 1024 Mb offset: 4, bank: 8, rank: 1, row: 0x4000, col: 0x400>>>>> [ 115.818982] EDAC DEBUG: get_dimm_config: Ch1 phy rd1, wr1 (0x063f4031): 2 ranks, UDIMMs>>>>>>>> and here 2 too although there's only one single-ranked DIMM here. So>>>> which is it?>>>>>> The # of ranks there is the total amount of ranks at the channel.>>>> The total amount of ranks what? The channel supports, are present on the>> channel, the number of physical slots?>>>> I'm just saying it is puzzling because your output says "2 ranks" whent>> there are 2 single-ranked DIMMs connected to ch0 and also "2 ranks" when>> there's only one DIMM connected to ch1.> > Ah, ok, now I understood what you meant: yeah, channel 1 and 2 also says> that there are two ranks.> > I'll double check what's happening there.> This were due to the way the driver reports that this channel doesn'thave any 4 Rank memories (e. g. all memories are either 1R or 2R).The enclosed patch should improve the debug output information.Thanks for pointing it,Mauro---From: Mauro Carvalho Chehab <mchehab@redhat.com>Date: Thu, 26 Apr 2012 11:47:29 -0300Subject: [PATCH] i7core: fix ranks information at the per-channel structThere is a flag at the per-channel struct that indicates if there areany 4R dimm on it. The way the presence of this flag were reportedis not ok, as it might give the false idea that the channel were filledwith 2R memories:[ 580.588701] EDAC DEBUG: get_dimm_config: Ch1 phy rd1, wr1 (0x063f7431): 2 ranks, UDIMMs[ 580.588704] EDAC DEBUG: get_dimm_config: dimm 0 1024 Mb offset: 0, bank: 8, rank: 1, row: 0x4000, col: 0x400(in this case, just one 1R memory is filled on channel 1)So, use a better way to represent the per-channel ranks information.After the patch, it will show:[ 2002.233978] EDAC DEBUG: get_dimm_config: Ch0 phy rd0, wr0 (0x063f7431): UDIMMs[ 2002.233982] EDAC DEBUG: get_dimm_config: dimm 0 1024 Mb offset: 0, bank: 8, rank: 1, row: 0x4000, col: 0x400[ 2002.233988] EDAC DEBUG: get_dimm_config: dimm 1 1024 Mb offset: 4, bank: 8, rank: 1, row: 0x4000, col: 0x400(in this case, there isn't any 4R memories)Reported-by: Borislav Petkov <borislav.petkov@amd.com>Signed-off-by: Mauro Carvalho Chehab <mchehab@redhat.com>diff --git a/drivers/edac/i7core_edac.c b/drivers/edac/i7core_edac.cindex dfdee48..f4a0fe1 100644--- a/drivers/edac/i7core_edac.c+++ b/drivers/edac/i7core_edac.c@@ -221,7 +221,9 @@ struct i7core_inject { }; struct i7core_channel {- u32 ranks;+ bool is_3dimms_present;+ bool is_single_4rank;+ bool has_4rank; u32 dimms; }; @@ -557,21 +559,20 @@ static int get_dimm_config(struct mem_ctl_info *mci) pci_read_config_dword(pvt->pci_ch[i][0], MC_CHANNEL_DIMM_INIT_PARAMS, &data); - pvt->channel[i].ranks = (data & QUAD_RANK_PRESENT) ?- 4 : 2;++ if (data & THREE_DIMMS_PRESENT)+ pvt->channel[i].is_3dimms_present = true;++ if (data & SINGLE_QUAD_RANK_PRESENT)+ pvt->channel[i].is_single_4rank = true;++ if (data & QUAD_RANK_PRESENT)+ pvt->channel[i].has_4rank = true; if (data & REGISTERED_DIMM) mtype = MEM_RDDR3; else mtype = MEM_DDR3;-#if 0- if (data & THREE_DIMMS_PRESENT)- pvt->channel[i].dimms = 3;- else if (data & SINGLE_QUAD_RANK_PRESENT)- pvt->channel[i].dimms = 1;- else- pvt->channel[i].dimms = 2;-#endif /* Devices 4-6 function 1 */ pci_read_config_dword(pvt->pci_ch[i][1],@@ -582,11 +583,13 @@ static int get_dimm_config(struct mem_ctl_info *mci) MC_DOD_CH_DIMM2, &dimm_dod[2]); debugf0("Ch%d phy rd%d, wr%d (0x%08x): "- "%d ranks, %cDIMMs\n",+ "%s%s%s%cDIMMs\n", i, RDLCH(pvt->info.ch_map, i), WRLCH(pvt->info.ch_map, i), data,- pvt->channel[i].ranks,+ pvt->channel[i].is_3dimms_present ? "3DIMMS " : "",+ pvt->channel[i].is_3dimms_present ? "SINGLE_4R " : "",+ pvt->channel[i].has_4rank ? "HAS_4R " : "", (data & REGISTERED_DIMM) ? 'R' : 'U'); for (j = 0; j < 3; j++) { | http://lkml.org/lkml/2012/4/26/186 | CC-MAIN-2017-22 | refinedweb | 731 | 65.32 |
rex_noctis
I have recently been messing around with the
turtlemodule on PC and have come up with a few handy programs. I then became curious about the possibilities on Pythonista. I am attempting to make a simple program where the title will move to where the user taps. The
onclick()does not seem to work. I will include the code I was trying to use below. How would I make a program like this and is there any documentation on turtle in Pythonista (I couldn’t find any)?
Code:
from turtle import * speed(0) screen = Screen() def moveTo(x, y): setpos(x, y) screen.onclick(moveTo) screen.listen()
So long story short, I’m good at playing games with touch screen controls and I’m bad with an Xbox controller. However I like slot of Xbox games so this somewhat limits me. So I was wondering if there was some way I could write a programme to connect to my Xbox via Bluetooth and then use custom controls (possible made using
scenemodule) to control it instead of the usual physical controller. I’ll divide this up into a few questions to make it a bit simpler. I know there is a sort of controller on the Xbox app but apparently that can’t be used with games.
- Is there a module or other way to connect to more advanced devices via Bluetooth (the
cbmodule says it’s only for basic Bluetooth devices)?
- Would I be able to control the Xbox through this method without having to modify the Xbox in any way?
- If it’s looking good so far, what are some of the pieces of code I would need to use (quite specifically)?
Thanks in advance. posted in Pythonista • read more
rex_noctis
@rex_noctis Did you try the 3 Australian voices?
speech: en-AU Objective-c: en-AU, Name: Catherine speech: en-AU Objective-c: en-AU, Name: Gordon speech: en-AU Objective-c: en-AU, Name: Karen```
How do I determine between those in the
speech.say()line cause they’re all
en-AU
rex_noctis posted in Pythonista • read more
rex_noctis
So I am building a text to speech program. It currently says text in the default Daniel Encanced voice. I want the program to say stuff in the Australian Male Siri voice. How would I do that? I have tried
speech.say(‘Hello’, ‘en-AU’)but this uses a different Australian voice. Please help.
rex_noctis
Thanks, it’s working now!
rex_noctis
I just realised the error. It’s meant to be
Rect(self.player.position.x-12, self.player.position.y-12, 24, 24)I forgot the
.xon the end of position. Thanks for making me notice it! | https://forum.omz-software.com/user/rex_noctis | CC-MAIN-2019-47 | refinedweb | 450 | 74.59 |
Sum of Series coderinme
Write Java program to compute the sum of the 2+4+6+———+10.
Mathematically, This is an an Arithmetic Sequence because we can clearly see that the difference between one term and the next is a constant (difference 2). In General we could write an arithmetic sequence like this:
{a, a+d, a+2d, a+3d, … }
where:
a is the first term, and
d is the difference between the terms (called the “common difference”)
To sum up the terms of this arithmetic sequence:
a + (a+d) + (a+2d) + (a+3d) + …
use this formula:
Sum = n/2 * { 2a + (n-1) * d }
In Java, it is quiet simple:
Program:
import java.io.*; public class Q10 { public static void main(String[] args) { int sum=0,i; for(i=2;i<=10;i=i+2) sum=sum+i; System.out.println(" The sum is :"+sum); } } | https://coderinme.com/sum-of-series-coderinme/ | CC-MAIN-2018-47 | refinedweb | 145 | 64.24 |
Content
All Articles
PHP Admin Basics
PHP Forms
PHP Foundations
ONLamp Subjects
Linux
Apache
MySQL
Perl
PHP
Python
BSD
Using PHP 5's SimpleXML
Pages: 1, 2
SimpleXML even makes processing RSS 1.0 feeds easy. RSS 1.0 uses XML
namespaces, which can present a bit of a headache during parsing. With XML
namespaces, each element lives under a URL, which acts as a package name. This
allows you to distinguish between, say, the HTML <title>
element and the RSS <title> element.
<title>
All of a sudden things became more complex. You can no longer refer to
title, since an unadorned title doesn't let the processor know
which <title> you mean. You could be thinking of the RSS
item <title>, but there's also an HTML
<title> in the document.
:
Since URLs are long, you can map a short word to the URL. So, you frequently
end up referring to these elements as <xhtml:title> and
<rss:title>. These short names are known as namespace
prefixes. However, it's the URL that's important, so prefixes like
xhtml and rss are conventions, not actual namespaces.
(It's important to mention that the URL doesn't have to resolve to a web page, it's just an easy way for people to create non-conflicting namespaces.)
<xhtml:title>
<rss:title>
xhtml
rss
SimpleXML likes the world to be simple, so it pretends the namespaces don't
exist. (I know a whole crowd of readers feel this cure is worse than the
disease. Remember, however, this is SimpleXML. If you're
worried about namespace clashes use DOM.)
Here's the same data as before, encoded as RSS 1.0 and saved as
rss-1.0.xml:
rss-1.0.xml
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns:rdf=""
xmlns:
<channel rdf:
<title>PHP: Hypertext Preprocessor</title>
<link></link>
<description>The PHP scripting language web site</description>
</channel>
<item rdf:
<title>PHP 5.0.0 Beta 3 Released</title>
<link></link>
<description>
PHP 5.0 Beta 3 has been released. The third beta of PHP is
also scheduled to be the last one (barring unexpected surprises).
</description>
<dc:date>2004-01-02</dc:date>
</item>
<item rdf:
<title>PHP Community Site Project Announced</title>
<link></link>
<description>
Members of the PHP community are seeking volunteers to help
develop the first web site that is created both by the community and for
the community.
</description>
<dc:date>2003-12-18</dc:date>
</item>
</rdf:RDF>
This XML document has three different namespaces. Looking at the top of the
file, two namespaces have explicit namespace prefix mappings. That's what
xmlns:rdf="" and the
following line does. It associates those URLs to rdf and
dc. You can see rdf:RDF, rdf:about, and
dc:date elements and attributes within the document.
xmlns:rdf=""
rdf
dc
rdf:RDF
rdf:about
dc:date
RDF is "Yet Another XML Spec" (YAXMLS). I won't go into it here, but you
can learn more on the W3 RDF site and in
Tim Bray's article, What is RDF?, on XML.com. O'Reilly
also has a book on RDF titled, Practical RDF.
There's also one entity without a prefix,
xmlns="". That's the default namespace,
since there's no colon after xmlns. Elements without a prefix,
like item and title, live in the default namespace.
This is different from RSS 0.91, where elements do not live in any
namespace.
xmlns=""
xmlns
item
To search for elements in a namespace under DOM, you need to switch to a
new set of methods, where you pass in the tag and the namespace. As I said
earlier, SimpleXML just barges forward with its head down. You can use the
exact same syntax with RSS 1.0 as earlier:
foreach ($s->item as $item) {
print $item->title . "\n";
}
PHP 5.0.0 Beta Released
PHP Community Site Project Announced
This is not a problem because, despite all the namespace vigilance, there
are no name clashes in the document.
However, SimpleXML is not completely naive. It recognizes the potential for
problems with this attitude. Therefore, you can distinguish between two
namespaced elements with XPath, but you need to use namespace prefixes.
SimpleXML automatically registers all the non-default namespace prefixes,
but you need to handle the default namespace. (This lack of default namespace
mapping is a deficit in XPath 1.0, not SimpleXML.)
To find and print all rss:title entries:
rss:title
$s = simplexml_load_file('rss-1.0.xml');
$s->register_ns('rss', '');
$titles = $s->xsearch('//rss:item/rss:title');
foreach ($titles as $title) {
print "$title\n";
}
PHP 5.0.0 Beta 3 Released
PHP Community Site Project Announced
After loading the file, manually register a namespace prefix to go with. You're free to select any prefix you
want, but rss is a natural choice.
The new XPath query now looks for //rss:item/rss:title instead
of plain old //item/title, since it needs namespace prefixes.
It's a little funny that there's no way to define a default namespace prefix
for an XPath search, but that's how it is. Even though these elements don't
have explicit prefixes in the document, they need prefixes in the XPath
query.
//rss:item/rss:title
//item/title
You can use XPath to take advantage of the additional data in the RSS feed.
For instance, to find and print all the entries from January 2004:
$s = simplexml_load_file('rss-1.0.xml');
$s->register_ns('rss', '');
$titles = $s->xsearch('//rss:item[
starts-with(dc:date, "2004-01-")]/rss:title');
foreach ($titles as $title) {
print "$title\n";
}
PHP 5.0.0 Beta 3 Released
The first two lines are the same, but I've modified the XPath query to
filter the results. In XPath, you can request a subset of elements in a level
by requiring them to match a test inside of square brackets ([]).
This test requires the dc:date element under the current
rss:item to begin with the string 2004-01-. If so,
starts-with() returns true, and XPath knows to include it in the
results. (These dates are part of the Dublin Core Metadata specification, hence
the prefix of dc.)
[]
rss:item
2004-01-
starts-with()
This prints only one title because the Community Site item was posted in
December, while Beta 3 came out in January. (Actually, it came out at the end
of December, but it makes the example easier to explain.)
SimpleXML has a few more features: you can edit elements and attributes in
place by assigning them a new value. Then, you can save the modified XML
document to a file or store it in a PHP variable. Additionally, you can
validate XML documents using XML Schema.
Besides RSS, SimpleXML is also perfect for parsing configuration files and
consuming web services with REST. Additionally, I'm sure that as PHP 5
evolves, SimpleXML will gain even more functionality. Keep an eye peeled for
the announcements and enjoy playing with SimpleXML.. | http://www.onlamp.com/pub/a/php/2004/01/15/simplexml.html?page=2 | CC-MAIN-2017-09 | refinedweb | 1,168 | 65.42 |
Basemap is the Matplotlib subpackage and one of the most commonly used and convenient tools for geographic data visualization in Python. The traditional Python install packages (PIP Install Basemap or Conda Install Basemap) often report errors and indicate that Python 2.7 Basemap and Python 3.6 conflict (Figure). Although 2.7 is a classic and most of the world’s data is still based on 2.x, it has been officially announced that 2.x is only for maintenance until 2020 and 3.x is the future.
The following is the Windows environment Python 3.x installation of basemap to share, for your reference.
Premise: My computer is configured 64 for Win10, Anaconda 3 (64-bit), Python 3.6.
1. First of all, download Basemap and Pyproj installation files according to your computer configuration and Python version. This website mainly provides Python Extension Packages under unofficial Windows environment
Basemap download address:
Pyproj download address:
Where, 1.1.0 after basemap represents the version number, cp36 represents python3.6, win represents Windows, and amd64 represents the 64-bit system. Basemap is about 120M, Pyproj is only about 3M.
2. Win +R opens the command prompt window, and the CD command sets the current directory to the folder where the download files are stored (I put it on the desktop) and then hits enter. Note: If you are using Spyder version 3.2 or above, please execute the following installation command on Anaconda Prompt (my_root), following the same steps.
3. Then start installing the two files, starting with Pyproj
PIP install pyproj 1.9.5.1 – cp36 – cp36m – win_amd64. WHL
Note that the full name of the file name and the suffix (.whl) cannot be lost, and the same command will install Basemap after successful installation
PIP install basemap – 1.1.0 – cp36 – cp36m – win_amd64. WHL
An error occurs here
You are using PIP version 9.0.1, however version 9.0.2 is available.
You should consider upgrading via the ‘python -m pip install –upgrade pip’ command.
The installation was successful using the easy_install directive:
, first go to the directory of easy_install such as C:\ProgramData\Anaconda3\Scripts
, then through the directive easy_install.exe PIP ==9.0.2 and finally install successfully.
And then install it
Successfully installing prompts you to install.
4. Then test whether the installation is successful
import numpy as np import pandas as pd import xarray as xy import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import os os.chdir(r'F:\NCEP') temp = xy.open_dataset('air.mon.mean.v401.nc') air = temp['air'] T30 = temp.sel(time=slice('1981-01-01', '2010-12-01')) t_average = T30.groupby('time.year').mean(dim='time') t = t_average.mean(dim='year') tmp = t['air'] lon = t['lon'][:] lat = t['lat'][:] lon, lat = np.meshgrid(lon, lat) def plt_map(data): m = Basemap(projection='mill', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, lat_ts=30, resolution='c') x, y = m(lon, lat) plt.xlim(-180, 180) plt.figure(figsize=(10, 7)) m.drawcoastlines() m.drawparallels(np.arange(-90., 91., 30.)) m.drawmeridians(np.arange(0., 361., 30)) m.drawmapboundary(fill_color='white') m.contourf(x, y, data, levels=np.linspace(-25, 30, 56), extend='both') plt.colorbar(orientation='horizontal', pad=0.05) plt_map(tmp)
Results:
Read More:
- Installing PyQt4 in Windows + Python 3.6
- Anaconda + vscode usage problem summary
- cannot import name ‘_validate_lengths’ from ‘numpy.lib.arraypad’
- Installing gensim in Anaconda
- In Python, import XXX does not report an error, but in IPython (Jupiter notebook)
- Data analysis to obtain Yahoo stock data: some problems are encountered when using panda datareader (cannot import name ‘is_ list_ Like ‘problem)
- To solve Anaconda error: command error out with exit status 1
- Importing the multiarray numpy extension module failed
- Installation of Python on MAC
- Finally solved the importError: DLLload failed: the specified module could not be found when import matplotlib.pyplot
- [error reported] [Python] [Matplotlib] importerror: failed to import any QT binding
- Package summary of installing python with CONDA
- Pychar configures Anaconda environment
- fatal error: Python.h: No such file or directory compilation terminated.
- [Python error] using PIP / easy under Windows_ Fail error in launcher: unable to create process using
- Installing flash in MAC environment
- CONDA creating virtual environment and common CONDA commands
- Importerror: the perfect solution of no module named CV2!!! (not too good)
- On the problem of from PIL import image
- ImportError: numpy.core.multiarray failed to import | https://programmerah.com/installing-the-basemap-package-in-anaconda-13795/ | CC-MAIN-2021-17 | refinedweb | 736 | 51.04 |
On a Wednesday in 2020, Michal Privoznik wrote: >Functions that create a device node after domain startup (used >from hotplug) will get a list of paths they want to create and >eventually call qemuDomainNamespaceMknodPaths() which then checks >whether domain mount namespace is enabled in the first place. >Alternatively, on device hotunplug, we might want to delete a >path inside domain namespace in which case >qemuDomainNamespaceUnlinkPaths() checks whether the namespace is >enabled. While this is not dangerous, it certainly burns a couple >of CPU cycles needlessly. > >Check whether mount namespace is enabled upfront. > >Signed-off-by: Michal Privoznik <mprivozn at redhat.com> >--- > src/qemu/qemu_domain_namespace.c | 39 ++++++++++++++++++++++++++++---- > 1 file changed, 35 insertions(+), 4 deletions(-) > Reviewed-by: Ján Tomko <jtomko at redhat.com> Jano -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 488 bytes Desc: not available URL: < | https://listman.redhat.com/archives/libvir-list/2020-July/msg01681.html | CC-MAIN-2022-21 | refinedweb | 144 | 54.73 |
User Details
- User Since
- Feb 1 2020, 6:09 AM (71 w, 13 h)
Mar 29 2021
Chiming in: they specifically refer to mmCOMPUTE_USER_DATA_0 and mmSPI_SHADER_USER_DATA_{STAGE}_0, which are in the public chip register offsets (not anywhere in LLVM right now, but present in PAL, Mesa, and any public chip register spec). I don't think we should explicitly define those values here, but using those names might make it a bit more specific and easier to find.
Oct 15 2020
Belated 'sounds good to me'.
Sep 21 2020
I'd be very surprised if any of the tests included in this change pass with that line commented.... it's meant so that things like #if and #else properly separate alignment after the first preprocessor run, where the whitespace manager doesn't have the full context of things between it.
Sep 13 2020
After looking at more of the history (ie, the commit you referenced), I'd definitely be open to something like this, provided that it doesn't affect namespaces that reside completely on one line. Since it was mostly a clang-format limitation and relatively rare, I think we can change the default here, but that's not up to just me (+@MyDeveloperDay), and extra scrutiny is definitely required when changing existing tests.
Sep 12 2020
Sorry on the delay, LGTM too.
Sep 8 2020
Sep 7 2020
I can see the use of this, but I am also wary that ignoring style options will lead to people producing different results on different versions of clang-format. This is both because having set-or-unset an option will naturally lead to different code and also that newer options are a de-facto check that clang-format is at least a certain version (we have minor differences between major versions as bugs are fixed). In any case, I see this being *very* easy to misuse and the documentation should have a warning reflecting that.
Aug 27 2020
LGTM, again assuming tests pass locally (patch did not resolve).
LGTM, assuming tests pass (automated checks failed to resolve your patch since you based it off of your other one). Looks like enabling C99 should have no other effects, right?
LGTM. Wait a bit to give others a chance to chime in before submitting.
Aug 26 2020
Agreed that this is a very nice solution for this case. LGTM too assuming it passes @MyDeveloperDay's tests.
Aug 23 2020
Aug 17 2020
Reviving this since it looks perfectly fine to me (from my limited commit history in git-clang-format :P), is useful, and there's no good reason for it to be stalled.
Jul 18 2020
Jun 29 2020
Jun 26 2020
Thanks for the fast review, @curdeius, and thanks for mentioning PP_STRINGIZE and BOOST_PP_STRINGIZE too!
Address feedback (nits, better docs, more defaults)
Jun 25 2020
May 28 2020
Great idea on this! I may borrow this idea and make something similar for some migrations I'm working on.
May 25 2020
May 24 2020
May 23 2020
May 22 2020
I'm a fan of the 'like' helpers, but I'm not entirely convinced that having helpers for languages covered by the 'like' is a bad thing-- it just needs to be very explicit that you do mean only that language. For example, an 'isObjCOnly()' would hint to reviewers that ObjC is sometimes used in combination with other languages and there may be a more appropriate helper (of course, this should be clearly documented as well).
May 20 2020
LGTM
Just belatedly caught something: Webkit style is supported too but not listed here. Can you add that?
May 19 2020
+1 for this idea. It'd eventually be neat to also take all samples from the style guide of each project and test them, if there aren't licensing concerns.
Hey @MyDeveloperDay, can I get your assistance committing this when you have the chance?
Can I get your assistance committing this?
Reformat with a newer clang-format
LGTM assuming CI tests pass.
May 18 2020
This is a great improvement in readability. I think this will get in here before it does for clang proper :D
I mainly have concerns with the search for noexcept being too brittle and not looking far enough back. Implementing that may have performance implications though, so I have no issue ignoring that problem if it's proven sufficiently rare.
Good idea, feel free to incorporate anything about the change (eg, tests and TT_BitFieldColon) or delegate to me if you like.
LGTM
Ironically, I independently made a near-identical change because my codebase needs this, and was going to upload it today. I won't post it now, but I stuck a copy on github if you're interested:. I also have some more tests there, and will cross-check with this once the merge conflicts are fixed.
May 15 2020
Rebase to fix merge conflict
Add a comment explaining why checking IsInsideToken is needed here.
May 13 2020
One spelling nit, but otherwise looks good to me.
Thanks for the commit and review @MyDeveloperDay!
May 11 2020
Hey, @MyDeveloperDay, can I get your assistance in committing this? It's probably been long enough for anyone to chime in.
May 6 2020
Mind looking again? They did add one later on I think. It helped a lot since the exact settings and whitespace to trigger this are really finicky (though reproducible). You're right that it won't reproduce without it.
May 5 2020
The failing case in this commit looks like the following after formatting (with alignconsecutiveassignments and a specific column limit)
Sure, I'll get started on that. It mainly comes from charging headfirst into the edge cases, but I think I have a decent grasp of clang-format internals now, and I'm definitely interested in both contributing to and reviewing for it.
@MyDeveloperDay, you're right about what this issue addresses: it surprised me a lot when an unrelated edit caused something to 'randomly' add spaces elsewhere, since it's in a different ifdef block (whether or not it has the same condition). The code that's aligned should always be across lines that are visually consecutive, and those ones weren't (in most cases, they aren't even logically consecutive). | http://reviews.llvm.org/p/JakeMerdichAMD/ | CC-MAIN-2021-25 | refinedweb | 1,051 | 67.89 |
Details
- Type:
Bug
- Status: Open
- Priority:
Major
- Resolution: Unresolved
- Affects Version/s: 0.1
- Fix Version/s: None
- Component/s: Python - Compiler
- Labels:None
- Patch Info:Patch Available
Description
Esteve's last change to how default values are stored broke stuff. Here is a quick example:
{{
service Test
}}
generates
{{
class get_slice_args:
thrift_spec = None
def _init_(self, start=thrift_spec[-1][4],):
self.start = start
}}
which is obviously invalid.
I'm not sure how thrift_spec is supposed to be populated here so I'm unsure how to fix this.
Issue Links
- is related to
THRIFT-105 make a thrift_spec for a structures with negative tags
- Open
Activity
- All
- Work Log
- History
- Activity
- Transitions
Although I'm happy to admit any breakage I cause
I don't think this issue is valid (or at least, not for the reasons exposed). Note that you're not using a field key, and thus the thrift_spec variable is not populated at all. You can fix this using a positive field key:
service Test{ bool get_slice(1:i32 start = -1), }
which should generate this code:
class get_slice_args:
thrift_spec = (
None, # 0
(1, TType.I32, 'start', None, -1, ), # 1
)
I think the compiler should abort if it doesn't find a valid field key and don't generate any code, though.
i thought the field keys are supposed to be optional, which is good, because they fuglify things up quite well.
I spoke too early, it seems my patch DID actually break things
Here's the code that an old compiler generates:
thrift_spec = None
def _init_(self, d=None):
self.start = -1
if isinstance(d, dict):
if 'start' in d:
self.start = d['start']
so, unless we always generate thrift_spec or we use a sentinel, I don't know if this can be fixed. However, I wonder how the fastbinary extension could work if thrift_spec is None. I can change the compiler to generate the thrift_spec variable no matter what, but would like to hear the opinion of others.
Argh, I just realized that even if we always generated the thrift_spec variable, it wouldn't work as it would try to access thrift_spec[-1]
It's quite late here, so I'm probably asking something stupid, but why is thrift_spec a tuple? Using a dict keyed on field keys, would allow the fastbinary extension to support negative field keys, IMHO. But I'm sure there must be a reason why it isn't, apart from dictionaries being mutable. I wish we could use named tuples in Python 2.4 and 2.5
THRIFT-105 is slightly related to this, so Alexander can explain the problem with negative field keys much better than I.
I think it was a tuple for performance reasons. I just thought of a way that we might be able to simplify both this issue and THRIFT-105. tuples can take negative indexes (indices?) just like lists, and they are counted from the end. What if we just extended the thrift_spec tuple so that all of the negative fields were in the right place (after all of the positive fields)? So if you had a struct like
struct foo { i32 bar; i32 baz; 2: i32 qux; }
then the thrift_spec would look like
( BLANK, # 0 aka -5 BLANK, # 1 aka -4 spec_for_qux, # 2 aka -3 spec_for_baz, # 3 aka -2 spec_for_bar, # 4 aka -1 )
This would not disturb the existing thrift_spec fields at all, so the current fastbinary extension would work fine. It should be robust against adding new negative fields to the end, since the indexes (indices?) of the existing fields will not change. I think it would make the patch for THRIFT-105 a lot simpler too, though we might need a little bit of magic to make sure that negative indexes work in the C code.
Thoughts?
This patch should fix this issue, I tested it using both the Python-only binary protocol and the native extension. This should fix THRIFT-105 as well.
Argh, I forgot to add the changes I made to fastbinary.c in the previous patch, here they are.
I implemented it the way you suggested David, the changes to fastbinary.c were minimal and the compiler got a bit simpler. I've tested it, but it needs a review
This looks awesome. There is one thing that I'm a little uneasy about, though, which is that (in my example), a field with id 3 (which should be skipped) would be treated as -2 instead. I think the only solution for this is to provide some extra info to the extension, specifically the maximum expected positive field id, and use that to skip over anything larger.
Thanks! I think that information could be stored as the first member of the thrift_spec tuple (key 0), as it's already empty. It shouldn't take too much work (as it's already in the sorted_keys_pos variable). What do you think?
function result structures use field 0, so how about a new attribute?
Ouch, you're right. A new class attribute (e.g. thrift_tag_limits) for storing maximum and minimum field keys sounds good, but I worry we might end up having too many attributes in the future and I'd like to keep all this information in a single attribute. Anyway, I think I can implement it in a relatively short time.
This patch adds some checks on lower and upper field keys using a new attribute called thrift_limits, I tested it both with the native extension and the Python-based binary protocol
Doesn't fix anything, but makes the compiler source code a bit simpler and cleaner.
Something isn't right here. I think it has to do with resetting the sorted_key_pos inside the inner loop.
For this structure...
struct AllPos { 2: i32 foo; 3: i32 bar; }
I get this output...
thrift_spec = ( None, # 0 None, # 1 (2, TType.I32, 'foo', None, None, ), # 2 None, # 0 None, # 1 None, # 2 (3, TType.I32, 'bar', None, None, ), # 3 )
Fixes repeated fields in thrift_spec
Fixes an issue that with negative field keys, all tests pass.
I had to rewrite my latest patch to fix structures with negative field keys, if they end with something lower than -1 For example, the ThriftTest.testException method generated a thrift_spec like this:
thrift_spec = ( (-2, TType.STRUCT, 'err1', (Xception, Xception.thrift_spec, Xception.thrift_limits), None, ), # -2 )
which caused some errors (i.e. thrift_spec[-2] didn't exist)
It's not as clean or pretty as the previous patch
but it works.
The patch fix default values. The patch is depend on THRIFT-105 patch. The patch duplicate default values in constructor and thrift_spec. I found it far better compare to thrift_spec[xxxx][4].
The patch is small and (I believe) clean enough.
Esteve: We should be able to go back to patch #5 if my solution to
THRIFT-361 is accepted. Thanks for uncovering this bug!
Alexander: At the moment, I prefer the solution in Esteve's patch (I am also biased, because I tried to push him toward that implementation). The main reason is that it is very low impact. The old generated code will continue to work with the new extension and vice versa. This version allows you to simply index into the thrift_spec list with the field id and have it work (without having to add an offset). The limits are completely unnecessary as long as the data is assumed valid. Finally, it allows users to set a field to None in the constructor, overriding the default.
Alexander: I don't fully understand your patch. Actually, it breaks the compiler and default values are not properly handled. For example, given this structure:
struct Foo { 1:optional list<i32> l = [1,2,3,4], }
the code generated after applying your patch is:
def __init__(self, l=None): if l is None: l = [ 1, 2, 3, 4, ]
which is wrong, which makes it impossible to pass None as l to Foo. Also, it doesn't set self.l to l, but I guess it was just a slip. With the current behavior, the generated code is:
def __init__(self, l=thrift_spec[1][4],): if l is self.thrift_spec[1][4]: l = [ 1, 2, 3, 4, ] self.l = l
David: great! However, I think the thrift_limits variable is necessary because, as you pointed out, if we have a structure like the one you added, a field with id 3 would be treated as -2. So, if we had a newer version of that structure, which adds another field (with id 3), wouldn't it clash with the old version?
1. Oops... I have to sleep more. I've fixed the bug.
2. I can't imagine a scenario which makes you to pass None (instead of empty list/set/dict) to init. Can you give me one?
Using the aforementioned structure (Foo), if I want l (an optional member) to be None so that it's not serialized, it would still end up passing [1,2,3,4] to the underlying transport.
Actually, I don't know what's wrong with the current behavior. The problem is in how thrift_spec for negative field keys is being generated.
THRIFT-361 was applied. Does that mean we can apply patch #5 for this now, per David's comments above?
Esteve: Good call on 3 vs. -2.
Don't we also need to adjust type_to_spec_args in order to include the limits for nested structures?
Also, it is unfortunate that adding the limits broke compatibility with the old version of the extension module. It doesn't seem like it will be easy to maintain compatibility, so as long as we are breaking it, we might as well go wild. If you want to combine the field specifiers and limits into a single attribute, that would be okay.
Is this something we could/should commit in 0.1? If so we need to make a final decision today.
Another version of my patch + THRIFT-105.
Shooting for 0.1, if we get review.
I can be wrong, but Esteve's patch doesn't work with old generated code. I believe it's a problem (because we don't break backward compatibility in python library for 0.1).
The big chunk of my patch was reviewed by Mark Slee in THRIFT-105.
> I can be wrong, but Esteve's patch doesn't work with old generated code
I'm confused. The whole point of this ticket is so we can replace old, broken generated code with generated code that works. If you are regenerating what is there to not work with?
Personally I would be most comfortable to get Esteve's buy-in on whatever fix we go with since he was the author of the -242 patch IIRC.
The Esteve's patch tries to fix two (THRIFT-105 and THRIFT-339) issue.
The fix of fastbinary protocol requires three argument instead of two. The change breaks all old-generated code if you use fastbinary even if you hasn't got any fields with negative tags.
The fix from THRIFT-105 (oh, it was six months ago) works fine with old-generated code, but it makes natural fields order: (-1, 0, 1, 2). Esteve uses order (0, 1, 2, -1).
Negative field ids are deprecated, so this doesn't need to block the release.
My case does not deal with negative field ids. (In the example I gave, the field default is -1, not the field id.)
bool get_slice(i32 start = -1),
start has field id == -1
bool get_slice(1: i32 start = -1),
works fine
sync patch with head
I'm deprioritizing this for now because I'm not sure what the status is, or if there's a champion for it.
damn it, jira said {{ }} would monospace my code samples there.
at least they are short enough that it's still pretty clear what is going on. | https://issues.apache.org/jira/browse/THRIFT-339?focusedCommentId=12680113&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2015-22 | refinedweb | 1,981 | 72.76 |
Primitive Operations (PrimOps)
PrimOps are functions.
It would also be useful to look at the Wired-in and known-key things wiki page to understand this topic..
Note that if you want to create a polymorphic primop, you need to return (# a #), not a.
Implementation of PrimOps
PrimOps are divided into two categories for the purposes of implementation: inline and out-of-line.
Inline PrimOps
Inline PrimOps are operations that can be compiled into a short sequence of code that never needs to allocate, block, or return to the scheduler for any reason. An inline PrimOp is compiled directly into Cmm? by the code generator. The code for doing this is in compiler/codeGen/StgCmmPrim.hs.
Out-of-line PrimOps
All other PrimOps are classified as out-of-line, and are implemented by hand-written C-- code in the file rts/PrimOps.cmm. An out-of-line PrimOp is like a Haskell function, except that
- PrimOps cannot be partially applied. Calls to all PrimOps are made at the correct arity; this is ensured by the CorePrep?
A new and somewhat more flexible form of out-of-line PrimOp is the foreign out-of-line PrimOp. These are essentially the same but instead of their Cmm code being included in the RTS, they can be defined in Cmm code in any package and instead of knowledge of the PrimOp being baked into the compiler, they can be imported using special FFI syntax:
foreign import prim "int2Integerzh" int2Integer# :: Int# -> (# Int#, ByteArray# #)
The string (e.g. "int2Integerzh") is the linker name of the Cmm function. Using this syntax requires the extensions ForeignFunctionInterface, GHCForeignImportPrim, MagicHash, UnboxedTuples and UnliftedFFITypes. The current type restriction is that all arguments and results must be unlifted types, with two additional possibilities: An argument may (since GHC 7.5) be of type Any (in which case the called function will receive a pointer to the heap), and the result type is allowed to be an unboxed tuple. The calling convention is exactly the same as for ordinary out-of-line primops. Currently it is not possible to specify any of the PrimOp attributes.
The integer-gmp package now uses this method for all the primops that deal with GMP big integer values. The advantage of using this technique is that it is a bit more modular. The RTS does not need to include all the primops. For example in the integer case the RTS no longer needs to link against the GMP C library.
The future direction is to extend this syntax to allow PrimOp attributes to be specified. The calling convention for primops and ordinary compiled Haskell functions may be unified in future and at that time it the restriction on using only unlifted types may be lifted.
It has been suggested that we extend this PrimOp definition and import method to cover all PrimOps, even inline ones. This would replace the current primops.txt.pp system of builtin PrimOps. The inline PrimOps would still be defined in the compiler but they would be imported in any module via foreign import prim rather than appearing magically to be exported from the GHC.Prim module. Hugs has used a similar system for years (with the syntax primitive seq :: a -> b -> b).
Adding a new PrimOp
To add a new primop, you currently need to update the following files:
- compiler/prelude/primops.txt.pp, which includes the type of the primop, and various other properties. Syntax and examples are in the file.
- if the primop is inline, then: compiler/codeGen/StgCmmPrim.hs defines the translation of the primop into Cmm.
- for an out-of-line primop:
- includes/stg/MiscClosures.h (just add the declaration),
- rts/PrimOps.cmm (implement it here)
- rts/Linker.c (declare the symbol for GHCi)
- for a foreign out-of-line primop You do not need to modify the rts or compiler at all.
- yourpackage/cbits/primops.cmm: implement your primops here. You have to arrange for the .cmm file to be compiled and linked into the package. The GHC build system has support for this. Cabal does not yet.
- yourpackage/TheCode.hs: use foreign import prim to import the primops.
In addition, if new primtypes are being added, the following files need to be updated:
- utils/genprimopcode/Main.hs -- extend ppType :: Type -> String function
- compiler/prelude/PrelNames.lhs -- add a new unique id using mkPreludeTyConUnique
- compiler/prelude/TysPrim.lhs --.lhs
See also AddingNewPrimitiveOperations, a blow-by-blow description of the process for adding a new out-of-line primop from someone who went through the process.
Explanation of attributes
TBV (To be verified)
has_side_effects
default = False
out_of_line
default = False
Set to True if there is a function in PrimOps.cmm. This also changes to code generator to push the continuation of any follow | https://ghc.haskell.org/trac/ghc/wiki/Commentary/PrimOps?version=24 | CC-MAIN-2015-40 | refinedweb | 796 | 56.96 |
I have a programing question that reads: Write a functional decomposition and a C++ program that reads a time in numeric form and prints it in English. The time is input as hours and minutes, separated by a space. Hours arespecified in 24-hour time(14 is 2 pm, etc.), but the output should be in 12-hour AM/PM form. Note that noon and midnight are special cases. Examples:
Enter Time: 12 00
Noon
Enter time: 6 44
Six forty four AM
And it says that this program should provide ample opportunity to use Switch Statements.
So, I have used switch statements, plenty of them as you will see in the code, but I am not sure how to do the AM/ PM part. Should I use an while loop for the entire code. I believe my switch statements are correct, but I could be wrong. Also if you spot anything else wrong or weird with my code that would be great if you could let me know. Or should I use void functions to complete, I am somewhat lost. I think I have to use the get function. So I will try that, but I welcome all suggestions.
I am working in C++ with Pico Text editor. Thanks for all of your help, you are a big help. And I have not compiled it yet either because it is not complete.
#include <iostream> #include <string> using namespace std; int main () { int time; int minutes; int hours; int tens; cout << "Please enter a time in the 24 hour clock format: " << endl; cin >> time; if (time > 0000 && time < 1200) time = AM; else time = PM; switch (hours) { case '1' : case '13': cout << "One"; break; case '2' : case '14': cout << "Two"; break; case '3' : case '15': cout << "Three"; break; case '4' : case '16': cout << "Four"; break; case '5' : case '17': cout << "Five"; break; case '6' : case '18': cout << "Six"; break; case '7' : case '19': cout << "Seven"; break; case '8' : case '20': cout << "Eight"; break; case '9' : case '21': cout << "Nine"; break; case '10': case '22': cout << "Ten"; break; case '11': case '23': cout << "Eleven"; break; case '12': cout << "Noon"; } switch(tens) { case '20': cout << "twenty"; break; case '30': cout << "thirty"; break; case '40': cout << "forty"; break; case '50': cout << "fifty"; } switch(minutes) { case '1': cout << "one"; break; case '2': cout << "two"; break; case '3': cout << "three"; break; case '4': cout << "four"; break; case '5': cout << "five"; break; case '6': cout << "six"; break; case '7': cout << "seven"; break; case '8': cout << "eight"; break; case '9': cout << "nine"; break; case '10': cout << "ten"; break; case '11': cout << "eleven"; break; case '12': cout << "twelve"; break; case '13': cout << "thirteen"; break; case '14': cout << "fourteen"; break; case '15': cout << "fifthteen"; break; case '16': cout << "sixteen"; break; case '17': cout << "seventeen"; break; case '18': cout << "eighteen"; break; case '19': cout << "nineteen"; break; } cout << hours << " " << tens << " " << minutes << " " << time; return 0; }
Note: Tens are the tens of minutes. Should I use subfunctions?
Thanks again. | http://www.dreamincode.net/forums/topic/21443-c-switch-statement-program-problem/ | CC-MAIN-2013-20 | refinedweb | 495 | 77.71 |
.)
First, namespaces. A namespace is a set of User, Msg, and File objects that belong together. Each namespace gets its own hyperdatabase blob. Each namespace numbers objects separately. Each namespace has a unique name used as a prefix in designators. Thus, if I say [gpsd/msg23], I’m asking for the 23rd msg object in namespace gpsd. Everyone talking to a system system has, at all times, a current namespace. If I just say [msg23], I am designating the 23rd message object in my current namespace.
Why the slash? because, in the most general case, designators will be URIs – as, for example, []. Presto! There is now an internet-wide namespace of Roundup objects all of which can refer to each other!
No prize for guessing that a namespace is a project. I’ve actually done two things above – I’ve defined all the required semantics for multiple projects to coexist in a forgelike system, and I’ve created a way for projects to refer to each others’ data even if they’re not on the same machine. Both features will be sources of power.
The subtler thing about namespaces is that they are perfectly orthogonal to the system’s other primitive concepts. This will pay off huge in some ways I can already foresee and many that I cannot yet.
I think the design also needs a primitive object class to encapsulate repositories. But I may be wrong about that; I’m still considering it.
This will be fun to watch.
You work and think, I sit and listen.
Good stuff.
Thanks.
t.
I find it rather amusing that Roundup’s URL is roundup.sourceforge.net.
>I find it rather amusing that Roundup’s URL is roundup.sourceforge.net.
Roundup isn’t a forge., it’s a discussion-moderation system. But it would be a helluva platform to build a forge on.
Having lived in deeply rural parts of the country, the fact that “Roundup” is the most commonly applied general use herbicide is bemusing to me.
(You know you’re in farm country when nearly every local television ad from 6 PM to 9 PM is for Roundup and its competitors from roughly April through September.)
> Roundup isn’t a forge., it’s a discussion-moderation system. But it would be a helluva platform to build a forge on.
So would Google Wave…
>
Might it make more sense to make it
or even
so that you could potentially append further qualifiers as the system evolves?
Why? You already have a primitive object of ‘File’. You could have multiple instances of File-derived objects, each with a version attribute and other metadata such as owner, check-in timestamps, etc. The implementation could be version-system agnostic, with additional derived objects with attributes and methods necessary to support different version systems. Maybe it could even have its own version system backend, but I’m guessing that would probably be out of scope.
On that we are in 100% agreement. I’m very impressed with what I’ve seen so far. It’s a very clean object-oriented designing and infinitely extensible. There seems to be adequate separation between UIs and implementation, something which I think is key to any project like this.
From what I’ve seen so far, looks very nice. I like the datastore backend system, it seems that it wouldn’t be very hard to write new Roundup backends. It means that Roundup’s hyperdb can potentially run on top of <a href=""redis or MongoDB. This would meet all potential scaling requirements of a large forge system with no unneeded SQL overhead.
Looks good. The one thing it seems to cry out for is primitive support for versioning and history tracking, down at the file level. It could also use some more active and durable workflow support than simple reactive detectors. It doesn’t seem to be possible to implement something like “alert me when any issue goes unassigned for two days”.
(I’m unable to see a good design without commenting on how I’d change it. There should be support group meetings for people like me.)
Interesting.
The Roundup site has a broken link to the original Ka-Ping Yee project that motivated everything. You can find the original project details here
Thanks ESR for this whole illuminating thread on forges.
To me, it looks as though there are two possible ways to go:
1. Extend Roundup to become a fully-fledged forge – this is what you seem to be thinking of. Due to its flexibility and the interfaces, this is not so much of a data jail. Still, it would be necessary to actually fetch the data of the central site.
2. Take the concepts of Fossil, a scripting language (probably Python) to make it better maintainable, and one or all of the existing DVCS (git, mercurial, bzr, whatever) as underlying backend. The advantage of this approach is that all data of the project(s) is distributed right from the start. No data jail here.
Now, just as an idea, wouldn’t it be possible to even combine both of these approaches? Assume, Roundup would store its data not in a database, but in a DVCS repository instead.
On the main server of a project, the web interface can be used to write issues, etc.
Its repo can be cloned easily by a developer, who can then work on his clone – modify code, write issues, etc., ideally via a Roundup CLI. Given that he has the full repo, he can of course also easily set up his own local Roundup web server, and do it via web interface, if he feels like it.
When he pushes his changes back to the main server, a detector on the origin site will note that some things have been changed, so corresponding Emails can be sent out, etc.
Doesn’t that sound nice? Or am I missing something?
>Assume, Roundup would store its data not in a database, but in a DVCS repository instead.
Nearly two years later: I don’t think this is quite the right thing, though you are correct that the forge itself should be DVCS-like. I may blog about this shortly. | http://0-esr.ibiblio.org.librus.hccs.edu/?p=1359 | CC-MAIN-2017-47 | refinedweb | 1,039 | 73.58 |
QtGraphicalEffects not included in mac deployment
Hello.
I am trying to deploy a QtQuick app for the mac but macdeployqt seems to be skipping or missing the QtGraphicalEffects module in the final DMG file.
The DMG seems to build fine. When I mount the generated DMG and inspect the contents of the package, I see the Contents tree, which has 'Frameworks' and 'MacOS' sub-directories. The Frameworks directory does NOT contain QtGraphicalEffects.framework or any mention of QtGraphicalEffects.
When I try to run the app from the MacOS subdirectory of the package, an error is reported to the console:
qrc:/TopPanel.qml:2 module "QtGraphicalEffects" is not installed
Here is the command line I use to create the DMG:
./macdeployqt /Users/(me)/Projects/QtQuickProjects/build-(myapp)-Desktop_Qt_5_9_1_clang_64bit-Release/(myapp).app/ -qmldir=/Users/(me)/Qt5.9/5.9.1/clang_64/qml -verbose=1 -dmg
In my /Users/(me)/Qt5.9/5.9.1/clang_64/qml directory, the QtGraphicalEffects directory exists, along with all the other modules that are successfully included in the DMG file.
So, my questions are:
why isn't QtGraphicalEffects being included?
how do I go about including it into the deployment?
Thank you very much in advance.
Kind Regards,
Carlos
I think you are mis-using the -qmldir option, it should point to a folder where you have your own QML files.
It will parse them and detect what plugins to install.
- SGaist Lifetime Qt Champion last edited by
Hi,
Can you provide a small sample application that triggers that behaviour ?
@SGaist Yes, of course. And thanks for replying.
Here is a sample app that has the same effect:
import QtQuick 2.9 import QtQuick.Window 2.2 import QtGraphicalEffects 1.0 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") Rectangle { anchors.fill: parent gradient: Gradient { GradientStop { position: 0.0; color: "white" } GradientStop { position: 0.06; color: "#93A8B8" } GradientStop { position: 0.45; color: "#B9E1E5" } GradientStop { position: 0.55; color: "#B9E1E5" } GradientStop { position: 1.0; color: "#71859D" } } } }
I used the same macdeployqt statement and I get the same error message.
I think you are mis-using the -qmldir option, it should point to a folder where you have your own QML files.
It will parse them and detect what plugins to install.
- SGaist Lifetime Qt Champion last edited by SGaist
I missed the ending of your
macdeployqtcommand.
-qmldirmust indeed be pointed to your projects QML sources. | https://forum.qt.io/topic/90362/qtgraphicaleffects-not-included-in-mac-deployment | CC-MAIN-2022-27 | refinedweb | 400 | 60.21 |
Now that Visual Studio Beta2 has been available for a few weeks (see Rick’s earlier blog post) I hope you’ve had a chance to experiment with one or both of the concurrent containers that were introduced: concurrent_queue<T> and concurrent_vector<T>. These two containers are lock-free, and are used to avoid synchronization bottlenecks in parallel algorithms. As with all concurrency features, they come with a set of pitfalls that must be avoided. In this post I will focus on the concurrent_queue, its design, proper usage of its methods, and its use in some real scenarios.
From std::queue to concurrent_queue
It is enlightening to compare the concurrent_queue design against that of the standard C++ std::queue, the latter which is, of course, not concurrency-safe. The basic API of std::queue’s enqueue/dequeue functionality can be summarized as follows:
template<class T>
class queue
{
public:
void push(const T&);
size_type size() const;
T& front();
void pop();
};
Forgetting for the moment that std::queue, as implemented, is not concurrency-safe, we can first note that the enqueue portion of this API could be concurrency-safe. Enqueuing an item can be accomplished with a single call to push(), and this operation is atomic in that it is performed by a single method call, which means that the enqueued item will be added to the queue by the time push() returns.
However, the dequeue portion of this API is not, and cannot be, concurrency-safe because the dequeue operation on std::queue is not atomic; it requires three separate sub-operations: size(), front(), and pop().
if (q.size() > 0)
{
T x = q.front();
q.pop();
}
To safely dequeue an item we must first check to see if the queue is empty, to avoid dequeueing from an empty queue. Then we have to retrieve the value from the front of the queue. After we have the front item, we need to remove it from the queue by calling pop(). Concurrent enqueue and dequeue operations that occur after the call to size(), or after the call to front(), can result in unexpected behaviour. Here, for example, are three potential races that could play out:
- The internal implementation of std::queue could be corrupted, which would result in undefined behaviour, likely a crash.
- The result of (q.size() > 0) cannot be trusted if a concurrent push() or pop() occurs immediately afterward. If the queue was empty (q.size() == 0), a concurrent push could occur immediately after the check, which would cause the rest of this dequeue operation to be skipped when in fact there is an item on the queue. If the queue had a single element in it (q.size() == 1), a concurrent pop could occur immediately after the check, causing the queue to become empty; this pop() would fail because the queue is now empty, which in debug-mode would throw an assert dialog.
- Two threads might dequeue simultaneously. The first thread could retrieve the front item, and then get interrupted. The second thread could then run and retrieve the front item, which is the same item as the first thread. Assuming nothing else bad happens (see #1), both threads will have dequeued the same item.
Why is std::queue designed this way? Imagine that front() and pop() were combined into a single method and invoked as:
T x = q.pop(); // Hypothetical API
If the copy-assignment operator in type “T” throws an exception, the value dequeued would be lost forever. By separating the retrieval of the item from the queue from its removal from the queue, users can potentially recover from this situation. This separation makes std::queue’s API exception-safe, but concurrency-unsafe.
As we’ll soon see, concurrent_queue makes the dequeue operation concurrency-safe by making it atomic.
Concurrency-Safe Operations on concurrent_queue
The concurrent_queue is concurrency-safe with respect to the following concurrent operations:
- Enqueues concurrent with enqueues
- Dequeues concurrent with dequeues
- Enqueues concurrent with dequeues
These operations are internally synchronized using a lock-free algorithm. This allows concurrent_queue to perform much better than one implemented using coarse-grained locking.
Enqueue: The enqueue operation on concurrent_queue is straightforward, and identical to that of std::queue:
void push(const T& source)
This will push a source value onto the tail of the queue, synchronizing with other concurrent enqueue/dequeue operations.
Dequeue: Instead of three method calls to achieve a dequeue, the concurrent_queue’s dequeue operation is encapsulated in a single method, try_pop():
bool try_pop(T& destination);
Note that the name of the method is now try_pop(), which as its name implies, attempts to pop an item from the head of the queue. If the dequeue was successful, the dequeued value is stored in the “destination” parameter, and this method returns true.
We’ve seen that a separate check for queue emptiness prior to popping is subject to races. The concurrent_queue try_pop() method solves this issue by simply returning false if we attempted to pop from an empty queue. Note that this is not a failure, nor does it necessarily indicate an error in the program that calls it. Frequently, the correct action for callers of try_pop() is to retry when false is returned. I’ll talk about this further down.
I mentioned that std::queue’s dequeue operation was exception-safe but not concurrency-safe. Here, concurrent_queue’s dequeue operation is concurrency-safe, but not exception-safe. If the assignment operator of type “T” throws an exception, the dequeued value will be lost.
Concurrency-Unsafe Operations on concurrent_queue
The methods discussed here are not safe to call during concurrent push() and try_pop() operations. They are meant to be used only after all concurrent operations have completed.
empty: This method returns true if the container has no elements:
bool empty() const;
While this method is technically thread-safe (it won’t corrupt the state of the concurrent_queue), the value it returns isn’t terribly useful because the returned value might immediately become incorrect if a concurrent push() or try_pop() happens.
unsafe_size: As is clearly apparent from its name, this method is concurrency-unsafe.
size_type unsafe_size() const;
This method can produce incorrect results if it is called concurrently with push() and try_pop() operations. To understand why, it is necessary to understand a bit about how the concurrent_queue operates under the covers. There are 2 member variables in concurrent_queue that demarcate a sliding window that keeps (_Tail_counter - _Head_counter), and indeed this formula expresses exactly how unsafe_size() is computed. Now consider the following case:
- Assume for this example that _Tail_counter is 12, and _Head_counter is 10. The queue has 2 elements.
- Thread 1 calls unsafe_size(). It gets as far as fetching the value of “_Tail_counter” before it gets pre-empted. It has fetched the value 12.
- Thread 2 performs 5 push() operations followed by 5 successful try_pop() operations. _Tail_counter will now be 17, while _Head_counter will now be 15. The queue still has 2 elements.
- Thread 1 resumes and finishes computing unsafe_size(). It fetches the value of _Head_counter, which is 15. It is now going to subtract the new value of _Head_counter (15) from the old value of _Tail_counter (12) and return (12 – 15), or -3 as the queue size. But wait! The concurrent_queue’s “size_type” is an unsigned type, which means the actual value will be 4294967293, or, if you prefer, really really huge.
clear: It is not concurrency-safe to clear out the contents of the concurrent_queue during concurrent operations:
void clear();
If, after all concurrent operations are complete, you wish to ensure that the concurrent_queue is empty and that all its elements are destructed, you can call this method. The concurrent_queue destructor will also implicitly clear out all its elements.
Iteration: Iteration over a concurrent_queue is not thread-safe and all methods that return iterators are explicitly prefixed with the word “unsafe_”.
iterator unsafe_begin();
iterator unsafe_end();
const_iterator unsafe_begin() const;
const_iterator unsafe_end() const;
Iterating while concurrent push() and try_pop() operations are happening will yield undefined results (e.g. crashing). However, for debugging it can be useful to traverse any remaining elements in the concurrent_queue and dump them out, and that’s what these methods are for.
Using concurrent_queue for Producer-Consumer
The concurrent_queue is an ideal data structure for producer-consumer scenarios. In the following simplistic example, we schedule one task that pushes (produces) 1000 integers, and the main thread pops (consumes) those integers:
// Task that produces 1000 items
void ProducerTask(void* p) {
concurrent_queue<int>* pq = (concurrent_queue<int>*)p;
for (int i = 0; i < 1000; ++i)
pq->push(i);
}
void Producer_Consumer() {
concurrent_queue<int> q;
// Schedule a task to produce 1000 items
CurrentScheduler::ScheduleTask(ProducerTask, &q);
// Consume 1000 items
for (int i = 0; i < 1000; ++i) {
int result = -1;
while (!q.try_pop(result))
Context::Yield();
assert(result == i);
}
}
Note that the consumer must retry (spin) if the try_pop() operation fails. Since this simple example guarantees that the producer will enqueue 1000 items, a failure in the dequeue operation simply means that the consumer thread is outpacing the producer thread, and eventually the producer thread will catch up and enqueue an item. When retrying in this way, it is very important to call Context::Yield() inside the spin-loop, which cooperatively yields to any other runnable tasks, allowing the producer task an opportunity to run. To see why this is important, imagine running this code on a single-core machine. Without the Context::Yield(), the consumer will busy-wait for an item to appear on the queue, starving out the producer task. If the producer task is starved, the process live-locks.
Debugger Visualizations for concurrent_queue
The internal implementation data structures for concurrent_queue are very complex. If you want to explore the internals of it, have fun. However, when debugging a program, developers simply want to see the contents of the concurrent_queue, not its internal data structures. In Beta2 we have included debugger visualizers for concurrent_queue (and concurrent_vector) so that they appear like their corresponding STL data structures in the debugger’s watch window. Here’s a sample of what the Visual Studio debugger’s watch window would look like for a concurrent_queue<int> that contains the three elements 5, 7, and 9:
Summary
The concurrent_queue container was adapted from the concurrent_queue in Intel’s Threading Building Blocks (and a big “thank you” goes to Intel for collaborating with us and allowing us to modify their implementation). If you’re familiar with the TBB concurrent_queue, you’ll note quite a few API differences, mainly because TBB’s queue supports bounded/blocking operations. Intel and Microsoft collaborated on a new, non-blocking concurrent_queue, and you’ll see TBB’s concurrent_queue start to conform to that of the Concurrency Runtime starting in TBB 2.2.
We will soon follow up with another post that talks about concurrent_vector.
In the Producer-Consumer example, why does ProducerTask() take a void* as parameter? Is this necessary, or would concurrent_queue<int>* have worked?
ProducerTask takes a void* as a parameter because it is using the ScheduleTask API which takes a void* for the data and requires you to dereference that data; ScheduleTask is similar to a CreateThread or ThreadPool API in that respect. If the example had used a message block like Concurrency::call<T> or a task_group then this wouldn’t have been necessary.
I do not understand how a single call to function push() could be concurrency safe. Thread-A will have the old copy of the queue size, if Thread-B increments the queue size inside the push() just after Thread-A reads the old value for the queue size.
The concurrent_queue size has nothing to do with the push operation. Indeed as I indicated, computing the queue size is not a concurrency-safe operation. In that discussion above, I mentioned that the queue keeps two counters going: _Tail_counter is incremented for every push(), and _Head_counter is incremented for every successful try_pop(). At no time during the push() operation does the queue ever try to maintain a consistent view of the queue’s size. As far as push() is concerned, it only needs to exclusively reserve a "slot" into which the item will be enqueued, and it does this by atomically incrementing the _Tail_counter. A concurrent push() operation on another thread will never reserve the same slot, so the _Tail_counter will always accurately reflect the number of push() operations, those that have completed as well as those that are still in flight. | https://blogs.msdn.microsoft.com/nativeconcurrency/2009/11/23/the-concurrent_queue-container-in-vs2010/ | CC-MAIN-2017-39 | refinedweb | 2,069 | 50.57 |
Windows Live Messenger Connect: In parts one, two, three and four we looked at how the OAuth WRAP profile is implemented with Windows Live Messenger Connect. Part Four just got in to a tiny bit of code. This post goes deeper, finishes off the code to get a simple site to display some Windows Live Profile information. Importantly though, it continually references the protocol diagram at Figure 3 (part one) and aligns that with what the code is doing.
Remember from figure 3, step 11 (in part one) the callback handler has access to the same secret that is used at the management portal. Because we’re talking about a Microsoft web environment in this blog post, we’ll use an assembly that Microsoft provides as part of the SDK. It’s all packaged up for us. If you insist on some other technology, there are example callback handlers in Flash, Java, ASP.NET, PHP and Python available here.
We’ll use the supplied assembly from the SDK. First a reference needs to be made to it and then a couple of entries made in web.config.
Figure 8: Location of the OAuthWRAPCallback handler assembly – Microsoft.Live.AuthHandler.dll
In system.web add the following HTTP handler.
<httpHandlers>
<add verb="*" path="OAuthWrapCallback.ashx"
type="Microsoft.Live.OAuthWrapHandler, Microsoft.Live.AuthHandler"/>
</httpHandlers>
!--
code>
This associates the type, Microsoft.Live.OAuthWrapHandler within the Microsoft.Live.AuthHandler assembly with the path “OAuthWrapCallback.ashx”.
Next, add the following to web.config replacing the client secret and client id with the data you obtained when you registered your application at manage.dev.live.com and as shown in figure 2 of part one.
<appSettings>
<add key="wl_wrap_client_secret" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>
<add key="wl_wrap_client_id" value="00000000xxxxxxxx"/>
<add key="wl_wrap_client_callback" value=""/>
<add key="wl_wrap_sessionId_provider_type" value="AuthIntegration" />
</appSettings>
!--
code>
Notice the value of the callback handler – OauthWrapCallback.ashx. And then reference the example in the httpHandler section above to see how this is now handled by the assembly from the SDK.
Also notice the value of this key is the entire URL. When you registered your application, you provided this URL. The callback handler passes this value (in this case ) to Windows Live. Windows Live will check that the supplied URL matches the stored URL. This means you will need to ensure your application is running against that real URL – so make sure you set the domain portion of the Start URL to the correct value in Visual Studio. You can’t run it at localhost.
Figure 9: The Start URL needs to have the domain portion set the same as the URL registered at manage.dev.live.com.
If the callback handler was running over SSL (and therefore the URL started “https”), the application would work at this stage. Most of us in the development environment are not running SSL – so you can see an additional line in appSettings called wl_wrap_sessionId_provider_type.
This references a class that provides a session ID as shown below:
public class AuthIntegration : Microsoft.Live.ISessionIdProvider
{
public string GetSessionId(System.Web.HttpContext context)
{
return context.Session.SessionID;
}
}
!--
code>
This session id is needed in the page you created with the wl: controls in part four. I left a little bit unexplained with this line:
callback-url="/OAuthWrapCallback.ashx?wl_session_id=<%= Session.SessionID %>"!--
code>
You can now see where the session ID comes from. It’s used for the callback handler and all the java libraries to keep track of things.
If you now press F5 and run the application – you’ll get something like this: after you’ve authenticated through the Windows Live Consent UI:
Figure 10: Running the application to retrieve the Live data
Steps 8 through 17 of figure 1 (in part one) are now completed. You added the callback handler which meant your application could retrieve the verification code and then add to it the client secret and pass it back to Windows Live. Windows Live verified the code and the secret, saw it had issued that verification code and that your application also knew the previously generated client secret. With Windows Live now being very assured that your application is genuinely what it purports to be, it generated the refresh token the access token and the lifetime and passed that back. The callback handler then used channel.html to turn the token data in to cookies.
The <wl:userinfo/> tag caused the javascript downloader to bring in enough javascript libraries to parse the cookies and generate a request to the Windows Live API Service with the access token in the header. You may have noticed a delay between the successful authentication in the consent page and the rendering of the Windows Live information in the userinfo tag. The delay is caused by not only the request for the data, but the amount of javascript that has to be downloaded to achieve the task. It’s the same when the page loads for the first time – you may have noticed a delay before the “Connect” button is rendered. Loader.js has a lot of work to do…. You’ll now understand the reason the javascript libraries have been minimised, simply to improve load times.
I hope you found this series of posts interesting in that they told you not only what code to use but also what the code was doing at a protocol level. Now that you have an understanding of OAuth WRAP – you’re in a great position to start playing around with Windows Azure and the Access Control Service in AppFab!!!!
If you want to follow along exactly – I used the walkthrough samples as the basis for the description of the protocol. They take things a little further but unfortunately there is no description of how the code is driving the OAuth WRAP profile behind it all. These posts should have given you a real leg up to understanding that – I hope…
I’ve actually wrapped the whole five articles up in to a pdf doc you might find interesting as a reference.
click the image above to read the entire set of 5 posts as one pdf document.
Planky | http://blogs.msdn.com/b/plankytronixx/archive/2010/09/24/it-s-not-about-what-we-have-it-s-about-what-we-share-that-counts-part-five.aspx | CC-MAIN-2015-48 | refinedweb | 1,020 | 63.09 |
#include <AnnexBread.h>
Definition at line 53 of file AnnexBread.h.
Create a bytestream reader that will extract bytes from istream.
NB, it isn't safe to access istream while in use by a InputByteStream.
Side-effects: the exception mask of istream is set to eofbit
Definition at line 65 of file AnnexBread.h.
returns true if an EOF will be encountered within the next n bytes.
Definition at line 87 of file AnnexBread.h.
return the next n bytes in the stream without advancing the stream pointer.
Returns: an unsigned integer representing an n byte bigendian word.
If an attempt is made to read past EOF, an n-byte word is returned, but the portion that required input bytes beyond EOF is undefined.
Definition at line 123 of file AnnexBread.h.
consume and return one byte from the input.
If bytestream is already at EOF prior to a call to readByte(), an exception std::ios_base::failure is thrown.
Definition at line 135 of file AnnexBread.h.
consume and return n bytes from the input. n bytes from bytestream are interpreted as bigendian when assembling the return value.
Definition at line 153 of file AnnexBread.h.
Reset the internal state. Must be called if input stream is modified externally to this class
Definition at line 77 of file AnnexBread.h.
Definition at line 169 of file AnnexBread.h.
Definition at line 170 of file AnnexBread.h.
Definition at line 168 of file AnnexBread.h. | http://hevc.info/HM-doc/class_input_byte_stream.html | CC-MAIN-2019-22 | refinedweb | 244 | 68.87 |
I have been using global variables for a little text game in python and have come across a lot of articles saying that global variables are a no no in python. I have been trying to understand how to get what I have below (just a health variable and being able to change it and print it) working using classes but I am confused how I can converted something like this in a class. Any help, example, point in the right direction would be great.
Here is an example of me using variables.
import sys
import time
health = 100
b = 1
def intro():
print("You will die after two moves")
def exittro():
time.sleep(1)
print("Thanks for playing!")
sys.exit()
def move():
global health
global b
health -= 50
if health <= 51 and b >0:
print("almost dead")
b = b - 1
def death():
if health == 0 or health <= 0:
print("...")
time.sleep(1)
print("You died\n")
time.sleep(2)
print("Dont worry, this game sucks anyway\n")
exittro()
intro()
a = 1
while a == 1:
input("Press Enter to move")
move()
death()
class Test:
def __init__(self):
number = 100
def __call__(self):
return number
def reduceNum(self):
number -=10
def printNum(self):
print(number)
a = 1
while a == 1:
input("Enter")
Test.self.reduceNum()
Test.self.printNum()
import time,sys,random
#starting stats
playerhealth = 100
stamina = 100
hydration = 100
#avaliable controls
controls = {
"?" : "for help",
"move" : "to make a move",
"stats" : "to check current health status and other stats",
"rest" : "to rest and regain some stamina",
}
#introduction text
def intro():
print("\n\nWelcome, you must try to survive. Keep an eye on your health, you will die if your health reaches zero. Other factors affect how much health you lose each move, such as stamina. \nGood luck, you will need it!")
print("\ntype ? for help")
#outro text and sys exit
def outtro():
print("Thanks for playing!")
time.sleep(2)
sys.exit()
#current stats
def currents():
global playerhealth
global stamina
global hydration
print("\nHealth", playerhealth,"Stamina:", stamina, "Hydration", hydration)
def checks():
global playerhealth
global stamina
global hydration
if playerhealth > 80:
print("\nYou are in good Health")
elif playerhealth > 50:
print("\nYou are getting weaker")
elif 20 <= playerhealth <= 50:
print("\nYou are getting dangerously weak")
elif playerhealth < 20:
print("\nYou are near death")
def lowerhydration():
global hydration
hydration = hydration - 50
def lowerstamina():
global stamina
stamina = stamina - 20
def lowerhealth():
global playerhealth
global stamina
global hydration
if stamina > 60:
playerhealth = playerhealth -10
time.sleep(1)
elif stamina == 60:
print("\nWarning! Your stamina is low, Your health will now deteriorate quicker each move")
playerhealth = playerhealth - 20
time.sleep(1)
elif stamina < 60:
playerhealth = playerhealth - 20
time.sleep(1)
if hydration < 50:
print("\n You are thirsty")
time.sleep(1)
print("\nMove made...")
time.sleep(2)
#choose what to do
def makeamove():
a = 1
while a == 1:
command = input(">").split()
if len(command) == 0:
continue
if len(command) > 0:
verb = command[0].lower()
if verb == "?":
for key in controls:
print("type:", key + " - " + controls[key])
if verb == "stats":
currents()
if verb == "healthcheat":
global playerhealth
playerhealth = 100
print("Cheater! Your Health has been reset to full")
if verb == "move":
input("Press Enter to confirm move...")
a = 0
if verb == "rest":
global stamina
stamina = stamina + 25
print("You rested and regained stamina")
if stamina >100:
stamina = 100
else:
input("Press Enter to confirm move...")
a = 0
#Main game loop
def mainloop():
while (playerhealth>5) and (hydration !=0):
checks()
makeamove()
lowerstamina()
lowerhealth()
lowerhydration()
else:
print("Game Over")
playAgain = "yes"
while playAgain == "yes" or playAgain == "y":
intro()
mainloop()
playAgain =""
playAgain = input("Do you want to play again? (yes or y to continue playing, any other key to end the game): ")
else:
outtro()
I would avoid classes for this, as classes are generally slower. You could make the function return the new value for the
health variable.
I would also suggest making a main controller function to take the return value and apply it to other functions. This prevents global variables outside of a function's scope.
import time def intro(): print("You will die after two moves") def outro(): time.sleep(1) print("Thanks for playing!") # sys.exit() # You can avoid this now by just stopping the program normally def move(health): health -= 50 if health <= 51: print("almost dead") return health # Return the new health to be stored in a variable def death(health): if health <= 0: print("...") time.sleep(1) print("You died\n") time.sleep(2) print("Dont worry, this game sucks anyway\n") return True # Died return False # Didn't die def main(): health = 100 # You start with 100 health intro() while not death(health): # While the death function doesn't return `True` (i.e., you didn't die) ... input("Press enter to move") health = move(health) # `health` is the new health value outro()
If you want to use classes, you need to actually instantiate the class (Make a new object from it) by doing
instance = Test(). You also need to store variables as attributes of self (so
self.number = number) as any local variables are different from each other.
class Test: def __init__(self): self.number = 100 def __call__(self): return self.number def reduceNum(self): self.number -= 10 def printNum(self): print(self.number) a = 1 game = Test() while a == 1: input("Enter") game.reduceNum() game.printNum() # Or: print(game()) # As you've changed `__call__` to return the number as well. | https://codedump.io/share/oaomV1QjcdV6/1/converting-globals-to-class | CC-MAIN-2017-34 | refinedweb | 896 | 63.19 |
package Time::Seconds; use strict; our $VERSION = '1.3401'; use Exporter 5.57 'import'; our @EXPORT = qw( ONE_MINUTE ONE_HOUR ONE_DAY ONE_WEEK ONE_MONTH ONE_YEAR ONE_FINANCIAL_MONTH LEAP_YEAR NON_LEAP_YEAR ); our @EXPORT_OK = qw(cs_sec cs_mon); use constant { ONE_MINUTE => 60, ONE_HOUR => 3_600, ONE_DAY => 86_400, ONE_WEEK => 604_800, ONE_MONTH => 2_629_744, # ONE_YEAR / 12 ONE_YEAR => 31_556_930, # 365.24225 days ONE_FINANCIAL_MONTH => 2_592_000, # 30 days LEAP_YEAR => 31_622_400, # 366 * ONE_DAY NON_LEAP_YEAR => 31_536_000, # 365 * ONE_DAY # hacks to make Time::Piece compile once again cs_sec => 0, cs_mon => 1, }; use overload 'fallback' => 'undef', '0+' => \&seconds, '""' => \&seconds, '<=>' => \&compare, '+' => \&add, '-' => \&subtract, '-=' => \&subtract_from, '+=' => \&add_to, '=' => \© sub new { my $class = shift; my ($val) = @_; $val = 0 unless defined $val; bless \$val, $class; } sub _get_ovlvals { my ($lhs, $rhs, $reverse) = @_; $lhs = $lhs->seconds; if (UNIVERSAL::isa($rhs, 'Time::Seconds')) { $rhs = $rhs->seconds; } elsif (ref($rhs)) { die "Can't use non Seconds object in operator overload"; } if ($reverse) { return $rhs, $lhs; } return $lhs, $rhs; } sub compare { my ($lhs, $rhs) = _get_ovlvals(@_); return $lhs <=> $rhs; } sub add { my ($lhs, $rhs) = _get_ovlvals(@_); return Time::Seconds->new($lhs + $rhs); } sub add_to { my $lhs = shift; my $rhs = shift; $rhs = $rhs->seconds if UNIVERSAL::isa($rhs, 'Time::Seconds'); $$lhs += $rhs; return $lhs; } sub subtract { my ($lhs, $rhs) = _get_ovlvals(@_); return Time::Seconds->new($lhs - $rhs); } sub subtract_from { my $lhs = shift; my $rhs = shift; $rhs = $rhs->seconds if UNIVERSAL::isa($rhs, 'Time::Seconds'); $$lhs -= $rhs; return $lhs; } sub copy { Time::Seconds->new(${$_[0]}); } sub seconds { my $s = shift; return $$s; } sub minutes { my $s = shift; return $$s / 60; } sub hours { my $s = shift; $s->minutes / 60; } sub days { my $s = shift; $s->hours / 24; } sub weeks { my $s = shift; $s->days / 7; } sub months { my $s = shift; $s->days / 30.4368541; } sub financial_months { my $s = shift; $s->days / 30; } sub years { my $s = shift; $s->days / 365.24225; } sub _counted_objects { my ($n, $counted) = @_; my $number = sprintf("%d", $n); # does a "floor" $counted .= 's' if 1 != $number; return ($number, $counted); } sub pretty { my $s = shift; my $str = ""; if ($s < 0) { $s = -$s; $str = "minus "; } if ($s >= ONE_MINUTE) { if ($s >= ONE_HOUR) { if ($s >= ONE_DAY) { my ($days, $sd) = _counted_objects($s->days, "day"); $str .= "$days $sd, "; $s -= ($days * ONE_DAY); } my ($hours, $sh) = _counted_objects($s->hours, "hour"); $str .= "$hours $sh, "; $s -= ($hours * ONE_HOUR); } my ($mins, $sm) = _counted_objects($s->minutes, "minute"); $str .= "$mins $sm, "; $s -= ($mins * ONE_MINUTE); } $str .= join " ", _counted_objects($s->seconds, "second"); return $str; } 1; __END__ =encoding utf8 =head1 NAME Time::Seconds - a simple API to convert seconds to other date values =head1 SYNOPSIS use Time::Piece; use Time::Seconds; my $t = localtime; $t += ONE_DAY; my $t2 = localtime; my $s = $t - $t2; print "Difference is: ", $s->days, "\n"; =head1 DESCRIPTION: C<print ONE_WEEK-E<gt>minutes;> =head1 METHODS) =head1 AUTHOR Matt Sergeant, matt@sergeant.org Tobias Brox, tobiasb@tobiasb.funcom.com Balázs Szabó (dLux), dlux@kapu.hu =head1 COPYRIGHT AND LICENSE Copyright 2001, Larry Wall. This module is free software, you may distribute it under the same terms as Perl. =head1 Bugs Currently the methods aren't as efficient as they could be, for reasons of clarity. This is probably a bad idea. =cut | https://metacpan.org/release/Time-Piece/source/Seconds.pm | CC-MAIN-2021-21 | refinedweb | 504 | 63.73 |
Vim is an improved version of the Vi editor. It has evolved from its simple origins and is now a powerful cross-platform text editing tool that works from the command line and as a standalone GUI. The full potential of Vim becomes evident when using its plugins, and this article tells you how to install them.
Vim is an improved version of the Vi editor. Many Linux OSs support it by default. Vim is a lightweight, flexible and easy-to-use command line editor. Many developers do use Vim, but not always to its full potential.
Vim is much more powerful than we think. It has a variety of open source plugins that are available for free. Vim can be easily installed in your OS, for which you will need to know the basics.
For a better understanding of this article, the reader should be familiar with the basics of Linux and Vim.
Vimawesome.com provides all types of plugins. It shows the following six options:
- The first option is with regard to language, allowing you to select plugins for your language of choice.
- The second option is for completion, which gives you a plugin for code completion.
- The third option is code display, which gives you code colour display plugins.
- The fourth option is for colourful interface plugins.
- The fifth option is for commands—it gives you command related plugins.
- The sixth option provides you different utilities like a library for Vim, a plugin manager, code review, etc.
Installation
The following three different and simple steps are suggested for installing plugins for Vim.
1) Using Vandle
Clone the repository into ~/.vim/bundle/ by default:
$ git clone ~/.vim/bundle/Vundle.vim
Once you clone it, set up your ~/.vimrc file, as follows:
set nocompatible filetype off set rtp+=~/.vim/bundle/Vandle.vim call vundle#begin() # We are hadling vandle in vim. It is required for enable plugin in vim. Plugin ‘VandleVim/Vandle.vim’ # Write plugin names here. # Keep your plugins in between begin() and end() tag. # you have to give git repo to install plugins. Like: Plugin ‘tpope/vim-fugitive’ # If plugin is not on github then write it as: Plugin ‘L9’ call vundle#end() #Vandle plugin end tag # Required for Ignore plugin indent changes. filetype plugin indent on
To install the plugins, launch Vim and run PluginInstall.
You can install the plugins using the command line:
$ vim +PluginInstall +qall
PluginInstall is for the plugin install; append ‘!’ to the update or just click on PluginUpdate.
PluginList is for the plugin list. Append ‘!’ to refresh the local cache.
PluginSearch foo is to search for the foo plugin.
PluginClean confirms the removal of unused plugins. Append ‘!’ for auto-removal approval.
2) Using NeoBundle
Clone the repo in your directory, as follows:
git clone ~/.vim/bundle/neobundle.vim
Configure vimrc:
if 0 | endif if &compatible set nocompatible endif set runtimepath^=~/.vim/bundle/neobundle.vim/ call neobundle#begin(expand(‘~/.vim/bundle/’)) “ Let NeoBundle manage NeoBundle “ Required: NeoBundleFetch ‘Shougo/neobundle.vim’ call neobundle#end() “ Required: filetype plugin indent on “ If there are uninstalled bundles found on startup, “ this will conveniently prompt you to install them. NeoBundleCheck
Note: Don’t set the neobundle setting in .gvimrc!
You can install the plugins in the following two ways:
- Launch vim run: NeoBundleInstall
- Using the command vim +NeoBundleInstall +qall
3) Using Vim Plug
Clone it in your PC, as follows:
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
Set up the .vimrc file:
call plug#begin(‘~/.vim/plugged’) Plug ‘scrooloose/nerdtree’, { ‘on’: ‘NERDTreeToggle’ } Plug ‘tpope/vim-fireplace’, { ‘for’: ‘clojure’ } Plug ‘bling/vim-airline’, { ‘for’: [‘clojure’, ‘scheme’], ‘rtp’: ‘vim’ } call plug#end()
I recommend the use of Vim Plug as it is easy and simple to use.
Installation of NERDTree
Try to install NERDTree by using the Vim Plug configuration. With your plugins installed, restart Vim and type :NERDTree.
This gives the current directory window. NERDTree shows the current files in the Documents directory (Figure 1). You can shift between the tree and file using the Ctrl+ww keys.
By default, Vim has three modes (see Figures 2 to 4). Sometimes it is very difficult to identify which mode you are in. Vim Airline provides a colourful GUI. This not only helps you to identify the mode, but also to change the colour in different modes.
Connect With Us | http://opensourceforu.com/2016/11/impress-colleagues-awesome-vim-plugins/ | CC-MAIN-2017-26 | refinedweb | 720 | 67.96 |
Even more update on my Mix09 talk “building business applications with Silverlight 3”. Now for some brand new content – that just could not have been done before this release.
This demo will take the Application logic we created in my Mix09 talk and put a REST based web service head on it with ADO.NET Data Services.
This might be useful if an application starts as a simple RIA Application but later you discover that you want to add a more explicit services layer to enable a wide range of clients to access your application. Luckily all your investment in the server application logic continues to work.
Just to show off the point, we will then consume that from a WinForms applications. This extends your reach and headroom for using RIA Services even more!
The demo requires (all 100% free and always free):
- VS2008 SP1 (Which includes Sql Express 2008)
- Silverlight 3 RTM
- .NET RIA Services July ’09 Preview
Also, download the full demo files and check out the running application.
Start with the application where we left off in Part 4… In the the server project, let’s add a REST head to the DomainService. This will allow any arbitrary client to access the DomainService and gives us a chance to selectively control what gets exposed.
Then we customize the class that was created for us.
public class SuperEmployeeService : DataService<SuperEmployeeDomainService>, IServiceProvider
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule(“*”, EntitySetRights.All);
config.SetServiceOperationAccessRule(“*”, ServiceOperationRights.All);
}
Notice here i am using the “demo” mode with “*” and “All”.. Here is where you can control what aspects of the Domain are meant to be accessed via any client and which are really part of the Silverlight app. It is a best practice to list them explicitly.
Now I simply right click and view in browser.. We get the standard ADO.NET Data Services (Astoria) REST head. But rather than going directly against my database, I now have a formal way to add application logic.
We can even traverse the data via the standard astoria URL formats.
Again, notice all the calls are run through your DomainService so the application logic controls the access, shape and content of all the data here.
Ok – that is cool… but let’s do something more useful. How about building an WinForms client from this service. Notice this would work with WPF, Ajax or even any Java client!
Add a new WinForms application then add a service reference.
Oh, and Shawn Wildermuth, this Add Service Reference is for you! We talked about it at Mix and now here it is in the bits! Enjoy.
Now we add a little form..
And some simple code behind… We set up the proxy to Astoria..
SuperEmployeeDomainService context;
public Form1()
{
InitializeComponent();
context = new SuperEmployeeDomainService(
new Uri(“”));
context.MergeOption = MergeOption.AppendOnly;
}
Now we can just load the data…
private void loadButton_Click(object sender, EventArgs e){
var savedCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
var q = from emp in context.SuperEmployee
where emp.Issues > 10
orderby emp.Name
select emp;
dataGridView1.DataSource = q.ToList();
dataGridView1.CellEndEdit += dataGridView1_CellEndEdit;
Cursor.Current = savedCursor;
}
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var row = dataGridView1.Rows[e.RowIndex].Cells;
int empId = Convert.ToInt32(row[“EmployeeId”].Value);
var q = from emp in context.SuperEmployee
where emp.EmployeeID ==empId
select emp;
var employee = q.FirstOrDefault();
employee.Gender = row[“Gender”].Value as string;
employee.Issues = Convert.ToInt32(row[“Issues”].Value);
employee.LastEdit = DateTime.Now;
employee.Name = row[“Name”].Value as string;
employee.Origin = row[“Origin”].Value as string;
employee.Publishers = row[“Publishers”].Value as string;
employee.Sites = row[“Sites”].Value as string;
var savedCursor = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
context.UpdateObject(employee);
context.SaveChanges();
Cursor.Current = savedCursor;
}
Here we just handle the event when the cell is done being edited.. Then we find employee that is object that corresponds to this row and update its values.
Again, this same pattern would work for any client that works with Astoria today..
Thats cool Brad – you’re making all this coding lark a bit too easy for us developers 🙂
When are you going to do a blog that tells us how to mix RIA, Forms Authentication (using a custom membership provider) and Prism v2 (Modularity)?
p.s. thanks for replying to my silverlight forum question (RIA Services as Data Services???)
This post is awesome! Thank you!
"Again, notice all the calls are run through your DomainService so the application logic controls the access, shape and content of all the data here. "
I’m not seeing DomainService here ? I think I missed something Brad ?
Sure, look back up at the declaration of that class that defines the Astoria services:
public class SuperEmployeeService : DataService<SuperEmployeeDomainService>,
Notice that you see it is of type SuperEmployeeDomainService… this is the place you would ordinarily put your EFModel… But instead we put our DomainService class where you can filter, aggregate, and compose data however you’d like.
Does that help?
I like the REST style service, also WCF will give a toolkit based on REST. Hope they will release soon.
Hi brad,
The article is noce. Can you please tell where you have updated the article for using RIA services ?
Thanks,
Thani
Brad,
In your example you have a specific item template called ‘Domain ADO.Net Data Service’ as well as a ‘ADO.Net Data Service’.
I don’t have the option of choosing a Domain ADO.Net Service 🙁
Now with .Net RIA Services, there is yet another option for the middle tier for Silverlight. What are your thoughts on when to use .Net RIA Services vs WCF (Basic HTTP Binding/Binary Binding) vs ADO.Net Data Services for Silverlight & WPF Apps.
Forget my last comment – found it DOH
As with Scott, I didn’t realize the new project type 🙂
Very cool – thanks Brad
Kiran – Think of RIA Services as just a layer on top of WCFAstoria…. So eventually all the goodness of WCF will just shine right through.. As far as when to use what, I’d use WCFAstoria directly when you are building a service and use the RIA Services layer on top when you are building a Silverlight application.
Does that help?
I hope you can render this app in vb, it’s not so useful to approx half of us in c#.
Also, I am not able to run the downloaded solution. It fails on the db. I have sql server 2005 express and sql server 2008 std installed. I think it expects sql server 2008 express. I’ve not been able to find a way around this yet.
What are the Deployment requirements for .NET RIA. Will all browsers be supported. Are there any client side installs or requirements??(Like IE7.0 or higher)?
please advice.
thank you
I’m with Bell…I cannot get the example running and have the same db issue and installs of sql server…
The documentation for RIA Services says:
"- Every public property on the server’s entity class name will be exposed by the entity proxy class " and has a footnote clarifying:
"Except for properties whose type would not be available on the Silverlight client, such as DAL-specific types"
I have a DAL layer that has plenty of DAL-specific types (Dictionaries mostly), but I still get a compiler error (I assume during the RIA code generation process) of:
"C:Program FilesMSBuildMicrosoftSilverlightv3.0Microsoft.Ria.Client.targets(99,6): error : Entity ‘CL.DAL.EntityClasses.UserEntity’ has a property ‘CustomPropertiesOfType’ with an unsupported type."
The Property definition is as follows:
public override Dictionary<string, string> CustomPropertiesOfType
{
get { return UserEntity.CustomProperties;}
}
How can I avoid this error? Astoria allows for an [IgnoreProperties] attribute. Is there something similar for RIA?
Thank you!
>> What are the Deployment requirements for .NET RIA. Will all browsers be supported. Are there any client side installs or requirements??(Like IE7.0 or higher)?
On the client all you need is Silverlight 3… that works with IE, FireFox, Chrome, and Safri… it works on Mac and Windows and with Mono it also works on Linux!
re the db issue – from what I’ve read some of us have issues because the mdf file based nw that comes with the download expects to be launched by sql server 2008 express. There may not be an easy workaround for this issue but it’d be cool to hear of one. Alternatively, could provide some guidance re switching the db refs to a nw db that’s running on sql server 2008 std? I have not tried any such workaround. I’m not sure that the EF config would survive the change…what approach would help the demo app surface in operational order?
Demo apps like you’ve created here are very very helpful for those of us that are trying to get a handle on all the new stuff coming out. A vb version would also be appreciated.
Yes — the DB issues sucks… I found that if I uninstall Sql Express 2005 and install Sql Express 2008 SP1 things work out fine.
THe good news is an upcomming posts gets ride of the database all together!
Brad,
In what circumstances should be use ADO .net services over WCF services?
ADO.NET Data Services is best when you exposing large chucks of data fairly directly… WCF is better if you are more operational and it is not simply CRUD… Does that help?
Also, WCF supports things like duplex and Binary formats, so if those are required, then you should use WCF.. I have examples of doing both in comming blog posts..
Maybe the no-db posts will work out ok. But frankly I never like demos that do not rely on an actual db for crud ops (xml file of something like that).
Couldn’t you just have the demo point to an installed copy of northwind? IE not a file that gets pulled in to the project? I don’t think anything you’re doing is sql server 2008 dependant, per se.
> Couldn’t you just have the demo point to an > >installed copy of northwind? IE not a file that gets >pulled in to the project? I don’t think anything >you’re doing is sql server 2008 dependant, per se.
Sure — if you just take the northwind.mdb file from the App_Data and host it in a SQL Server and change the connection string you should be good to go..
ok, I’m missing something obvious.
I have the latest updates to everything, using VS2008.
I have created an EntityModel and the Domain service:
public class KerdaService : LinqToEntitiesDomainService<KerdaEntities>.
Following the above instructions I created a web service:
public class WebDataService : DataService<KerdaService>, IServiceProvider.
and updated the InitializeService:
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
When I run the service i get this:
– <workspace>
<atom:title>Default</atom:title>
</workspace>
Nothing seems to be available?
Looking at the $metadata produces nothing as well.
What am i missing?
I’ve gone over the sample application and can’t seem to find anything out of place.
Is it a web.config setting? Property on the project.
Any help would be appreciated.
thanks
What does your KerdaService look like? Did you add a query method?
There are 16 Entities in the model.
The KerdaService was generated with all 16 Entities.
Each Entity has the standard Get,Insert,Update, Delete in the Service:
public IQueryable<Vendor> GetVendor()
{
return this.Context.Vendor
.Include("CountryISO3166_1")
;
}
public void InsertVendor(Vendor vendor) {
this.Context.AddToVendor(vendor);
}
public void UpdateVendor(Vendor currentVendor) {
this.Context.AttachAsModified(currentVendor, this.ChangeSet.GetOriginal(currentVendor));
}
public void DeleteVendor(Vendor vendor) {
if ((vendor.EntityState == EntityState.Detached)) {
this.Context.Attach(vendor);
}
this.Context.DeleteObject(vendor);
}
I have done as little as possible to get this to work. All the code is pretty much the same as when RIA generated it. I have generated the Metadata as well and attached Annotations, Include, Required and so on.
Do I need to annotate the methods in the service ?
Your example has no annotations in the service though, so I’m just lost.
thanks
Sorry, one more thing.
The Silverlight Application, what liittle i have done, is able to connect to the data.
ogreboy – that is odd…do you want to send me the project and I can debug? bradA@microsoft.com
thanks for your interest.
since I really only have much of a shell I am going to start over and regenerate everything again,
Mabey I did something i shouldn’t have.
When I get there I will try to insert the WebDataService and see what happens.
If my problem continues I will let you know.
thanks again
Brad,
Why is that when I created a plain Web App using ADO.Net Data Services template and a Domain Service as data source for the Data Service it does not expose any data?
GusG – I think you need to edit the service to say what entities to expose… You can use "*" for all if you’d like..
Once we have our data showing in the Domain ADO.Net Data service (in the view browser), how do we hook this up to RIA. I tried adding a Domain Service Class and the Available DataContexts/ObjectContexts only has the empty domain service class to select from. The Domain ADO Data service does not show up.. I might be missing something but i figured it would show up here.
Just noticed a gotcha when trying to put together this project myself. Be sure to include the correct version of the System.Data.Services dll from the path "C:Program FilesMicrosoft SDKsRIA Servicesv1.0LibrariesServerSystem.Data.Services.dll".
You need to use the RIA Services version of the DLL or your call to your domain service will return no entities :
<service xml:
<workspace>
<atom:title>Default</atom:title>
</workspace>
</service>
I’m having a problem implementing this. I have a working
DesignDataService : LinqToEntitiesDomainService<DesignRepositoryEntities>
that I can hit from my Silverlight application.
I’m attempting to add a Domain ADO.NET Data Service class:
WebDataService1: DataService<DesignDataService>, IServiceProvider
However, inside the call to GetService() when the serviceType parameter is of type {System.Data.Services.Providers.IDataServiceProvider}, I get a MissingManifestResourceException at the call to this.provider.GetService(serviceType):
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "System.Data.Services.Providers.DomainService.resources" was correctly embedded or linked into assembly "System.Data.Services.Providers.DomainService" at compile time, or that all the satellite assemblies required are loadable and fully signed.
Any clues? All of my RIA assembly references are marked with "copy local". My web app’s "bin" folder does not have any language specific subfolders. | https://blogs.msdn.microsoft.com/brada/2009/07/15/business-apps-example-for-silverlight-3-rtm-and-net-ria-services-july-update-part-5-astoria-add-service-reference-and-winforms/ | CC-MAIN-2017-13 | refinedweb | 2,454 | 58.58 |
Author: Kevin B. Kenny <[email protected]> State: Draft Type: Project Vote: Pending Created: 25-Oct-2017 Tcl-Version: 8.7 Keywords: assertion, pragma, type, alias, compilation Post-History: Tcl-Branch: tip-480
Abstract
This TIP proposes a new ensemble in the
::tcl namespace,
::tcl::pragma,
that will provide a place to install commands that make structural assertions
about Tcl code. Initially, two subcommands will be provided:
::tcl::pragma
type, which asserts that Tcl values are lexically correct objects of a given
data type, and
::tcl::pragma noalias, which describes the possible aliasing
relationships among a group of variables. The assertions are provided in an
ensemble, so that the set of available assertions can be expanded in the
future as additional opportunities are discovered to make useful claims about
program and data structure.
Motivation
Tcl, of course, is a typeless language: every value is a string. Moreover, it is an intensely dynamic language: the association of names with commands and variables is made very late, sometimes only when code is executed that searches for a variable by name.
Nevertheless, often a programmer's intention is to have values from a restricted set of strings, or to make restrictions on what names may address what variables. For instance, it may be known that a given piece of code is prepared to accept only numeric data, well-formed lists, Boolean values, or some other restricted type of data as its input.
Similarly, a great many programs that import variables using forms such as
global,
variable,
upvar,
namespace upvar, and the custom variable
resolutions of systems like TclOO cannot function correctly if two or more of
their variable names actually designate the same variable. A procedure like
proc collect {inputVar} { upvar 1 $inputVar inputs variable collection for {set i 0} {$i < [llength $inputs]} {incr i} { lappend collection [lindex $inputs $i] } }
will surely yield surprising results if called with
collection as its
parameter!
Giving the programmer the capability to specify restrictions on data types and alias relationships would have multiple advantages:
It documents what is expected. In particular, procedure, method and lambda parameters can have assertions about their structure early in a procedure, informing callers what preconditions must be met.
It fails early. Rather than having mistaken values or unexpected aliases run some way into a procedure and then fail mysteriously or even silently, it can yield an informative message at the first sign of a violated condition.
It aids with code optimization. While data type restrictions can be deduced by a compiler with considerable effort (1), making them explicit can still lead to more performant code. Alias restrictions are considerably harder to deduce, and the problem is Turing-complete in general. Unexpected aliases can be created at points in the program far remote from a procedure. Code like
uplevel #0 {upvar 0 ::path::to::variable ::some::other::thing}
will create an alias without any procedure accessing one or another of the variables being any the wiser.
Proposal
The
::tcl::pragma ensemble will be added. Initially, it will have two
::tcl::pragma type and
::tcl::pragma noalias.
tcl::pragma type
The
::tcl::pragma type command will have the syntax:
::tcl::pragma type typeName $value1 $value2...
In this usage, typeName is a description of the acceptable type of the given values. The values will be checked for whether they are instances of the given type, and a run-time error will be thrown if any value is not. Initially, the following types will be supported:
boolean: Indicates that the value is a Boolean:
0,
1,
off,
on,
true,
false,
yes,
no: in general, a value that will pass the test of
string is boolean -strict.
int32: Indicates that the value is an integer, small enough to fit in a C
intvalue on the current platform.
int64: Indicates that the value is an integer, small enough to fit in a
Tcl_WideIntvalue on the current platform.
integer: Indicates that the value is an integer, without constraint on its size.
double: Indicates that the value is representable as a double-precision floating point number (including the special values for Infinity and Not-a-Number).
number: Indicates that the value is representable as a number, which is the union of values accepted as an integer and values accepted as a double.
list: Indicates that the value is representable as a Tcl list. The elements of the list are not constrained.
dict: : Indicates that the value is representable as a Tcl dictionary. The keys and values of the dictionary are not constrained.
It is anticipated that further TIP's will be proposed that expand the available set of types. In particular, lists and dictionaries with constrained content types are foreseen as being useful things to include.
Note that this command operates on values, not variables. A command like:
::tcl::pragma type int $a
does not declare that
a is an integer variable, and does not require future
assigmnents to it to have the given type. It merely asserts that at the
current point in the program, the value of
a will be an integer small
enough to fit in a C
int.
One may think of this assertion as syntactic sugar for the longer codeburst:
if {![string is integer -strict $a]} { return -code error -level 0 "expected an integer but got $a" }
and in fact the bytecode compiler will be free to compile that, or similar code. (The description is slightly oversimplified, since other error options must also be manipulated.)
tcl::pragma noalias
The syntax for the
::tcl::pragma noalias command shall be:
::tcl::pragma noalias set1 set2...
In this usage,
set1,
set2, ... are lists of variable names. The syntax
expresses the assertion that variables that are mentioned in the call are not
aliases of each other at the time the command is executed, except that
variables in the same set are permitted to alias.
The most common usage will be simply to use singleton sets. For instance, the
collect procedure above might contain
::tcl::pragma noalias inputs collection
following the command
upvar 1 $inputsVar inputs
This command would have the effect of asserting that
inputs and
collection
designate distinct variables, avoiding strange behaviour of modifying the
inputs while an iteration is in progress.
It is possible for any combination of aliases to be permitted by including the
possibility on the command line. For instance to assert that
a may be an
alias of
b or
c, but
b and
c must not alias each other, the command:
::tcl::pragma noalias {a b} {a c}
might be used. (The program could specify, redundantly,
b and
c on the
command line, but the
noalias command will enforce that any variable
mentioned anywhere in its arguments is not aliased to any other, except as
specified.
As a final note, it is anticipated that
::tcl::pragma noalias {*}[info locals]
will be a common usage - most programs do not tolerate any unexpected aliasing at all. It is therefore further anticipated that this specific usage may receive special handling in the implementation.
As with
type,
noalias is an assertion of the state of the program at a
given point in the flow of execution. It does not establish a permanent
constraint. A subsequent command such as
upvar may change the aliasing
relation, and there will be no prevention of such a change.
It is worth noting that the necessary interfaces to implement this command are not yet available at the Tcl level at all. A Tcl script has no easy way to determine whether one variable is an alias for another. This command has no counterpart in today's Tcl.
A quick view may lead one to suspect that
noalias will require quadratic
time to check the relationships at runtime. In at least the common cases,
though, it is to be expected that
noalias will run in time O(N), where N
is the number of included variables. Instead of comparing all pairs, it will
be easier to maintain a hash table of variable addresses, and check for
collisions by looking for existing hash entries.
Discussion
The Naming of Names
An appropriate name for this ensemble is a difficult choice. A very early
draft of this proposal, circulated privately, suggested
::tcl::assume (since
it was seen as a claim that it is safe for a compiler to make a given
assumption). This name was roundly rejected by the reviewers. An alternative
that was counterproposed was
::tcl::assert. The disadvantage to the latter
name is that it is easy to imagine a piece of code wanting to
namespace
import both
::tcl::assert and
::control::assert leading to a name
collision. Moreover,
::tcl::assert does not take a Boolean expression but
rather a different sort of expression of a constraint. The similarity of the
names would therefore be confusing. In names, as in many other aspects of
life, "the good ones are already taken."
Runtime Behaviour
The assertions described in this TIP are not without cost at runtime. In an
interpreted environment, it may be desirable to control, on a per-namespace
basis, whether the assertions are enforced. In a compiled environment, many of
these assertions will either enable more aggressive optimization, be removable
themselves with appropriate analysis to prove they are unnecessary, or
both. For this reason, the proponent wishes to consider enabling and disabling
of structural assertions to be Out Of Scope at the present time. If it does
prove to be necessary, it can be done with a mechanism analogous to the way
that today's
::control::assert works.
References
- Kenny, Kevin B. and Donal K. Fellows. 'The State of Quadcode 2017.' Proc. 24th Annual Tcl/Tk Conf. Houston, Tex.: Tcl Community Association, October 2017. | https://core.tcl-lang.org/tips/doc/trunk/tip/480.md | CC-MAIN-2021-21 | refinedweb | 1,610 | 51.89 |
These are chat archives for FreeCodeCamp/HelpFrontEnd
hi guys, just wonder from the syntax :
import React from 'react'; import ReactDOM from 'react-dom';
how javascript find the exact library path?
because there is a kind of import syntax that specifies the file path to import to like below.
import Anything from '/folder/anything.js'
import Name from 'name';
namein the root of your directory, you can use
import Name from './name'
divnot
dive
Hi, I can't figure out why the
<a> element is overflowing a couple of pixels below the project images. I am also trying to get the
figcaption tags to fill in all remaining space in the
figure tag, but when I set the height to 100% it just stretches them to the bottom of the page
font-size: 0;on the
atag gets rid of it below the image, but my
figcaptionis still not filling the whole space below the image
figurethat has a set height of 360px, the only two elements inside the
figureare my
imgand
figcaption. If the
imgis set to fixed height of 320px, then that leaves me with 40px on the bottom. So surely if I set the height of my
figcaptionto 100% it should take all of the remaining space (If there is no margin/padding and I can't see any), is this right?
figcaptioncontainer starts a couple of pixels below the image and I can't find a way to get it so start just below it so that I would have 320px/40px split in the container between the image and the caption
I see...
As of June 11, 2018, you must enable billing with a credit card and have a valid API key for all of your projects. | https://gitter.im/FreeCodeCamp/HelpFrontEnd/archives/2018/08/04 | CC-MAIN-2019-04 | refinedweb | 291 | 68.44 |
Part 1. Debugging Python Code
Preparing an example.
Copy the following code into a file in your project (though it is recommended to type this code manually):
import math class Solver: def demo(self, a, b, c): d = b ** 2 - 4 * a * c if d > 0: disc = math.sqrt(d) root1 = (-b + disc) / (2 * a) root2 = (-b - disc) / (2 * a) return root1, root2 elif d == 0: return -b / (2 * a) else: return "This equation has no roots" if __name__ == '__main__': solver = Solver() while True: a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) result = solver.demo(a, b, c) print(result)
As you see, there is the
main clause here. It means that execution will begin with it, let you enter the desired values of the variables
a,
b and
c, and then enter the method
demo.
Placing breakpoints
To place breakpoints, just click the left gutter next to the line you want your application to suspend at:
Refer to the section Breakpoints for details.
Starting the debugger session
OK now, as we've added breakpoints, everything is ready for debugging.
PyCharm allows starting the debugger session in several ways. Let's choose one: click
in the left gutter, and then select the command in the pop-up menu that opens:
The debugger starts, shows the Console tab of the Debug tool window, and lets you enter the desired values:
By the way, in the Console, you can show a Python prompt and enter the Python commands. To do that, click
:
If your debug console is too short for the prompt icon to be visible, click
>>>.
Then the debugger suspends the program at the first breakpoint. It means that the line with the breakpoint is not yet executed. The line becomes blue:
On the stepping toolbar of the Debugger tab, click the button
, to move.
Refer to the sections Stepping Through the Program and Stepping toolbar for details.
Watching
PyCharm allows you to watch a variable. Just click
on the toolbar of the Variables:
Refer to the sections Debug Tool Window. Variables and Debug Tool Window. Watches.
Evaluating expressions
Finally, you can evaluate any expression at any time. For example, if you want to see the value of the variable, click the button
, and then in the dialog box that opens, click Evaluate:
PyCharm gives you the possibility to evaluate any expression. For example:
Refer to the section Evaluating Expressions.
You can also click the button
in the Debug console, and enter some commands that show the variables values. For example, with IPython installed, you can easily get an expression value:
Summary
This brief tutorial is over - congrats! Let's repeat what you've learnt from it:
- You've refreshed your knowledge of the breakpoints and learnt how to place them.
- You've learnt how to begin the debugger session, and how to show the Python prompt in the debugger console.
- You've refreshed your knowledge about the inline debugging.
- You've tried hands on stepping, watches and evaluating expressions.
The next step is intended for the Professional edition users - this is Debugging Django Templates. | https://www.jetbrains.com/help/pycharm/2017.2/part-1-debugging-python-code.html | CC-MAIN-2018-13 | refinedweb | 518 | 61.26 |
background
Use Python to operate a batch of images with the same resolution, and merge them into TIFF format files.
Because opencv is mainly used to read single frame TIFF files, it does not support multi frame files well.
Two useful packages are found: tiffcapture and tifffile. Both can be installed with PIP.
The former is mainly used to read TIFF files, while the latter is readable and writable. Finally, the TIFF file is selected to synthesize the TIFF image file.
Install tifffile
pip install tifffile
Principle and code
My picture is 8 bit grayscale.
After each read, first upgrade dimension:
new_gray = gray_img[np.newaxis, ::]
Then use it again np.append Add to the array. Each append is equivalent to TIFF adding a frame of picture.
tiff_list = np.append(tiff_list, new_gray, axis=0)
After all operations are completed, it will be saved to disk at one time.
tifffile.imsave( out_tiff_path, tiff_list )
Here is my complete code:
import cv2 import tifffile import time import numpy as np import time import os img_path = '../word_all' out_txt_path = '../out_word_all.box' out_tiff_path = '../out_word_all.tif' tiff_list = None with open(out_txt_path, 'wb') as f: dir_list = os.listdir(img_path) cnt_num = 0 for dir_name in dir_list: dir_path = os.path.join(img_path, dir_name) img_list = os.listdir(dir_path) pwd = os.getcwd() os.chdir(dir_path) for img in img_list: print('dir_path:{}'.format(dir_path)) gray_img = cv2.imread(img, cv2.IMREAD_GRAYSCALE) new_gray = gray_img[np.newaxis, ::] print('gray_img shape:{}, new_gray shape:{}'.format(gray_img.shape, new_gray.shape)) #global cnt_num if cnt_num == 0: print('cnt_num == 0') tiff_list = new_gray else: print('np.append') tiff_list = np.append(tiff_list, new_gray, axis=0) print('tiff_list shape:{}'.format(tiff_list.shape)) content = '{} 2 2 60 60 {}\n'.format(dir_name, cnt_num) print(content) f.write(content.encode('UTF-8')) cnt_num += 1 os.chdir(pwd) tifffile.imsave( out_tiff_path, tiff_list ) print('tiff_list shape:{}'.format(tiff_list.shape))
The above way to read and write the TIFF file in Python + tifffile is the whole content shared by Xiaobian. I hope it can give you a reference and support developer. | https://developpaper.com/how-to-read-and-write-tiff-file-in-python-tifffile/ | CC-MAIN-2021-43 | refinedweb | 330 | 62.24 |
Homework
Homework Questions? Ask a Tutor for Answers ASAP
Attachment: 2013-09-13_010035_capstone_1_lab_instructions.docx
I have it uploaded.
Hi John are you still with me. I am on my computer now?
Hi John
Attachment: 2013-09-14_023126_acctinfo.docx
Please let me know if you are able to see the attach file
Not a problem
Hi John,
I received the following error message:
AcctInfo-1.java:5: error: class AcctInfo is public, should be declared in a file named AcctInfo.javapublic class AcctInfo { ^1 error
Please advise
What IDE compiler are you using maybe that will help.
Jgrasp -- I am not able to get it to compile
Were you able to get it to compile
Attachment: 2013-09-18_220206_doc1.docx
Exception in thread "main" java.io.FileNotFoundException: AcctInfo.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.util.Scanner.<init>(Scanner.java:656)
I am still getting this error message
My question is with the above attachement, how do I write the program?
Attachment
Write a program that simulates customers waiting in line at a grocery store. Your program must use a Queue to represent the customer objects waiting in line. A Customer class is provided for you (download from Moodle). You must use that class, without alternations, for the creation of your Customer objects. You must analyze the class and use the provided methods to achieve the desired functionality of the program.The program should simulate 60 minutes of activity at the store. Each iteration of your program should represent one minute. At each iteration (minute), your program should do the following:• Check to see if new customers are added to the queue. There is a 25% chance that new customers show up (need to be added to the queue) every minute. This does not mean you should add a customer every four iterations, but rather each iteration should have its own 25% chance.• Update the customer object currently being serviced (if one exists). This will be the customer object at the front of the queue. If the customer has been completely serviced, remove them from the queue.During execution, your program should output the following information:• When a new customer is added to the queue, output, “New customer added! Queue length is now X” where X is the size of the queue after the new customer has been added.• When a customer has been completely serviced, output, “Customer serviced and removed from the queue. Quest length is now X” where X is the size of the queue after the customer has been removed.• At the end of each iteration (minute), output, “---------------------------------------------------“ to visually identify the passing of time.When your simulation ends, your program should also output the following information: Total number of customers serviced Maximum line length during the simulation
Sept. 26
ok thanks | http://www.justanswer.com/homework/7zt0b-write-program-reads-bank-account-information-contained.html | CC-MAIN-2017-13 | refinedweb | 482 | 66.94 |
I am attempting to create LineRenderers at runtime(when the user presses a button).
My Problem: I can never create more than one LineRenderer. When I go to created the 2nd one, the LineRenderer object is always NULL.
What am I doing wrong? Can you provide advice on what I need to do to create more than one LineRenderer?
public class AppInit : MonoBehaviour {
public Vector3[] TEST_VERTICES;
public const int SPEED = 5;
public List<LineRenderer> lines;
// Use this for initialization
void Start () {
TEST_VERTICES = new Vector3[10] {new Vector3(0,0,0), new Vector3(10,10,10), new Vector3(30,10,50), new Vector3(30,40,50),
new Vector3(10,30,90), new Vector3(10,20,40), new Vector3(50,20,40), new Vector3(70,80,90),
new Vector3(10,70,20), new Vector3(60,10,0)};
lines = new List<LineRenderer>();
}
// Update is called once per frame
void Update () {
float x = Input.GetAxis ("Horizontal") * Time.deltaTime * SPEED;
float z = 0;
float y = Input.GetAxis ("Vertical") * Time.deltaTime * SPEED;
gameObject.transform.Translate (new Vector3(x,y,z));
}
void OnGUI() {
if (GUI.Button (new Rect(10,10,100,20), "Create"))
createString(TEST_VERTICES);
}
public bool createString( Vector3[] vertices ) {
LineRenderer lRend = gameObject.AddComponent ("LineRenderer") as LineRenderer;
//LineRenderer lRend = new LineRenderer();
lines.Add(lRend);
Debug.Log ("IS NULL"+(lRend == null).ToString ());
lRend.SetColors (new Color(100,0,0,100), new Color(0,0,100,100));
lRend.SetWidth(10, 1);
lRend.SetVertexCount(vertices.Length);
for (int i=0; i<vertices.Length; i++)
lRend.SetPosition(i, vertices[i]);
return true;
}
}
Answer by Bunny83
·
Jun 15, 2012 at 09:24 AM
It should be possible to attach more than one linerenderer to one gameobject, but in your case all are drawing exactly the same... You set the exact same vertices array. It depends on the LineRenderer-useWorldSpace setting if the positions are relative to the objects position, so if you move the gameobject the line moves along, or relative to the world. In both cases your multiple lines will be exactly the same...
What do you want to achieve? a TrailRenderer?
btw, there is a generic version of AddComponent:
LineRenderer lRend = gameObject.AddComponent<LineRenderer>();
LineRenderer is a component. I'm pretty sure you can only have one LineRenderer per game object.
In the editor you can only attach one, and I just tried it in code, you can only attach one.
Also I recall it mentions it in the doc somewhere: but I can't find it
(Aside: in fact, is there a list or something of "components where you can attach only one to a game object" ? Eg Transform etc??)
Actually it says unclearly here
"to draw two or more completely separate lines, you should use multiple GameObjects, each with its own Line.
Multiple Cars not working
1
Answer
Distribute terrain in zones
3
Answers
Creating a LineRenderer: its always null
2
Answers
Merge paths
2
Answers
Cant figure out how to code this...
0
Answers | https://answers.unity.com/questions/267482/wont-allow-me-to-create-more-than-1-linerenderer.html?sort=oldest | CC-MAIN-2020-29 | refinedweb | 487 | 58.18 |
Can you show me how I can fill the board with 0s and 1s?
Can you show me how I can fill the board with 0s and 1s?
I understand what you are saying. Index are element - 1. I don't know how to go forward with filling the board with 0s and 1s in the 3x3 position. For example for each number of row and column such...
How do I randomly fill with 0s and 1s in the 3x3 board?
I am trying to display the board using JOptionPane and it is giving me an exception error - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
I have declared to generate a random number and assign to each row and column of the 3x3 array. I'm not sure if the below portion of the code is correct.
Random randomGenerator = new Random();
...
I am trying to create a 3x3 board using 2 dimensional array that randomly fills 0s and 1s into the board and finds the rows, columns, and diagonals with all 1s.
Please help!
Thank you
This is what I have so far and I obviously know it's not correct at all. This is my very first time writing something like this JOptionPane.
import javax.swing.JOptionPane;
public class...
Write a Java program that lets the user enter the loan amount and loan period in number of years and
displays the monthly and total payments for each annual interest rate starting from 3.5% to 8%... | http://www.javaprogrammingforums.com/search.php?s=1a49b4f5f349a1cab780691b7c76523e&searchid=837014 | CC-MAIN-2014-15 | refinedweb | 247 | 74.08 |
Kees Cook <kees.cook@canonical.com> writes:>.> PTRACE is not commonly used by non-developers and non-admins, so).>> This patch is based on the patch in grsecurity. It includes a sysctl> to enable the behavior via /proc/sys/kernel/ptrace_scope. This could> be expanded in the future to further restrict PTRACE to, for example,> only CAP_SYS_PTRACE (scope 2) or only init (scope 3).This is ineffective. As an attacker after I gain access to a userssystem on ubuntu I can wait around until a package gets an update,and then run sudo and gain the power to do whatever I want.Either that or I can inject something nasty into the suid pulse-audio.I tell you what. If you really want something effective, help Sergeand I finish getting the cross namespace issues fixed for the usernamespace. When complete, it will possible for an unprivileged processto create a new one, and since kernel capabilities along with everythingelse will be local to it, running pidgin, or firefox, or another networkfacing potentially buggy application in such a namespace will ensure thateven if the process is compromised it won't have privileges to ptrace anotherprocess or do much else on the system.Eric | http://lkml.org/lkml/2010/6/17/121 | CC-MAIN-2017-09 | refinedweb | 201 | 54.32 |
Barcode Software
qr code with vb.net
Terminal Server in .NET
Development qrcode in .NET Terminal Server newStream = stream oldStream = New MemoryStream() Return oldStream End Function Public Overrides Sub ProcessMessage(ByVal message As _
print barcode rdlc report
use rdlc report files barcodes writer to attach barcodes with .net book
BusinessRefinery.com/barcode
java barcode reader tutorial
using scanners applet to render barcode in asp.net web,windows application
BusinessRefinery.com/barcode
Finally, add declarative permission statements using the PrincipalPermission class before each method you need to restrict access to. You must define two things for PrincipalPermission:
generate, create barcode mail none on .net c# projects
BusinessRefinery.com/ bar code
barcode printing using vb.net
generate, create bar code report none on vb projects
BusinessRefinery.com/ barcodes
the values 0, 128, 192, 224, 240, 248, 252, 254, and 255.
using help reporting services to build barcodes in asp.net web,windows application
BusinessRefinery.com/ bar code
birt barcode font
generate, create barcodes coding none in java projects
BusinessRefinery.com/ bar code
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
to embed qr-code and qrcode data, size, image with java barcode sdk signature
BusinessRefinery.com/qr-codes
quick response code image database on visual basic.net
BusinessRefinery.com/Denso QR Bar Code
5. 6.
use microsoft word qrcode integration to print qr code 2d barcode with microsoft word data
BusinessRefinery.com/QR-Code
ssrs 2016 qr code
use ssrs qr code iso/iec18004 creator to receive qr-codes on .net activity
BusinessRefinery.com/qrcode
15-3
to generate qr code iso/iec18004 and qrcode data, size, image with excel microsoft barcode sdk connection
BusinessRefinery.com/qr codes
qr code size zipcode in office excel
BusinessRefinery.com/qr barcode
is stored, a hash of the assembly s code, or the assembly s signature.
winforms data matrix
using barcode printing for .net winforms control to generate, create ecc200 image in .net winforms applications. good,3
BusinessRefinery.com/barcode data matrix
vb.net pdf417
generate, create pdf417 usb none for visual basic.net projects
BusinessRefinery.com/PDF-417 2d barcode
Each approach is described in the following sections.
use word code 39 extended integration to draw bar code 39 with word vba
BusinessRefinery.com/39 barcode
java data matrix decoder
using ascii jsp to access data matrix 2d barcode in asp.net web,windows application
BusinessRefinery.com/barcode data matrix
1. What will be the fastest and most effective means to configure user accounts to require a password change at the next logon a. Select a user account. Open its properties and, on the Account page, select User Must Change Password At Next Logon. Repeat for each user account. b. Press CTRL+A to select all users in the Employees OU. Choose the Properties command and, on the Account page, select User Must Change Password At Next Logon. Repeat for each OU. c. Use the Dsadd command. d. Use the Dsrm command. e. Use the Dsquery and Dsmod commands.
rdlc code 39
use rdlc report files code 39 extended generator to draw barcode 3 of 9 with .net abstract
BusinessRefinery.com/barcode 3 of 9
use word documents pdf417 encoder to produce pdf-417 2d barcode with word documents addon
BusinessRefinery.com/PDF417
//C# using System; using MSLearning.12.Services; namespace MSLearning.12.ConsoleClient {
vb.net code 39 generator in vb.net
using based visual .net to draw barcode 39 in asp.net web,windows application
BusinessRefinery.com/ANSI/AIM Code 39
pdf417 c#
using barcode encoder for .net vs 2010 control to generate, create pdf417 image in .net vs 2010 applications. new
BusinessRefinery.com/PDF 417
It is possible to move disks between computers. If, for example, you plan to take a server offline, you might attach its physical disks to another server so that data can con tinue to be accessed. The process for doing so is the following: 1. Check the health of the disk while it is in the original server. It is recommended to open Disk Management and confirm that the disk status displays Healthy before moving the disk. If the disk is not healthy, repair the disk. 2. Uninstall the disk in the original computer. If the original server is online, uninstall the disk by right-clicking the disk in Device Manager and choosing Uninstall. 3. Remove a dynamic disk correctly. If the original server is online, open Disk Man agement, right-click the dynamic disk and choose Remove. This step is not neces sary or possible with basic disks. 4. Physically detach the disk. If the computer supports hot-swapping the drive, you may remove the drive. Otherwise, shut down the computer to remove the physi cal disk. 5. Attach the disk to the target server. Open Disk Management and, if the drive has not been detected automatically, right click the Disk Management node and choose Rescan Disks. Otherwise, shut down the target server before adding the physical disk. 6. Follow instructions in the Found New Hardware Wizard. If the wizard does not appear, open Device Manager and see if the drive was detected and installed auto matically. If not, open Add Hardware from Control Panel. 7. Open Disk Management. Right-click Disk Management and choose Rescan Disks. 8. Right-click any disk marked Foreign and choose Import Foreign Disks. Importing a disk reconciles the LDM databases on a new dynamic disk with the existing disks. Some important notes about moving physical disks:
4-23
Configuring Linked Servers for Delegation
Besides being able to perform all of the tasks of any other group member, members of
Understanding TCP/IP
Questions and Answers 11-89
If you want to enable POP3 or IMAP4 for more than one mailbox, you can pipe the output of a PowerShell command based on the Get-Mailbox cmdlet into a command based on the Set-CASMailbox cmdlet. For example, to enable IMAP4 for all the mailboxes in the database First Glasgow Mailbox Database in the storage group First Storage Group, you would use the following command:
Firewall
8-32
ALTER TABLE Test.Orders WITH CHECK CHECK CONSTRAINT FKOrdersCustomers;
Table 2-3
MORE INFO
Note
Boot partition The disk partition that possesses the system files required to load the operating system into memory. Files And Settings Transfer Wizard One of two methods used by administrators to transfer user configuration settings and files from systems running Windows 95 or later to a clean Windows XP installation. The other method is the USMT. Last Known Good Configuration The configuration settings that existed the last time that the computer started successfully. NTFS The native file management system for Windows XP. However, Windows XP is also capable of using FAT and FAT32 file systems to maintain compatibility with previous versions of Windows. Recovery Console A command-line utility that gives you access to the hard disks and many command-line utilities when the operating system will not start. The Recovery Console can access all volumes on the drive, regardless of the file system type. You can use the Recovery Console to perform several operating system trou bleshooting tasks. Safe mode An alternative startup mode that loads a minimal set of device drivers (keyboard, mouse, and standard mode VGA drivers) that are activated to start the computer. System partition Contains the hardware-specific files that are required to load and start Windows XP. Normally the same partition as the boot partition. User State Migration Tool (USMT) Allows administrators to transfer user configura tion settings and files from systems running Windows 95 or later to a clean Win dows XP installation.
More QR Code on .NET
asp net barcode generator: Figure A-4 The Network Adapter tab of the RDP-Tcp Properties dialog box in .NET Compose qr barcode in .NET Figure A-4 The Network Adapter tab of the RDP-Tcp Properties dialog box
qr code with vb.net: Important in .NET Maker QR Code ISO/IEC18004 in .NET Important
qr code with vb.net: Glossary in .NET Generator qr codes in .NET Glossary
qr code with vb.net: Glossary in .NET Generator qrcode in .NET Glossary
create 2d barcode c#: Glossary in .NET Creator Quick Response Code in .NET Glossary
how to generate qr code in vb.net: Contents in .NET Encoding qr-codes in .NET Contents
create 2d barcode c#: User Accounts in .NET Get Quick Response Code in .NET User Accounts
qr code vb.net free: Files and Folders in .NET Integrating QR Code 2d barcode in .NET Files and Folders
how to generate qr code using vb.net: Maintaining the Operating System in .NET Generating QR Code JIS X 0510 in .NET Maintaining the Operating System
how to generate qr code in vb.net: of Contents in .NET Development QR Code 2d barcode in .NET of Contents
create qr barcode c#: Part II in .NET Create Quick Response Code in .NET Part II
create qr barcode c#: xxiv in .NET Make Quick Response Code in .NET xxiv
how to create qr code vb.net: Lesson Review in .NET Assign QRCode in .NET Lesson Review
how to create qr code vb.net: Delegation in .NET Insert QR Code JIS X 0510 in .NET Delegation
qr code with vb.net: Lesson 2 in .NET Compose QR Code JIS X 0510 in .NET Lesson 2
qr code with vb.net: Extension Snap-Ins in .NET Draw QRCode in .NET Extension Snap-Ins
qr code with vb.net: Administering Microsoft Windows Server 2003 in .NET Compose QR Code JIS X 0510 in .NET Administering Microsoft Windows Server 2003
asp net barcode generator: Security Alert in .NET Creator qr barcode in .NET Security Alert
qr code with vb.net: Questions and Answers in .NET Development QR Code 2d barcode in .NET Questions and Answers
qr code with vb.net: Off the Record in .NET Build qrcode in .NET Off the Record
Articles you may be interested
ean 128 vb.net: F02NS04 in .NET Writer QR Code JIS X 0510 in .NET F02NS04
generate barcode c# free: Case Scenario 1: Distributing the Document Viewer . . . . . . . . . . . . . . . . . . . . 687 in .NET Creation Quick Response Code in .NET Case Scenario 1: Distributing the Document Viewer . . . . . . . . . . . . . . . . . . . . 687
c# read barcode free library: Note in visual C#.net Writer barcode 3 of 9 in visual C#.net Note
zxing generate qr code sample c#: F04im16 in C#.net Produce QR Code in C#.net F04im16
An Introduction to Microsoft SQL Server Manageability Features in C# Generator qr barcode
how to print barcode in crystal report using vb.net: Restoring the Sort Order in .NET Generate 2d Data Matrix barcode in .NET Restoring the Sort Order
upc internet service: Lesson 2: Designing a Cursor Strategy in .NET Implement UPC-A in .NET Lesson 2: Designing a Cursor Strategy
Questions and Answers in visual basic Render barcode pdf417
vb.net print barcode zebra: BACKUP LOG AdventureWorks TO DISK = C:\TEST\AW3.TRN in .NET Incoporate PDF 417 in .NET BACKUP LOG AdventureWorks TO DISK = C:\TEST\AW3.TRN
qr code vb.net free: Quick Check Answers in .NET Display QR Code JIS X 0510 in .NET Quick Check Answers
printing barcode vb.net: Publishing license in .NET Generate barcode 128a in .NET Publishing license
c# qr codes: Lesson 2 in .net C# Generating QRCode in .net C# Lesson 2
vb.net code to print barcode: Lesson 2 in .NET Generation PDF-417 2d barcode in .NET Lesson 2
zxing c# qr code sample: Lesson 2 in .net C# Implementation QR-Code in .net C# Lesson 2
barcode generator c# code: Interviews in visual C# Integrating EAN/UCC-13 in visual C# Interviews
creating barcode vb.net: Administration in .NET Writer USS Code 128 in .NET Administration
free visual basic qr code generator: Lesson 1: Enforcing Data Quality According to Business Requirements in visual basic Encoding qr codes in visual basic Lesson 1: Enforcing Data Quality According to Business Requirements
qr code vb.net source: Answers in .NET Produce qr-codes in .NET Answers
vb.net code 39 generator open source: Introducing Windows 7 for Developers in VB.NET Build qr codes in VB.NET Introducing Windows 7 for Developers
vb.net code to generate barcode: Lesson 6: Removing Database Mirroring in .NET Connect PDF417 in .NET Lesson 6: Removing Database Mirroring | http://www.businessrefinery.com/yc2/283/285/ | CC-MAIN-2022-05 | refinedweb | 2,037 | 61.73 |
As part of a project I'm working on, I need to develop a program that can take in a sentence and convert it somehow (I'm choosing to convert into Pig Latin). At first I thought this was going to be a piece of cake, until I realized that after
#include <iostream> using namespace std; int main(){ string sentence; cout << "Please enter the phrase you want to be translated: "; getline(cin, sentence); return 0;}
I have no real good idea of how to iterate through to the string so I can get it to do what I want. I need to separate each individual word (so copy every letter up to the first space), check whether the first letter of that word is a vowel or not (if vowel, do nothing), and if it's not a vowel move the first letter to the end of the word and add the letters 'ay', and then display it. An example would be
this is a phrase
histay is a hrasetay
Any help on how to accomplish such an easy sounding yet somehow ridiculously hard feat would be appreciated. | https://www.daniweb.com/programming/software-development/threads/182051/string-manipulation | CC-MAIN-2018-26 | refinedweb | 188 | 50.17 |
Hello All,
We have upgraded from SP11 to SP17. All the post installation steps are completed.
On SP11 I had configured portal provisioning with role mapping to ECC System and was all working fine. When moved to SP17 on the last stage I get the error "EP-6622-USER CREATE-noSuchidentifier" when trying to provision. Role gets assigned in portal but request remains in the same stage with error. I found SAP notes for the same error and implemented Note No: 1482968, but problem not solved.
The log says ""Could not update user Attribute "j_user" on namespace"
I got a solution where I have to take out CHANGE_USER action from Request type. But this will not suit my requirement.
EP is connected to LDAP and User data source is LDAP.
Has any one come across this problem or can suggest a different solution ?
Thanks and Regards,
Ajesh. | https://answers.sap.com/questions/8976235/ep-provisioning-ac-53.html | CC-MAIN-2022-40 | refinedweb | 147 | 75.1 |
Largest Palindromic Number by Rearranging Digits
Given N (very large), we need to find the largest palindromic number by rearranging digits. If it is not possible to print the largest palindromic number from N then, print "Palindrome not found" without double quotes.
Examples:
Input: N = 113223 Output: 321123 Input: N = 333 Output: 333 Inuput: N = 123 Output: Palindrome not found
Naive Approach
Find all the palindromic permutations of the digits in N and print out the maximum from it.
Example:
Input: N = 1122 Pallindromic Permutations: 1. 1212 2. 1221 3. 2121 4. 2112 Among these values 2121 is the largest. So, we print 2121 as the largest palindromic number we can get from N(1122).
The Naive Approach will be too slow to calculate the answer when N is very large.
Efficient Approach
-.
- If we can form a palindrome by rearranging the digits of given number then apply Greedy approach to obtain the largest palindromic number.
The Greedy Approach
- To make a number large we have to put the largest digit at first. Therefore, we start checking the occurrences of every digit from 9 to 0.
- Now, if the occurrences of the digit is even, then we put half of the occurrence at front and subtract that half from the actual occurrences of current digit and move to the next digit.
- After completing the traversal, we will add that digit which is occurring odd times and make its occurrence zero.
- Now, we traverse the digits again but now from 0 to 9 and we will keep adding the remaining occurrences of digits to the number we obtained in step 3.
- After step 4 we will be having The Largest Palindromic Number.
Important Points we need to remember while coding the solution-:
- The number can be very large so we need to store it in a string.
- To store the occurrences of the digits we will use a count array of size 10.
- We should include a function which will check if the given number can form a palindrome number or not.
C++ Code
#include<bits/stdc++.h> using namespace std; string theLargestPalindromicNumber;//This will contain the answer, right now it is empty. bool possiblePalindrome(int count[], int length) { int numberOfOdds = 0; for(int i=0;i<length;i++) { if(count[i] & 1)// it will give 1 if the count is odd otherwise 0 will be the output. { numberOfOdds++; } } if(numberOfOdds>1) return false; else return true; } void largestPalindromicNumber(string number) { int length = number.size(); int count[10]={0};//to store count of digits. //Step 1 for(int i=0;i<length;i++) { count[number[i] - '0']++; } // check if we can form a palindrome or not. if(possiblePalindrome(count, length) == false) { cout<<"Palindrome Not Found"; return ; }//step 1 ends else { // Now we can make palindromic numbers from the given input. int indexOfOddTimesOccuringDiigit = -1;// -1 indicates, no digit is occurring odd number of times. //Step 2 starts for(int i=9; i>=0; i--) { if(count[i]&1) { indexOfOddTimesOccuringDiigit = i; } else { for(int j = 0; j < count[i]/2; j++) { theLargestPalindromicNumber+= char(i + 48); } count[i]/=2; } } //step 2 ends //step 3 starts if(indexOfOddTimesOccuringDiigit!=-1) { for(int i = 0; i<count[indexOfOddTimesOccuringDiigit]; i++) { theLargestPalindromicNumber+= char(indexOfOddTimesOccuringDiigit + 48); } count[indexOfOddTimesOccuringDiigit] = 0; } //step 3 ends //step 4 starts for(int i=0; i<=9; i++) { for(int j=0; j<count[i]; j++) { theLargestPalindromicNumber+= char(i + 48); } } //step 4 ends } return ; } int main() { string number; cin>>number; largestPalindromicNumber(number); //step 5 starts cout<<theLargestPalindromicNumber; //step 5 ends return 0; }
In the worst case, the time complexity will be O(10 * (length of string/2)), in case the number consists of a same digit at every position.
Time Complexity: O(N)
Example:
N = 1122334
step 1: Count the digits having odd occurences.
Frequency array: occurrences 0 2 2 2 1 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9
We have 1 digit whose occurrence is odd. So this is a valid number, we can form a palindrome.
step 2: Start travesing from 9, till 0.
Intialize a varible Answer = 0. This will store our answer.
Frequency array: occurrences 0 2 2 2 1 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 ^ | (Odd Occurrence we will add it later!!)
Answer = 0
Frequency array: occurrences 0 2 2 2 1 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 ^ | (Take half and subtract half)
Answer = 3
Frequency array: occurrences 0 2 2 1 1 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 ^ | (Take half and subtract half)
Answer = 32
Frequency array: occurrences 0 2 1 1 1 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 ^ | (Take half and subtract half)
Answer = 321
Frequency array: occurrences 0 1 1 1 1 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 ^ | (It is zero)
Answer = 321
step 3: Add the digit which was occurring odd number of times. Here it is 4.
Answer = 3214
step 4: Traverse from 0, till 9.
Frequency array: occurrences 0 1 1 1 0 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 ^ | (Add all the remaining occurrences)
Answer = 32141
Frequency array: occurrences 0 0 1 1 0 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 ^ | (Add all the remaining occurrences)
Answer = 321412
Frequency array: occurrences 0 0 0 1 0 0 0 0 0 0 index 0 1 2 3 4 5 6 7 8 9 ^ | (Add all the remaining occurrences)
Answer = 3214123
We have obtained the Longest Palindromic Number By Rearranging the digits. With this article at OpenGenus, you should now have a complete about solving this problem with a greedy approach.
Learn more:
- Greedy Algorithms at OpenGenus | https://iq.opengenus.org/largest-palindromic-number-by-rearranging-digits/ | CC-MAIN-2020-24 | refinedweb | 998 | 64.64 |
Red Hat Bugzilla – Bug 444759
high I/O wait using 3w-9xxx
Last modified: 2010-04-06 06:31:35 EDT
Description of problem:
High I/O wait (100%) when writing lots of data with 3ware 9650, awfully slow
write performance. A friend also gets the problem with aacraid.
Version-Release number of selected component (if applicable):
2.6.18-53.1.14
How reproducible:
Write something like 1GB data.
Steps to Reproduce:
1.
2.
3.
Actual results:
4 hours to import a 1GB sql file in postgresql.
Expected results:
6 minutes with the fix. 10 to 15% of I/O wait instead of 100% previously seen.
Additional info:
See;a=commit;h=1e6c38cec08f88b0df88a34e80f15492cace74e9
I've made a quick and dirty fix for local use and without having to backport the
pci_try_set_mwi function. I simply used pci_set_mwi instead of pci_try_set_mwi.
Will such a fix be included in a next kernel release ?
Regards.
Tomas,
See if you can reproduce this with the 3ware hardware you have. Either way,
please review for applicability on RHEL 5, and keep an eye on the upstream
results. If it looks good, we can propose it for 5.3.
Tom
AFAIK, it depends on the bios. Some enable MWI by default, some don't.
Linux devs choose to override it, just in case.
The box is running fine since the fix (no data corruption occured, normal
performance, sluggish system and I/O vanished).
I think this fix should be included as soon as possible, no need to wait for 5.3.
Regards,
Laurent.
Created attachment 308525 [details]
modified version
Laurent,
thanks for the patch, I had to slightly modify it.
I don't have access to the hardware, please could you verify that the test
kernel
on resolves your issue ?
Tomas, just rebooted the server with the x86_64 version of your kernel.
I/O wait went up to 45% with another test (and previously untested - deleting
loads of data from postgresql).
Data are being processed again so we can recreate the previous test that made me
post this bug, I'll keep you informed very soon (say about one hour).
Could you show me the diff you applied ?
duh, didn't see the attached patch, sorry.
OK, we've run again the 1GB import, and system is behaving normally, the same
way as with my patch.
Thank you very much.
When will that fix be included by default ? Please tell me it'll be included in
the next kernel update, and not with 5.3 release :)
Laurent, the attachment is inaccessible for you? But it doesn't matter - here is it:
diff -Naurp linux-2.6.18.x86_64/drivers/scsi/3w-9xxx.c
linux-2.6.18.x86_64a/drivers/scsi/3w-9xxx.c
--- linux-2.6.18.x86_64/drivers/scsi/3w-9xxx.c 2008-06-05 14:53:15.000000000 +0200
+++ linux-2.6.18.x86_64a/drivers/scsi/3w-9xxx.c 2008-06-05 14:39:11.000000000 +0200
@@ -89,6 +89,7 @@
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_cmnd.h>
+#include <linux/libata.h>
#include "3w-9xxx.h"
/* Globals */
@@ -2062,6 +2063,7 @@ static int __devinit twa_probe(struct pc
}
pci_set_master(pdev);
+ pci_try_set_mwi(pdev);
retval = pci_set_dma_mask(pdev, sizeof(dma_addr_t) > 4 ? DMA_64BIT_MASK :
DMA_32BIT_MASK);
if (retval) {
Laurent,
is your test system still working well with this test kernel ?
>Please tell me it'll be included in
>the next kernel update, and not with 5.3 release :)
I could tell you what you want :) , but I think that it will go in the 5.3..
Yes, the system still works without problems, and normal performance.
Please include that fix in the bext kernel update. It'd be shame to have to wait
until 5.3.
Thanks.
The only kernel updates between 5.2 and 5.3 are for critical security fixes,
system crashers, or data corruption. This does not fit the bill.
The other option is for you to contact Red Hat support, and request a hot fix
for this.
Enormous performance problems should be added too, IMHO :) Not only the
performance increase is 40 times (!) when it comes to write I/O, and the system
remains responsive under load, and that's absolutely not the case without it.
I'm a bit unsure about the real cause, but we met crashes of the system with
high I/O writes (good ol' oops, but I haven't kept logs, unfortunately). That
never happened with the fix. I think it may be due to the ever growing list of
I/O write demands that take longer and longer to de done. I can't try that case
anymore, as the corresponding server is going into prod real soon now.
I guess I'll have to add by hand that fix until 5.3 then, as I'm not a RH
customer, but a CentOS user. Unless I can convince CentOS people to add it
before you do in 5.3.
Regards.
Laurent,
once again thanks for your report + testing.
I'm sorry, but I think that requesting a hot fix via our support is the only way
how to get it sooner then in rel. 5.3.
You're welcome.
I'll try to maintain a fixed kernel repo until 5.3 is out then.
Time to take a look at how to create a repo.
OK ... I have created a test kernel that has this patch for CentOS. We will be
maintaining it as security updates are done until this issue is fixed in the 5.3
kernel.).
To compare, the 3ware exported drives and an md created array not only performed
much better, but did not crash the box with the same scp or rsync.
(In reply to comment #17)
>).
This sounds like a different bug.
The crash you describe happens with or without the patch posted in this BZ,
right? And the patch posted in this BZ improves performance, at least on some
motherboards. right? If so, then we will go ahead with this patch and you should
open a new BZ for the crash you have seen. Please include a stack trace, or even
better, a crash dump.
>.
Is there any kernel/driver version that successfully allows you to run 3ware
RAID 5 without crashing?
Sorry for the delay (summer vacation)...
(In reply to comment #18)
...
>
> This sounds like a different bug.
Yes, after I added my comment, I kinda thought the same thing.
> The crash you describe happens with or without the patch posted in this BZ,
> right?
Yes, the crash happens with all of the kernels CentOS derived kernels. Those
kernels include stock, centosplus and the BZ kernel noted here. I also tried a
kernel.org 2.6.25.7 kernel (with kernel config from CentOS kernel) and includes
the newer 3ware 2.26.02.010 driver. Sadly, all of them crash after a couple
hours or more of continuous transfer with an error like:
3w-9xxx: scsio: warning: (cox06: 0x000c): Character ioctl (0x108) timed out
reseting card.
3w-9xxx: scsio: ERROR (ox06: 0x0030) Response queue (large) empty failed during
reset sequence.
> And the patch posted in this BZ improves performance, at least on some
> motherboards. right?
There is a slight improvement to performance with the bz kernel with:
sync ; iozone -s 20480m -r 64 -i 0 -i 1 -t 1 -b some_file.xls
sync ;hdparm -Tt /dev/sda1
sync ; time `dd if=/dev/md0 of=/dev/null bs=1M count=20480`
compared to the stock centOS kernels. It's interesting that using the "deadline"
scheduler actually seems makes a positive difference, also.
> If so, then we will go ahead with this patch and you should
> open a new BZ for the crash you have seen. Please include a stack trace, or even
> better, a crash dump.
I did find a CentOS bug that seems to match my issue at:
One of the solutions noted did not help ("noapic" for the kernel). Sadly, that
bug was closed with a "it's a hardware problem"... I'm not sure I agree ;)
>
> >.
Correct, with all the same hardware, and only changing from 3ware RAID 5 to md
raid 5 = no crash with LONG transfers. Every attempt at LONG transfers with
3ware RAID 5 = crash in all x86 kernels tested.
>
> Is there any kernel/driver version that successfully allows you to run 3ware
> RAID 5 without crashing?
No. There was no kernel/driver version (including the 2.6.25.7 with 2.26.08.010
driver and latest card firmware) that did not crash with 3ware RAID 5.
(In reply to comment #19)
I think that this definitely is a different bug and the patch from this bug
which should increase the performance on some motherboards doesn't make it worse
or better.
If your problem still persist please open for it another bugzilla where we will
then continue the discussion.
in kernel-2.6.18-99.el5
You can download this test kernel from
Has this been resolved? We recently re-provisioned a server with latest kernel updates and this problem seems to have gone away.
the fix is included in rhel 5.3 kernel. I've checked the kernel patches list in 5.3 beta.. | https://bugzilla.redhat.com/show_bug.cgi?id=444759 | CC-MAIN-2017-39 | refinedweb | 1,534 | 75.5 |
2.9.1 PO design mode
Before talking about Pytest, let's take a look at what is the PO (Page Object) design pattern.
Why reference PO design patterns? PO provides a mode of separating business process from page element operation, which makes the test code clearer.
PO (Page Object) Page Object model is a design pattern used to manage and maintain an object library of a set of web elements. In PO mode, each page of the application has a corresponding page class. Each page class maintains the element set of the web page and the methods to operate these elements.
2.9.2 installation and use of pytest
2.9.2.1 Pytest installation
We use the pip install command pip install -pytest.
Check the pytest installation version, and the command is pytest – version.
2.9.2.2 introduction to pytest
pytest is a unit test framework of Python. It is similar to the unit test framework of python, but it is simpler and more efficient than the unit test framework.
Advantages of pytest:
·The grammar is simple and easy to use
·Open source
·Convenient integration
·Support report framework - allure, etc
2.9.2.3 what modules does pytest execute?
All test module file names need to meet test_ Py format or_ test.py format.
In the Test module file, the Test class starts with Test and cannot have init method (Note: when defining a class, it needs to start with Test_, otherwise pytest will not run the class)
In a test module class, you can include one or more tests_ Function at the beginning.
At this time, when the pytest command is executed, it will automatically find the test functions that meet the above constraints from the current directory and subdirectories for execution.
2.9.2.4 execution mode of pytest
- pycharm
Select Edit configurations
Click the + sign and select pytest
Select the script path and click ok
Click Run:
- Main function mode
pytest.main(['parameter', 'script name'])
Example:
pytest.main(['-s','test_run.py'])
If there are multiple parameters:
pytest.main(['parameter',..., 'parameter', 'script name'])
Example:
pytest.main(['-s','-n','3','test_run.py'])
- command line
pytest + parameter + file path / test file name
Example:
pytest -s ./pytest_examples/test_run.py
- configuration file
Create the pytest.ini configuration file under the appropriate folder.
When pytest is executed, the configuration run of the configuration file is read
The contents of pytest.ini are as follows:
[pytest] # Command line parameters addopts = -s # Search file name python_files = test_*.py # Class name to search python_classes = Test_* # Function name to search python_functions = test_*
2.9.2.5 execution sequence of pytest
- setup_class
In the test class, setup_class method is a class level pre operation, which belongs to this test class. Execute the code before all test cases.
- teardown_class
In the test class, teardown_ The class method is a class level post operation. If it belongs to this test class, execute the code after all use cases
- setup
In the test class, the setup method is a pre operation at the use case level. It belongs to the test class and the code to be executed before each use case is executed
- teardown
In the test class, teardown method is a pre operation at the use case level. It belongs to the code to be executed after each use case is executed
- @pytest.fixtrue()
In the test class, the method decorated with @ pytest. Fixrule () can be referenced by other test classes, and its priority is higher than setup. The yield keyword can be used in the method. The method after yield will be executed after the end of the use case, and its priority is lower than teardown
Example code:
import pytest class Test_Run: """ Test operation principle """ def setup_class(self): """Class level pre operation""" print("For the test class, execute the code before all use cases") def teardown_class(self): """Class level post operations""" print("For all test cases belonging to this test class, execute the code") def setup(self): """Pre operation at use case level""" print("The code that belongs to this test class and must be executed before each use case is executed") def teardown(self): """Post operation at use case level""" print("The code belonging to this test class to be executed after each use case is executed") @pytest.fixture() def dec_fun(self): """Component functions that can be called by use cases""" print("Code to be executed before a specific use case is executed") yield print ( "Code to be executed after a specific use case is executed" ) def test_run1(self): """ :return: """ print("Operation of case 1") def test_run2(self,dec_fun): """ :return: """ print("Operation of case 2") def test_run3(self): """ :return: """ print("Operation of case 3") def test_run4(self): """ :return: """ print("Operation of case 4")
Operation results:
For the test class, execute the code before all use cases The code that belongs to this test class and must be executed before each use case is executed Operation of case 1 The code belonging to this test class to be executed after each use case is executed Code (component function) to be executed before execution of a specific use case yield (previous code) The code that belongs to this test class and must be executed before each use case is executed Operation of case 2 The code belonging to this test class to be executed after each use case is executed Code (component function) to be executed after a specific use case is executed yield (code after) The code that belongs to this test class and must be executed before each use case is executed Operation of case 3 .The code belonging to this test class to be executed after each use case is executed The code that belongs to this test class and must be executed before each use case is executed Operation of case 4 .The code belonging to this test class to be executed after each use case is executed For all test cases belonging to this test class, execute the code
2.9.2.6 Pytest Exit Code
• Exit code 0 all use cases have been executed and passed
• Exit code 1 all test cases have been executed, and there are Failed test cases
• Exit code 2 the user interrupted the execution of the test
• an internal error occurred during Exit code 3 test execution
• Exit code 4 pytest command line usage error
• Exit code 5 does not collect available test case files
2.9.2.7 Pytest parameterization
Parameterization refers to serializing multiple sets of parameter values of a function.
The parameterization method used in pytest is parameterize (arguments, argvalues)
explain:
arguments: parameter name
argvalues: parameter value, type must be list
When the parameter is one, the format is: [value]
When there are multiple parameters, the format is:
[(param_value1,param_value2),...,(param_valuen,param_valuen)]
use parametrize method: @pytest.mark.parametrize(arguments,argvalues)
In the test method, use arguments[0] to call the first parameter. Similarly, use arguments[1] to call the second parameter.
Example code:
class Test_DS: """E-commerce website PO Design pattern""" def setup_class(self): """Create before execution Web object""" self.web = Web () self.web.openbrowser ( 'gc' ) @pytest.mark.parametrize('loginparams',[('Password error','13800138006','12345611'), ('Account does not exist','13110138006', '123456'), ('Login succeeded', '13800138006', '123456')]) def test_login_success(self,loginparams): # Login succeeded self.web.geturl ( 'Test website' ) self.web.input ( '//*[@id="username"]', loginparams[1] ) self.web.input ( '//*[@id="password"]', loginparams[2] ) #self.web.get_verify ( '//*[@id="verify_code_img"]' ) self.web.input ( '//*[@id="verify_code"]', '1111' ) self.web.click ( '//*[@id="loginform"]/div/div[6]/a' ) def teardown_class(self): # wait for self.web.sleep('3') self.web.quit()
Operation results:
2.9.2.8 Pytest assertion
pytest uses assert to assert.
Example:
class Test_Assert: """ Assert """ def test_run1(self): a=0 print ( a) assert a def test_run2(self): assert 3==4
Operation results:
2.9.2.9 common parameters of pytest
Display print content:
When running the test script, in order to debug or print some content, we will add some print content to the code, but these contents will not be displayed when running pytest. If you bring - s, you can display it.
Operation mode:
pytest test_se.py -s
In addition, various running modes of pytest can be superimposed. For example, if you want to run four processes at the same time and want to print the content of print. You can use:
pytest test_se.py -s -n 4
Multi process running cases:
When there are a lot of cases, the running time will also become very long. If you want to shorten the running time of the script, you can run it with multiple processes.
To install pytest xdist:
pip install -U pytest-xdist
Operation mode:
pytest test_se.py -n NUM
Where NUM is the number of concurrent processes.
Failed case retry:
Install pytest rerunfailures:
pip install -U pytest-rerunfailures
Operation mode:
pytest test_se.py --reruns NUM
2.9.3 Pytest integration allure Report
2.9.3.1 original report of allure
allure download address:
Download this:
Configure environment variables after decompression:
The installation of allure is completed. python needs to install the allure pytest library.
pip install allure-pytest
Add parameters when executing pytest:
pytest.main ( ['-s','test_param.py', '--alluredir', 'result'] )
At this time, there will be a result file
In the folder (the file with result, here is pytest_example), execute the command line
`allure generate result -o reports`
We can let the code execute this command for us. The command is as follows:
os.system ( 'allure generate result -o reports --clean' )
The reports folder will be generated, and the index under the file will be opened_ HTML to get a clean test report
2.9.3.2 allure report DIY
1. Annotation optimization
2. Set logo
a. Modify logo image
Open the allure folder:
G:\allure-2.15.0\plugins\custom-logo-plugin\static
custom-logo.svg in the static folder is the default logo. We want to put our logo image here.
Then open styles.css
Here we need to adjust the style - find a front-end with good relationship!
b. Enable plug-ins
G:\allure-2.15.0\config \allure.yaml
Add a line at the end: - Custom Logo plugin
Just regenerate the report. | https://programmer.group/pytest-framework-and-application.html | CC-MAIN-2022-27 | refinedweb | 1,691 | 53.71 |
.
If it wasn’t so tragic it would be funny.
And it is not even (or wasn’t even) a poor country. Will the right lessons be learnt here?
Given certain ‘politicians” earlier gushing over the former ruler and his plans for a Bolivarian paradise, methinks that the chances are slim, cigarette paper slim.
When they start ‘arresting’ pigeons, eagles, vultures and other creatures as Israeli spies, as the Arab countries are won’t to do, they will have…
Like we are any better:
SMFS – Racist Scrabble! Brilliant!
And “jigaboo”, classic. Haven’t heard that one in donkeys.
I like my racism to be old-timey and vintage. It’s far more thoughtful than this rubbish modern racism.
What’s next? I have noticed a shocking lack of diversity in Cluedo.
And you just know that Mr. Monopoly is a racist, because he looks like one. We know who he wants to “go to jail”.
JuliaM – to be fair to the Arabs, eagles probably are Jewish, just look at the size of their beaks.
War on words – the crossword panic of May 1944 ‘Red!
Steve – “Racist Scrabble! Brilliant!”
Well we have had racist nursery rhymes so I suppose that Scrabble boards can’t be too far behind.
“And “jigaboo”, classic. Haven’t heard that one in donkeys.”
Don’t think I have ever heard it. In real life.
“I like my racism to be old-timey and vintage. It’s far more thoughtful than this rubbish modern racism.”
Absolutely. I am with Homer Simpson here – I like my Gays *flaming* and my racism more or less the same way. I don’t care much for all this secret code word and special Gnostic interpretation that the modern young ‘uns go in for.
“What’s next? I have noticed a shocking lack of diversity in Cluedo.”
Given we have already reached this point with Midsummers murders, Cluedo can’t be far behind – except your not allowed to show any criminals as Black but the Police Captain has to be. Which is ironic because in most US cities with Black police captains virtually no crimes are solved.
“And you just know that Mr. Monopoly is a racist, because he looks like one. We know who he wants to “go to jail”.”
Unfettered capitalist too. I am sure there is a Leftist version of Monopoly. I wonder if it features mass murder of peasants.
@JG
With the possible exception of Mulberry, it shows the remarkable stupidity of wartime military planners using “code words” bear such an obvious relationship to the items they’re supposed to be encoding..
Interestingly, Monopoly was first designed as an anti-capitalist game. Or at least anti-rentier.
@JG Thanks for the interesting yarn.
Tim Worstall – “Interestingly, Monopoly was first designed as an anti-capitalist game. Or at least anti-rentier.”
Wasn’t it the work of one of Henry George’s followers? So not so much anti-capitalist as anti-landowner?
Perhaps one of the more interesting misjudgements of history. Not as bad as the Romanian Communists allowing Dallas to be shown, thinking it an indictment of American capitalism ….
Dear Govt of Venezula
14 down and 23 across you, you evil bastards.
BiS,
i beg to differ – Utah and Omaha have no suggestion apart from them being something to do with the Yanks. Even then, what are you going to suppose: assault by the 23rd Mormon Divison or the 102nd Western “B” Movie Actors Brigade ? Juno, Sword and Gold sound like destroyers.
Overlord should raise eyebrows and its precursors were Roundup and Sledgehammer, so I guess you’re right on that one 🙂 And that was largely down to the Americans anyway. They tended to take leaves out of the German book on Wagnerian operation names.
Bomber Harris was the worst offender, but he pinched the names “Millennium” and “Gommorrah” to make a point about “burning out the black heart” of the enemy.
Ideally secret military codenames would be taken at random and carry no obvious martial connotations. But then nobody wants to be remembered as the man.who commanded Operation French Tickler.
True story:
A previous employer had a top-secret project that was in all the senior managers’ diaries under the name “Alderaan”.
The Star Wars geeks knew that Alderaan was the first planet to be destroyed by the Death Star.
It therefore came as no surprise to them when the final outcome of Project Alderaan was a massive amount of job losses.
Steve: Churchill, in a 1943 memo to “Pug” Ismay had this to say on the matter
Steve – “Ideally secret military codenames would be taken at random and carry no obvious martial connotations. But then nobody wants to be remembered as the man.who commanded Operation French Tickler.”
After the war Britain did this. They used colour codes. Every military project, more or less, had to have a colour and then a random word. Thus we got Britain’s space effort involving Black Prince and Blue Steel. As well as some oddities – like Purple Possum which was actually a chemical nerve agent.
It must have been pretty embarrassing when you had to get on the radio and tell HQ that your Yellow Duckling wasn’t working. Still it did give up Blue Peacock. Which remains the world’s only chicken powered nuclear land mine. That I know of.
@BiCR
Isn’t Churchill losing the point of code words, there? They are supposed to obscure what they represent. Thus a NAAFI menu requisition should be indistinguishable from an airborne assault. “Heroes of antiquity, figures from Greek and Roman mythology,…names of British and American war heroes” are hardly going to refer to lavatory paper supply. Which is what you’d wish them to.
I can see Churchill’s point though. Ideally codewords should be random, but even constraining the namespace as Churchill did should still allow a lot of random selection to occur. It’s not as if English has a thin vocabulary.
Modern British codewords are random – taken from a list, although you are allowed to reject a number. Hence Corporate (Falklands), Granby (1st Gulf), Telic (2nd Gulf / Iraq) & Herrick (Afghanistan) from among the more widely known ones.
The assistance for the recent flooding was Op Pitchpole. The only recent one that wasn’t done this way was Op Olympics, which was exactly what it says on the tin.
Fishcake and toadstool were, famously, featured in “Dance to the Music of Time”.
And I believe the current disastrous soon-to-end-in-abject-defeat British folly in Afghanistan rejoices in the code name of “Herrick”. | https://www.timworstall.com/2014/03/theyre-entirely-losing-it-arent-they/ | CC-MAIN-2020-45 | refinedweb | 1,100 | 75.5 |
0
First, you need to use code tags on your code to make it readable and not lose your inentation.
Your line
for (first, second) in pairs: is along with your error suggesting that pairs is being passed in as an integer.
When you provide an example code it would help if it is an actual example that can be run to demonstrate your dilemma. Otherwise we are left to guess at best, which is all we can do here since we can't see what you're passing to this function or what the context of your program is like.
You can test if an object can be iterated over ...
import operator a = 1 b = 'abc' c = [1, 2, 3] d = {'a': 1, 'b': 2, 'c': 3} print operator.isSequenceType(a) # False print operator.isSequenceType(b) # True print operator.isSequenceType(c) # True print operator.isSequenceType(d) # False print operator.isSequenceType(d.items()) # True # test if an object is a sequence and can be iterated over if operator.isSequenceType(b): for x in b: print x | https://www.daniweb.com/programming/software-development/threads/134808/help-needed-to-solve-an-error | CC-MAIN-2017-04 | refinedweb | 176 | 66.33 |
So I have written a minimal example that I hope would result more intuitive as a first introduction to this concept.
We have a class designed to be used in a multithread context, it has as data member a resource that is meant to be shared, and we have a couple of functions that modify that shared value, and could be called from different threads.
Usually what we do is relying on mutexes and locks to synchronize the access to the shared resource. ASIO provides us the strand class, as a way to serialize the execution of the works posted to it, making unnecessary explicit synchronization. But be aware that this is true only for the functions going to the same strand.
We want to write a piece of code like this:
namespace ba = boost::asio; // ... ba::io_service aios; Printer p(aios, 10); // 1 boost::thread t(std::bind(&ba::io_service::run, &aios)); // 2 aios.run(); // 3 t.join(); // 41. See below for the class Printer definition. In a few words, it is going to post the execution of a couple of its functions on ASIO, both of them acting on the same shared resource.
2. We run a working thread on the ASIO I/O service.
3. Also the main thread is running on ASIO.
4. Wait for the worker completion, than end the execution.
So we have two threads running on ASIO. Let's see now the Printer class private section:
class Printer { private: ba::strand strand_; // 1 int count_; // 2 void print(const char* msg) // 3 { std::cout << boost::this_thread::get_id() << ' ' << msg << ' ' << count_ << std::endl; } void print1() // 4 { if(count_ > 0) { print("print one"); --count_; strand_.post(std::bind(&Printer::print1, this)); } } // ... };1. We are going to operate on a Boost Asio strand object.
2. This is our shared resource, a simple integer.
3. A utility function that dumps to standard output console the current thread ID, a user message, and the shared resource.
4. Client function for (3), if the shared resource count_ is not zero, it calls (3), than decreases count_ and post through the strand a new execution of this function. There is another private function, print2(), that is exactly like print1(), it just logs a different message.
Since we are in a multithread context, these function should look suspicious. No mutex/lock? No protection to the access of count_? And, being cout an implicitly shared resource, we are risking to get a garbled output too.
Well, these are no issues, since we are using a strand.
But let's see the Printer ctor:
Printer(ba::io_service& aios, int count) : strand_(aios), count_(count) // 1 { strand_.post(std::bind(&Printer::print1, this)); // 2 strand_.post(std::bind(&Printer::print2, this)); }1. Pay attention to how the private ASIO strand object is constructed from the I/O service.
2. We prepare the first runs, posting on the strand the execution of the private functions.
What happens is that all the works posted on the strand are sequentially executed. Meaning that a new work starts only after the previous one has completed. There is no overlapping, no concurrency, so no need of locking. Since we have two threads available, ASIO will choose which one to use for each work execution. We have no guarantee on which thread is executed what.
We don't have the troubles associated with multithreading, but we don't have some of its advantages either. Namely, when running on a multicore/multiprocessor machine, a strand won't use all the available processing power for its job.
The full C++ source code for this example is on github. | http://thisthread.blogspot.com/2012_04_01_archive.html | CC-MAIN-2017-51 | refinedweb | 605 | 64.61 |
Three years ago, when Web services entered the radar of the technology community, the Remote Procedure Call (RPC) interface was the common implementation. Many people looked at SOAP and started down the familiar path of technologies like RMI, CORBA, and their own custom hacks for exposing server-side data and functions -- complex, closed systems that defined how to make and receive a request in a rigorous, yet highly encoded fashion. The RPC style of encoding Web services, by providing an automatic method of exposing and calling methods, quickly became popular. Yet. This article.
The two faces of Document-style encoding
One challenge a developer encounters when working with Web services is that there are two invocation models: RPC and Document style. There are several good articles that address the differences of these two models in detail, but the following section will review these differences briefly to put the rest of the article in context.
RPC-style encoding seems attractive because it is conceptually the same as other implementations architects and developers have worked with over the years, such as CORBA or RMI. Document-style encoding piques interest, but RPC is easy and makes demonstrating the technology straightforward, and so frequently Document style receives short shrift. However, the minute development is past the proof-of-technology point, there is an immediate need to send real, complex objects over the wire. Sending Strings and Integers, maybe even Arrays, is okay for show, but the real world uses complex data structures and models to encode data. To handle this, SOAP RPC implementations support complex object serialization and deserialization. As long as the object complies with the Java Bean specification, the object could be turned into XML and handled transparently to the developer. This was wonderfully seductive -- in a few simple lines of code, real business data objects were sailing over the wire with little concern for underlying implementation.
But as it turns out, there are drawbacks to using complex objects over RPC. This approach often leads to integration issues. One implementation's serialization might not match another's deserialization, since the Java Bean to XML SOAP encoding process is ambiguous and not well-defined. Suddenly open technology comes to a screeching halt -- an Apache SOAP service had trouble working with .NET because of discrepancies in their implementations, and thus drove the need to keep services more open.
Document-style Web services offer a satisfying mix of well-defined structures and interoperability. This is achieved through standard XML-Schemas for defining complex objects. In contrast to SOAP encoding, XML-Schema is a rigorous and well-understood standard for defining structures. XML-Schemas provide a great deal of flexibility in defining complex structures while ensuring all the promises of Web services -- language, platform, environment, and transport-independent with a common application programming interface.
Document style, which gains all the benefits of XML-Schema, seems to be the solution to all your Web service headaches. However, Document style has some trade-offs. One of the trade-off problems the programmer is faced with is increased complexity. Suddenly, the developer has the arduous task of parsing an XML document and performing the necessary transformations to populate other data beans or method requests with the incoming data. This is true both for the server and client. For the brave of heart, this means writing a custom SAX handler. And SAX handlers aren't known for being particularly user friendly or easy to maintain.
Solution in the making: Apache Axis
Apache Axis is one of the most popular Web services toolkits out there. Axis supports both RPC and Document-style services, and so it would seem to be the right starting point for a Document-style service. As with any Document-style service, you still have the task of handling the incoming XML data somehow. Axis includes a handy tool to help solve this arduous task, called WSDL2Java. WSDL2Java can generate both code stubs for the client and server for your methods, and actual beans to model your data from the model defined in the XML-Schema. WSDL2Java will then populate these beans automatically from the XML. This process in general is called data binding, and it's one of the mainstays of the movement behind XML-Schema. WSDL2Java can be a little quirky, but in general it helps get things rolling. Clearly a tool like this is very useful to have, but unfortunately it is not the end-all for client stub generation -- it faces some real issues:
- WSDL2Java suffers from the common trap most technologies in the space have fallen into, which is playing catch-up with schema support. Writing a tool that can correctly and completely handle the highly complex XML-Schema standard is no small task. It alone represents an effort potentially as difficult as Axis itself. WSDL2Java is noticeably lacking in this area, having buggy or incomplete support for many XML-Schema features. Examples of this are support for attribute groups and choice groups, but these are of course changing, as work on WSDL2Java continues. The point, however, is that writing and maintaining such a complex piece of code isn't the area that Axis is concentrating on, and WSDL2Java will likely continually be playing a game of catch-up to meet the functionality of stand-alone data-binding solutions.
- Another problem, related to the first, is that the code that WSDL2Java generates lacks XML validation capability. When you begin to work with XML documents, validation is important, and the XML-Schemas allow validation to occur automatically. However, WSDL2Java doesn't have a facility to do this.
- The interface to serialization to and from strings is not intuitive. If you are using WSDL2Java's data binding code for your XML objects, chances are, you'll need to encode or decode the objects back to an XML string at some point. While this is possible with WSDL2Java's generated objects, it's not an easy task. A large framework has to be set up, and it can cause a lot of headaches, for what seems to be a simple task.
Another reason the development community has some mixed reactions and confusion about using Apache Axis is because it has grown with it through its beta phases. The quirky workarounds and configuration mechanisms many learned have changed from version to version. This is just a reality of a developing body of code. Initially, when Axis was first being produced, the primary focus was RPC-style Web services. As such the support for RPC services is greater, and its interfaces are more stable and well-known to developers. Until recently, Document-style documentation, examples, and sample configurations for Axis have been limited. With the advent of multiple internal configuration options for using Document style, such as wrapped, document, or message, developers have a few more decisions and complexities to go through in setting up their own Document-style service. While these configuration difficulties are not a great hurdle, by any means, working with RPC has traditionally been the quick, easy way to get a Web service off the ground. Certainly as Axis continues to develop, this will resolve itself. But for the here and now, with the explanations and step by step instructions in this article, working with Document-style services is about to get much easier.
Axis and Castor: The best of both
Castor is a stand-alone XML data binding package that provides a mapping from XML-Schema to Java objects. These Java objects look and feel like beans, but can be marshaled and un-marshaled to XML strings or streams, and importantly, validated against their original schema. Castor is an open-source effort that compliments the open technologies of Web services. It is backed by a very active development community, and it has in turn generated a lot of attention and Web content to help developers leverage the technology effectively.
We will use Castor where Apache Axis and WSDL2Java fall short, to build a solution of best practices on all levels. We'll gain the benefits of an easy, intuitive data binding interface with a more fully supported schema implementation, while still leveraging all the Web services capabilities of the Axis framework. Figure 1 shows the relationship between Axis and Castor.
Figure 1. Relationship between Axis and Castor in our solution
What you need to get started
This article is intended for intermediate Java developers familiar with Web services and the various technologies involved in creating and deploying them. If you can write a basic WSDL and deploy a service with Axis, then you should be ready for everything in this article. Likewise, the article assumes some knowledge of XML and Schema. All the code was developed, tested and deployed using WebSphere Studio Application Developer and WebSphere Application Server versions 4.0.4 and 4.0.6. Other development and deployment environments or libraries could very well be substituted to achieve similar effect, but we'll concentrate on these environments here.
Getting the latest Axis and Castor
To build and run this project, you'll need Apache Axis and Exolab's Castor. Castor is available at. Instructions for download and installation are available there, which are very straightforward. Grabbing Apache Axis is a little more difficult, but not too much. At the time of this article's writing, the code needed to make Axis interoperate properly with Castor is not yet in a released beta, and is only found in CVS. By the time you read this, the functionality will very likely be in the latest released JARs. However, until it is, the best way to get the latest Axis with the org.apache.axis.ser.CastorSerializer and Deserializer code necessary for this project is to grab it from CVS or download a nightly build, both of which are available at. Follow the instructions there to download and build a copy of Apache Axis, which is easier than it seems, thanks to the Apache Ant build architecture.
Getting Axis off the ground in WebSphere
Our sample environment for this project is WebSphere Application Server V4.0.4. Getting Axis set up with WebSphere or another Java container isn't too difficult, but it's important to get the steps right. The Apache Axis documentation includes a guide for doing so (see Resources), or in
/xml-axis/java/docs/install.html in your local CVS checkout or nightly.
If you're using WebSphere Application Studio V5.0, you may run into a "gotcha" on JAR conflicts between what's installed on WebSphere Application Developer V5 and what you are trying to use with Apache Axis. If you run into these problems, try this quick fix: in your Server Configuration for your test server, set the System Property (-D property) for "com.ibm.ws.classloader.warDelegationMode" to false in the Environment Options pane. You'll find this under Server perspective > the server you are using for our example > Environment Options > System Properties > Add....
Define the schema and the service
The input that you'll need to developing your Web service is a schema to represent the data you'll be using and a service description to delineate your methods that you would like to expose. Describing how to write an XML-Schema or a WSDL is beyond the scope of this article, but documentation on how to do so abounds elsewhere.
For the purpose of this article, we'll create an example service: the StockQuote service.
Defining the schema for your data: StockQuote.xsd
The first thing that your service needs is a description in XML-Schema of your data model. In Listing 1 is the simple data model that you'll use in your StockQuote service, which should be self-explanatory.
Listing 1. Data Model for the StockQuote service form StockQuote.xsd
In addition to defining the elements and complexTypes that represent your data model, you must also define the representation of the input/output messages of your interface. These are the methods that your Web service will expose, and that you will point to in the WSDL, which you'll create in the next step, shown in Listing 2.
Listing 2. Method Signatures for the StockQuote service from StockQuote.xsd
Defining the WSDL for your service: the StockQuote WSDL
Next you must build a WSDL file for your service. You can do this in the standard fashion here, but with a few important notations. First, notice the bold highlight in Listing 3. In standard fashion you define the
"types" namespace prefix with the URI associated to your data model. Next, you import the desired stand-alone schema file, StockQuote.xsd, into the WSDL, and finally you make use of the
"types" namespace in the message declarations in the WSDL. Why is it important that we do all of this? Because Castor does not natively support input of
<xsd:schema> nodes embedded in files, in this case from the
<types> section of a WSDL file. We've found that using an external file like this to define your data model and methods is not only cleaner and easier to maintain, but it allows Castor and other tools to interact directly with your schemas as a file.
Listing 3. WSDL file for the StockQuote service
The only other thing of note here is setting up the WSDL to use Document-style encoding. Notice the bold highlight in Listing 4, which is the continuation of the WSDL. These sections are what will tell the WSDL, and correspondingly, WSDL2Java, that you are using a Document-style Web service, and that you should generate document (non-RPC) -style service requests.
Listing 4. WSDL file for the StockQuote service, continued
Generate required code and stubs
Now that you've got your service definition and schema prepared, you're ready to get your hands dirty with Axis and Castor. Both Axis and Castor require some code generation, and you'll be overlaying the generation of Castor's code on top of Axis's to get this "best of both worlds" solution of Axis's Web Service client and server code and Castor's data binding. This first section will show you how to generate the code, and the next section will show you how to reconfigure the generating mappings to get the interoperability you desire.
Building client and service stubs using WSDL2Java
WSDL2Java generates Java classes for data binding of the objects in your data model, client and server stub code for connecting to your methods, and service binding information for the Axis server. We are going to use the latter two parts, the stubs and service binding, and replace the data model code with the code generated by Castor. But to do this, we must first run WSDL2Java to generate stubs and service binding we will need.
To generate the required files with WSDL2Java, run the following command:
%java org.apache.axis.wsdl.WSDL2Java -s "Web Content/StockQuoteService.wsdl"
--NStoPkg
--NStoPkg
-o "Java Source"
The command above will generate the files shown in Listing 5.
Listing 5. WSDL2Java generated files
When you ran the command to generate the files with WSDL2Java, you provided several arguments. The
NStoPkg arguments specify the Java packages you want to use for the different namespaces used in your StockQuote.xsd file, automatically included from the WSDL file by WSDL2Java. You'll use the same mapping when you run Castor to generate the data model classes, in the next step. There is an optional extra parameter to WSDL2Java which we didn't specify in this article, and that is to not use the wrapped style. This option can be specified by adding "-W" to the command line above. What does the wrapped style mean, in WSDL2Java? It controls how WSDL2Java generates method clients and stubs. For a Document-style service, specifying that you don't want to use wrapped with the -W option would map to a method like this being generated in the StockQuoteSOAPBindingStub class:
public GetStockQuoteResponse getStockQuote(GetStockQuote gsq)
In other words, the entire
<GetStockQuote> element, defined in your StockQuote.xsd file and shown in Listing 2, would be handed to your method as a single bean with three fields inside it. On the other hand, for a standard wrapped style service, which is what you are generating in this example, it would map to a method like this:
public Quote getStockQuote(String symbol)
This article will use the wrapped style, as we think it's a little easier to read, and it will save you from writing a few lines of extra code.
Generating a data binding with Castor
Now we're ready to continue and generate the data model data binding with Castor, to replace the one that WSDL2Java created. Since Castor is not Web service-specific, it works with XSD files directly, and not with WSDL files. Hence, you pass it the StockQuote.xsd file, with the following command:
%java org.exolab.castor.builder.SourceGenerator -i "Web Content/StockQuote.xsd"
-package com.ibm.w3.services.stockquote
-nomarshall
-dest "Java Source"
-f
You pass Castor a few arguments on the command line. The
-package argument is the analog of WSDL2Java's NStoPkg argument. The
-nomarshall argument tells Castor to not generate the marshalling framework methods (marshall, unmarshall, validate) in each bean that it generates. In your example, these methods are not needed because the Castor Serializer and Deserializer for Axis is using the Castor Marshaller and Unmarshaller classes directly, which accomplishes the exact same purpose, and so for clarity we've turned them off. If you plan to use the objects as part of a larger system, it might make sense to turn them back on. The
-f arguments just tells Castor to overwrite any existing files without prompting. If you've been paying attention, you might have noticed that this could overwrite some of the data model beans that WSDL2Java created in the previous step. Not to worry, however, because you won't be using those files, so this isn't a problem.
The remaining options for Castor are specified in the castorbuilder.properties file. Most of these settings are not important, but there is one important setting: the
javaclassmapping setting.
# Java class mapping of <xsd:element>'s and <xsd:complexType>'s
#
org.exolab.castor.builder.javaclassmapping=element
This setting determines how Castor generates classes from your schema. Depending on how you wrote your schema, you may want to use
element or
type. The difference between the two is that the
element method creates classes for all elements whose type is a
complexType. Abstract classes are created for all top-level
<complexTypes>. Any elements in the schema whose type is a top-level
<complexType> will have a class created for them that extends the
<complexType's> abstract class. Classes are not created for elements whose type is a
<simpleType> -- instead, underlying Java types are used directly. The other option, the
type method, behaves differently. Instead of creating classes for each element, which extend the classes created for
<complexTypes>, the
type option creates classes for all top-level
<complexTypes> and all inlined anonymous
<complexTypes>. Elements are then formulated as instances of those classes, without separate classes of their own.
These two options are a little complicated to explain, but one option tends to be the natural one for each schema, depending on how your schema is defined. So, for your own schema, experiment with both methods until you come up with classes that you like. For this StockQuote.xsd example, we found that the
element style worked well, and so we used it for generating example data model beans here.
Configure Axis and Castor to work together
It's time for the nitty-gritty: getting Axis to use Castor's generated classes instead of its own. This task is the most critical point of the article, and it shows you how to do the "tough" work of getting Axis to use Castor's classes in both the client and server code stubs. But don't worry -- with these step by step instructions, it won't be tough at all. To get all this off the ground involves changes to the Axis server stubs classes, and to the Axis-generated .wsdd file.
Modifying the server stubs to use Castor classes
To make the stubs use Castor classes, you simply modify the classnames in the stub files. As we have already mentioned, although frequently Castor and WSDL2Java will generate the same classnames, resulting in stubs with the same classnames, this is not always the case. Thus, it is important to check the WSDL2Java client and server stub code to make sure that they are set to return the proper classname for your Castor-generated objects.
Looking at Listing 5 again, notice that two files,
StockQuotePortType.java and
StockQuoteSOAPBindingStub.java are listed as being for the server. For our purposes, we'll have to modify both of these files. The only modification that will be necessary here is checking all of the classnames, and making sure that they point to the Castor-generated classes, rather than the WSDL2Java-generated ones.
As it turns out, in our example, only one class name has changed:
_quote. The class
_quote, generated by WSDL2Java, has changed to
Quote in Castor. They are both still in the same package, since we generated them that way, but we must change the class name in each place that it is referenced.
The change for the file
StockQuotePortType.java, then, is that the line
public com.ibm.w3.services.stockquote._quote getStockQuote(java.lang.String symbol) throws java.rmi.RemoteException;
becomes:
public com.ibm.w3.services.stockquote.Quote getStockQuote(java.lang.String symbol) throws java.rmi.RemoteException;
For the file
StockQuoteSOAPBindingStub.java, we must change a similar line,
public com.ibm.w3.services.stockquote._quote getStockQuote(java.lang.String symbol) throws java.rmi.RemoteException {...
into
public com.ibm.w3.services.stockquote.Quote getStockQuote(java.lang.String symbol) throws java.rmi.RemoteException {...
Now all references in the server code are pointing to the Castor classes. That means we're ready to modify the deploy.wsdd file to make use of these classes and the Castor configuration.
Modifying and deploying the server-config.wsdd file
The second task is modifying the deploy.wsdd. Let's start with an overview of that file, with the sections you'll need to modify highlighted, in Listing 6.
Listing 6. Modified deploy.wsdd for StockQuote service
There are two types of changes we have to make to this file, and one "gotcha" to watch out for. All the changes are on the
<typeMapping> elements. The first change is to modify the classnames listed under the
type attribute to use the Castor-generated classnames instead of the WSDL2Java classnames, if they differ. In our example, for the first two mappings,
ns:changeType and
ns:lastTradeType, the classnames remained the same in Castor, so no change was necessary. However, for the
ns:quote class, the class name did change, from WSDL2Java's
_quote to Castor's
Quote.
The second change to make is to change all of the serializers and deserializers in the
<typeMappings> to
org.apache.axis.encoding.ser.castor.CastorSerializerFactory and
org.apache.axis.encoding.ser.castor.CastorDeserializerFactory, respectively. This tells Axis to use the special, Castor-specific classes for serializing and deserializing the incoming XML for these types, rather than the default
org.apache.axis.encoding.ser.BeanSerializerFactory and
org.apache.axis.encoding.ser.BeanDeserializerFactory classes. These classes are the classes which are included in the latest Axis 1.1 CVS revision, as of this writing, which is exactly why we had you grab the CVS version of Axis in the "Getting the latest Axis and Castor" step.
There's one "gotcha" to watch out for here, and we've highlighted a place where it came up for us in the code above. The "gotcha" has to deal with how Axis and WSDL2Java deals with reading and writing XML. In our tests, we found that WSDL2Java occasionally generated invalid XML by misplacing a few '<' and '>' in the output. The
qname attribute in the final
<typeMapping> element above was one such place. The generated value for the
qname attribute was
"ns:>quote", which clearly isn't valid XML, since '>' is a protected character. In any case, deleting this stray '>' solved all the problems, but keep an eye open for other stray characters like this one.
Deploying the service using the deploy.wsdd file
Now that you've got your deploy.wsdd modified and ready to go, you need to deploy it on the server. You can do this by copying the
<service> element from the deploy.wsdd file to the
WEB-INF/server-config.wsdd file, but you can also use Axis's convenient deployment utility to do it for you. This method also ensures that the
server-config.wsdd file already exists, creating it if it doesn't, and does some error checking, so it's the right way to go.
To run the deployment utility, make sure your working directory is set to the root Axis directory, in our case
WEB-INF, and run the following command:
%java org.apache.axis.utils.Admin server classes/com/ibm/w3/services/stockquote/deploy.wsdd
If the command executes successfully, no errors will be returned, and your service has been deployed. Now, simply restart your server, and you should be ready to go.
Similarly, if you at some point later would like to undeploy your test service, run the command:
%java org.apache.axis.utils.Admin server classes/com/ibm/w3/services/stockquote/undeploy.wsdd
Test out the service on Axis
Now that you've got all the code built, integrated Axis and Castor, and deployed the service in the .wsdd file, it's time to test everything out. Test your install out by pointing it to the endpoint you defined in the .wsdd file, in this case
<context root>/services/StockQuoteSOAPPort. You should see something like Figure 2.
Figure 2. Axis running our StockQuote service
If you can't get this message to display, then something went wrong in your set-up of Axis or the StockQuote service, so look over your configuration and the above steps again until everything's working as it should be.
If you can get this message to display, then you're ready to write some code to make the
getStockQuote method actually do something.
Everything's up and working now, but your server still doesn't do anything -- you haven't implemented the
getStockQuote method yet. With everything set up, doing this is remarkably simple, however. All you need to do is fill in the methods in
StockQuoteSOAPBindingImpl, which correspond one-to-one to the method signatures you created in Listing 2.
Writing the getStockQuote method
Since this is a sample Web service, we're not really going to do much here. But this sample code points out just how easy it is to work with the data binding code generated by Castor and filled in by Axis. Here's our sample code for the
getStockQuote method, in Listing 7.
Listing 7. Sample getStockQuote method, in StockQuoteSOAPBindingImpl.java
What's important to note is that the objects used here are the same ones used on the client, and have already been validated according to their schema by Castor, so any incoming data will be safe to use. If the incoming data doesn't validate, Castor will throw an exception before your method gets called. Similarly, you get the benefits of validation for data you return, as well -- if the data in your returned bean doesn't validate, Castor will throw an exception when Axis attempts to serialize the outgoing bean.
Additionally, although our beans are pretty simple here -- just the
Quote,
Change, and
LastTrade objects -- Castor handles quite admirably much more complicated XML-Schema data models that WSDL2Java tends to have problems with.
Now that you've got everything running with Axis and Castor on the server side, you're ready to build a client.
Using the dynamic Axis Web services client and our knowledge of Castor, we might make a first attempt like that shown in Listing 8.
Listing 8. First attempt at a client for the StockQuote service
This is OK, but it's not too automatic. However, with a little tweaking to the Axis-generated client stubs, we might be able to do better, and have a client that does all the set-up automatically.
Modifying the client stubs to use Castor classes
To make the stubs use Castor classes, simply modify the classnames in the stub files, just like in the server stubs -- although, frequently Castor and WSDL2Java will generate the same classnames, thus resulting in stubs with the same classnames. This is not always the case, so it is important to check and correct.
The file that you'll need to modify is
StockQuoteSOAPBindingStub.java. In this case, WSDL2Java generated the class for the Quote element as
_quote, but Castor generates it as
Quote, so you need to change those all over. Rather than listing every place it is referenced and every line that needs to be changed, which is repetitive and not so useful to read over, we'll leave it up to you to just go through the file and change all references to the class
com.ibm.w3.services.stockquote._quote to
com.ibm.w3.services.stockquote.Quote.
Modifying the client to use Castor serializers rather than Axis serializers
Now, the crucial change: Modifying the client to use the Castor-specific serializer and deserializer classes, rather than the BeanSerializers that the WSDL2Java-generated code uses by default. In the server, we were able to modify a configuration file,
deploy.wsdd, to tell it what class to use to do the serialization and deserialization. The client, unfortunately, doesn't use such a configuration file, so we have to modify it in the code. However, it's a very simple modification, and it's clear that it's doing just what the modification to
deploy.wsdd does on the server side.
The first thing you need to modify to get the client to use the Castor serializer and deserializer classes is to add them to the list of the possible serializers, created in the constructor
public StockQuoteSOAPBindingStub(javax.xml.rpc.Service service) of
StockQuoteSOAPBindingStub.java.
Listing 9. Modified constructor in StockQuoteSOAPBindingStub.java
Listing 9 shows the modification to make to the constructor in bold. The change is relatively self-explanatory: it adds the
CastorSerializerFactory.class and
CastorDeserializerFactory.class as options to be used by the code that follows, which defines the serializer and deserializers to use for incoming and outgoing objects.
The final step in updating the client is to change all the occurrences of
cachedSerFactories.add(beansf) and
cachedDeserFactories.add(beandf) to use Castor instead of Axis's BeanSerializer in the above constructor. This is equivalent to the change we made in
deploy.wsdd, where we listed the Castor serializing and deserializing classes instead of the Axis's BeanSerializer. You'll want to change each occurrence of
beansf and
beandf to
castorsf and
castordf where you are talking about your objects, which in this case, is all occurrences.
For example, one of the changed code blocks will look like Listing 10, with the changes in bold:
Listing 10. Sample modified block in StockQuoteSOAPBindingStub.java
Make this change on each remaining block in the constructor, and then you're done: the Axis generated client is now using Castor serialization and data binding.
Trying the generated client
Now, you can write client code that looks like Listing 11.
Listing 11. The final StockQuote client
It's safer, more automatic, and it's easy to work with. Moreover, you've now got a Web service using Axis for communication and Castor for validation and data binding, end to end.
Axis and Castor: Document-style fun for the whole family
As you can see here, integrating Document-style services, Castor, and Axis isn't terribly difficult, just a bit complicated to set up. But once you're off the ground, you've got a Web service that gains all the flexibility and clarity of Document-style, the robust Web services support of Axis, and the validation and data binding prowess of Castor.
Once you've got all this. Look for more information on these topics in future articles building on integrating Castor and Axis.
Information about download methods
- Download the files used in this article.
- Get the latest copy of Castor from the Castor web site.
- See the Apache Axis documentation which includes a guide for getting Axis set up with WebSphere or another Java container.
- The Axis CVS page contains instructions for downloading and building Axis from CVS or nightly files.
- For instructions on how to get Axis installed and working, turn to the Axis installation instructions documentation page.
- "Reap the benefits of Document-style Web services" (developerWorks, June 2002) offers additional insight on the benefits of Document-style services.
- This series, Finding your way through Web service standards (developerWorks, October 2002), explains the intricacies of SOAP.
- Deploying Web services with WSDL (developerWorks, November 2001), provides an introduction to defining a WSDL for your Web service.
- The basics of using XML-Schema to define elements (developerWorks, August 2000) will help you get off the ground with defining the XML-Schema for your service's data.
Kevin Gibbs is a Software Engineer with IBM's Advanced Internet Technologies in Cambridge, MA. He previously worked on the SashXB for Linux scripting environment, and currently investigates various Internet technologies, including Web services and blogging architectures. You can reach Kevin at kagibbs at us.ibm.com.
Brian Goodman is an IT Architect focusing on expertise, communities and collaboration on the IBM Intranet. You can reach Brian at bgoodman at us.ibm.com. | http://www.ibm.com/developerworks/library/ws-castor/ | crawl-002 | refinedweb | 5,639 | 53.31 |
NAME
sigprocmask - examine and change blocked signals
SYNOPSIS
#include <signal.h> int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);
DESCRIPTION
sigprocmask() is used to change the signal mask, the set of currently blocked signals. (it is not NULL). The use of sigprocmask() is unspecified in a multithreaded process; see pthread_sigmask(3).
RETURN VALUE
sigprocmask() returns 0 on success and -1 on error.
ERRORS
EINVAL The value specified in how was invalid.
CONFORMING TO
POSIX.1-2001.
NOTES ALSO
kill(2), pause(2), sigaction(2), signal(2), sigpending(2), sigqueue(2), sigsuspend(2), pthread_sigmask(3), sigsetops(3), signal(7)
COLOPHON
This page is part of release 3.01 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. | http://manpages.ubuntu.com/manpages/intrepid/man2/sigprocmask.2.html | CC-MAIN-2014-52 | refinedweb | 128 | 60.21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.